From 4872496ee54f846183b54c0301ef05ea49f12e3a Mon Sep 17 00:00:00 2001 From: PythonSdkPipelines Date: Tue, 11 Oct 2022 02:41:45 +0000 Subject: [PATCH] code and test --- .../azure-mgmt-authorization/CHANGELOG.md | 56 + .../azure-mgmt-authorization/MANIFEST.in | 1 + .../azure-mgmt-authorization/_meta.json | 10 +- .../azure/mgmt/authorization/__init__.py | 4 + .../_authorization_management_client.py | 534 ++- .../mgmt/authorization/_configuration.py | 16 +- .../mgmt/authorization/_serialization.py | 2006 +++++++++ .../azure/mgmt/authorization/_version.py | 2 +- .../aio/_authorization_management_client.py | 526 ++- .../mgmt/authorization/aio/_configuration.py | 8 +- .../azure/mgmt/authorization/models.py | 5 + .../authorization/v2015_06_01/__init__.py | 13 +- .../_authorization_management_client.py | 90 +- .../v2015_06_01/_configuration.py | 58 +- .../authorization/v2015_06_01/_metadata.json | 33 +- .../mgmt/authorization/v2015_06_01/_patch.py | 20 + .../mgmt/authorization/v2015_06_01/_vendor.py | 27 + .../authorization/v2015_06_01/_version.py | 2 +- .../authorization/v2015_06_01/aio/__init__.py | 13 +- .../aio/_authorization_management_client.py | 78 +- .../v2015_06_01/aio/_configuration.py | 55 +- .../authorization/v2015_06_01/aio/_patch.py | 20 + .../v2015_06_01/aio/operations/__init__.py | 8 +- .../_classic_administrators_operations.py | 133 +- .../v2015_06_01/aio/operations/_patch.py | 20 + .../v2015_06_01/models/__init__.py | 32 +- .../v2015_06_01/models/_models.py | 163 - .../v2015_06_01/models/_models_py3.py | 157 +- .../v2015_06_01/models/_patch.py | 20 + .../v2015_06_01/operations/__init__.py | 8 +- .../_classic_administrators_operations.py | 171 +- .../v2015_06_01/operations/_patch.py | 20 + .../authorization/v2015_07_01/__init__.py | 13 +- .../_authorization_management_client.py | 129 +- .../v2015_07_01/_configuration.py | 58 +- .../authorization/v2015_07_01/_metadata.json | 33 +- .../mgmt/authorization/v2015_07_01/_patch.py | 20 + .../mgmt/authorization/v2015_07_01/_vendor.py | 27 + .../authorization/v2015_07_01/_version.py | 2 +- .../authorization/v2015_07_01/aio/__init__.py | 13 +- .../aio/_authorization_management_client.py | 117 +- .../v2015_07_01/aio/_configuration.py | 55 +- .../authorization/v2015_07_01/aio/_patch.py | 20 + .../v2015_07_01/aio/operations/__init__.py | 18 +- .../_classic_administrators_operations.py | 133 +- .../_global_administrator_operations.py | 102 +- .../v2015_07_01/aio/operations/_patch.py | 20 + .../aio/operations/_permissions_operations.py | 233 +- ...provider_operations_metadata_operations.py | 204 +- .../_role_assignments_operations.py | 996 +++-- .../_role_definitions_operations.py | 493 ++- .../v2015_07_01/models/__init__.py | 107 +- .../v2015_07_01/models/_models.py | 595 --- .../v2015_07_01/models/_models_py3.py | 667 +-- .../v2015_07_01/models/_patch.py | 20 + .../v2015_07_01/operations/__init__.py | 18 +- .../_classic_administrators_operations.py | 171 +- .../_global_administrator_operations.py | 131 +- .../v2015_07_01/operations/_patch.py | 20 + .../operations/_permissions_operations.py | 324 +- ...provider_operations_metadata_operations.py | 265 +- .../_role_assignments_operations.py | 1312 ++++-- .../_role_definitions_operations.py | 632 ++- .../v2018_01_01_preview/__init__.py | 13 +- .../_authorization_management_client.py | 114 +- .../v2018_01_01_preview/_configuration.py | 58 +- .../v2018_01_01_preview/_metadata.json | 33 +- .../v2018_01_01_preview/_patch.py | 20 + .../v2018_01_01_preview/_vendor.py | 27 + .../v2018_01_01_preview/_version.py | 2 +- .../v2018_01_01_preview/aio/__init__.py | 13 +- .../aio/_authorization_management_client.py | 102 +- .../v2018_01_01_preview/aio/_configuration.py | 55 +- .../v2018_01_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 14 +- .../aio/operations/_patch.py | 20 + .../aio/operations/_permissions_operations.py | 233 +- ...provider_operations_metadata_operations.py | 204 +- .../_role_assignments_operations.py | 997 +++-- .../_role_definitions_operations.py | 494 ++- .../v2018_01_01_preview/models/__init__.py | 87 +- .../v2018_01_01_preview/models/_models.py | 521 --- .../v2018_01_01_preview/models/_models_py3.py | 604 +-- .../v2018_01_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 14 +- .../v2018_01_01_preview/operations/_patch.py | 20 + .../operations/_permissions_operations.py | 328 +- ...provider_operations_metadata_operations.py | 267 +- .../_role_assignments_operations.py | 1315 ++++-- .../_role_definitions_operations.py | 633 ++- .../v2018_05_01_preview/__init__.py | 13 +- .../_authorization_management_client.py | 161 +- .../v2018_05_01_preview/_configuration.py | 58 +- .../v2018_05_01_preview/_metadata.json | 33 +- .../v2018_05_01_preview/_patch.py | 20 + .../v2018_05_01_preview/_vendor.py | 27 + .../v2018_05_01_preview/_version.py | 2 +- .../v2018_05_01_preview/aio/__init__.py | 13 +- .../aio/_authorization_management_client.py | 149 +- .../v2018_05_01_preview/aio/_configuration.py | 55 +- .../v2018_05_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 32 +- ...cess_review_default_settings_operations.py | 240 +- ...ss_review_instance_decisions_operations.py | 143 +- ...review_instance_my_decisions_operations.py | 385 +- .../_access_review_instance_operations.py | 411 +- ...ces_assigned_for_my_approval_operations.py | 212 +- .../_access_review_instances_operations.py | 215 +- ...ons_assigned_for_my_approval_operations.py | 126 +- ..._review_schedule_definitions_operations.py | 471 +- .../aio/operations/_operations.py | 125 +- .../aio/operations/_patch.py | 20 + .../v2018_05_01_preview/models/__init__.py | 156 +- .../_authorization_management_client_enums.py | 97 +- .../v2018_05_01_preview/models/_models.py | 1204 ----- .../v2018_05_01_preview/models/_models_py3.py | 1495 ++++--- .../v2018_05_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 32 +- ...cess_review_default_settings_operations.py | 306 +- ...ss_review_instance_decisions_operations.py | 184 +- ...review_instance_my_decisions_operations.py | 487 ++- .../_access_review_instance_operations.py | 575 ++- ...ces_assigned_for_my_approval_operations.py | 274 +- .../_access_review_instances_operations.py | 282 +- ...ons_assigned_for_my_approval_operations.py | 157 +- ..._review_schedule_definitions_operations.py | 628 ++- .../operations/_operations.py | 156 +- .../v2018_05_01_preview/operations/_patch.py | 20 + .../v2018_07_01_preview/__init__.py | 13 +- .../_authorization_management_client.py | 90 +- .../v2018_07_01_preview/_configuration.py | 58 +- .../v2018_07_01_preview/_metadata.json | 33 +- .../v2018_07_01_preview/_patch.py | 20 + .../v2018_07_01_preview/_vendor.py | 27 + .../v2018_07_01_preview/_version.py | 2 +- .../v2018_07_01_preview/aio/__init__.py | 13 +- .../aio/_authorization_management_client.py | 78 +- .../v2018_07_01_preview/aio/_configuration.py | 55 +- .../v2018_07_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 8 +- .../_deny_assignments_operations.py | 562 +-- .../aio/operations/_patch.py | 20 + .../v2018_07_01_preview/models/__init__.py | 47 +- .../v2018_07_01_preview/models/_models.py | 290 -- .../v2018_07_01_preview/models/_models_py3.py | 313 +- .../v2018_07_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 8 +- .../_deny_assignments_operations.py | 766 ++-- .../v2018_07_01_preview/operations/_patch.py | 20 + .../v2018_09_01_preview/__init__.py | 13 +- .../_authorization_management_client.py | 89 +- .../v2018_09_01_preview/_configuration.py | 58 +- .../v2018_09_01_preview/_metadata.json | 33 +- .../v2018_09_01_preview/_patch.py | 20 + .../v2018_09_01_preview/_vendor.py | 27 + .../v2018_09_01_preview/_version.py | 2 +- .../v2018_09_01_preview/aio/__init__.py | 13 +- .../aio/_authorization_management_client.py | 77 +- .../v2018_09_01_preview/aio/_configuration.py | 55 +- .../v2018_09_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 8 +- .../aio/operations/_patch.py | 20 + .../_role_assignments_operations.py | 997 +++-- .../v2018_09_01_preview/models/__init__.py | 48 +- .../_authorization_management_client_enums.py | 25 +- .../v2018_09_01_preview/models/_models.py | 247 -- .../v2018_09_01_preview/models/_models_py3.py | 256 +- .../v2018_09_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 8 +- .../v2018_09_01_preview/operations/_patch.py | 20 + .../_role_assignments_operations.py | 1315 ++++-- .../v2019_08_01_preview/__init__.py | 13 +- .../_authorization_management_client.py | 89 +- .../v2019_08_01_preview/_configuration.py | 58 +- .../v2019_08_01_preview/_metadata.json | 33 +- .../v2019_08_01_preview/_patch.py | 20 + .../v2019_08_01_preview/_vendor.py | 27 + .../v2019_08_01_preview/_version.py | 2 +- .../v2019_08_01_preview/aio/__init__.py | 13 +- .../aio/_authorization_management_client.py | 77 +- .../v2019_08_01_preview/aio/_configuration.py | 55 +- .../v2019_08_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 8 +- .../aio/operations/_patch.py | 20 + .../_role_assignment_metrics_operations.py | 112 +- .../v2019_08_01_preview/models/__init__.py | 27 +- .../v2019_08_01_preview/models/_models.py | 145 - .../v2019_08_01_preview/models/_models_py3.py | 113 +- .../v2019_08_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 8 +- .../v2019_08_01_preview/operations/_patch.py | 20 + .../_role_assignment_metrics_operations.py | 148 +- .../v2020_04_01_preview/__init__.py | 13 +- .../_authorization_management_client.py | 89 +- .../v2020_04_01_preview/_configuration.py | 58 +- .../v2020_04_01_preview/_metadata.json | 33 +- .../v2020_04_01_preview/_patch.py | 20 + .../v2020_04_01_preview/_vendor.py | 27 + .../v2020_04_01_preview/_version.py | 2 +- .../v2020_04_01_preview/aio/__init__.py | 13 +- .../aio/_authorization_management_client.py | 77 +- .../v2020_04_01_preview/aio/_configuration.py | 55 +- .../v2020_04_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 8 +- .../aio/operations/_patch.py | 20 + .../_role_assignments_operations.py | 1048 +++-- .../v2020_04_01_preview/models/__init__.py | 48 +- .../_authorization_management_client_enums.py | 25 +- .../v2020_04_01_preview/models/_models.py | 301 -- .../v2020_04_01_preview/models/_models_py3.py | 364 +- .../v2020_04_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 8 +- .../v2020_04_01_preview/operations/_patch.py | 20 + .../_role_assignments_operations.py | 1398 ++++-- .../authorization/v2020_10_01/__init__.py | 24 + .../_authorization_management_client.py | 148 + .../v2020_10_01/_configuration.py | 64 + .../authorization/v2020_10_01/_metadata.json | 98 + .../mgmt/authorization/v2020_10_01/_patch.py | 20 + .../mgmt/authorization/v2020_10_01/_vendor.py | 27 + .../authorization/v2020_10_01/_version.py | 9 + .../authorization/v2020_10_01/aio/__init__.py | 21 + .../aio/_authorization_management_client.py | 145 + .../v2020_10_01/aio/_configuration.py | 61 + .../authorization/v2020_10_01/aio/_patch.py | 20 + .../v2020_10_01/aio/operations/__init__.py | 35 + .../_eligible_child_resources_operations.py | 137 + .../v2020_10_01/aio/operations/_patch.py | 20 + ...ssignment_schedule_instances_operations.py | 200 + ...assignment_schedule_requests_operations.py | 556 +++ .../_role_assignment_schedules_operations.py | 200 + ...igibility_schedule_instances_operations.py | 203 + ...ligibility_schedule_requests_operations.py | 556 +++ .../_role_eligibility_schedules_operations.py | 200 + .../_role_management_policies_operations.py | 387 ++ ...anagement_policy_assignments_operations.py | 390 ++ .../v2020_10_01/models/__init__.py | 149 + .../_authorization_management_client_enums.py | 140 + .../v2020_10_01/models/_models_py3.py | 3118 +++++++++++++ .../v2020_10_01/models/_patch.py | 20 + .../v2020_10_01/operations/__init__.py | 35 + .../_eligible_child_resources_operations.py | 164 + .../v2020_10_01/operations/_patch.py | 20 + ...ssignment_schedule_instances_operations.py | 258 ++ ...assignment_schedule_requests_operations.py | 704 +++ .../_role_assignment_schedules_operations.py | 256 ++ ...igibility_schedule_instances_operations.py | 258 ++ ...ligibility_schedule_requests_operations.py | 704 +++ .../_role_eligibility_schedules_operations.py | 256 ++ .../_role_management_policies_operations.py | 492 +++ ...anagement_policy_assignments_operations.py | 504 +++ .../mgmt/authorization/v2020_10_01/py.typed | 1 + .../v2020_10_01_preview/__init__.py | 13 +- .../_authorization_management_client.py | 166 +- .../v2020_10_01_preview/_configuration.py | 58 +- .../v2020_10_01_preview/_metadata.json | 33 +- .../v2020_10_01_preview/_patch.py | 20 + .../v2020_10_01_preview/_vendor.py | 27 + .../v2020_10_01_preview/_version.py | 2 +- .../v2020_10_01_preview/aio/__init__.py | 13 +- .../aio/_authorization_management_client.py | 154 +- .../v2020_10_01_preview/aio/_configuration.py | 55 +- .../v2020_10_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 26 +- .../_eligible_child_resources_operations.py | 140 +- .../aio/operations/_patch.py | 20 + ...ssignment_schedule_instances_operations.py | 207 +- ...assignment_schedule_requests_operations.py | 443 +- .../_role_assignment_schedules_operations.py | 205 +- .../_role_assignments_operations.py | 1345 +++--- ...igibility_schedule_instances_operations.py | 209 +- ...ligibility_schedule_requests_operations.py | 441 +- .../_role_eligibility_schedules_operations.py | 205 +- .../_role_management_policies_operations.py | 417 +- ...anagement_policy_assignments_operations.py | 423 +- .../v2020_10_01_preview/models/__init__.py | 371 +- .../_authorization_management_client_enums.py | 101 +- .../v2020_10_01_preview/models/_models.py | 2581 ----------- .../v2020_10_01_preview/models/_models_py3.py | 3187 ++++++++------ .../v2020_10_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 26 +- .../_eligible_child_resources_operations.py | 178 +- .../v2020_10_01_preview/operations/_patch.py | 20 + ...ssignment_schedule_instances_operations.py | 271 +- ...assignment_schedule_requests_operations.py | 575 ++- .../_role_assignment_schedules_operations.py | 271 +- .../_role_assignments_operations.py | 1760 +++++--- ...igibility_schedule_instances_operations.py | 270 +- ...ligibility_schedule_requests_operations.py | 573 ++- .../_role_eligibility_schedules_operations.py | 271 +- .../_role_management_policies_operations.py | 538 ++- ...anagement_policy_assignments_operations.py | 553 ++- .../v2021_01_01_preview/__init__.py | 13 +- .../_authorization_management_client.py | 128 +- .../v2021_01_01_preview/_configuration.py | 55 +- .../v2021_01_01_preview/_metadata.json | 27 +- .../v2021_01_01_preview/_patch.py | 20 + .../v2021_01_01_preview/_vendor.py | 27 + .../v2021_01_01_preview/_version.py | 2 +- .../v2021_01_01_preview/aio/__init__.py | 13 +- .../aio/_authorization_management_client.py | 122 +- .../v2021_01_01_preview/aio/_configuration.py | 52 +- .../v2021_01_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 20 +- .../aio/operations/_operations.py | 125 +- .../aio/operations/_patch.py | 20 + .../_role_assignment_approval_operations.py | 200 +- ...ole_assignment_approval_step_operations.py | 418 +- ...le_assignment_approval_steps_operations.py | 120 +- ...ope_role_assignment_approval_operations.py | 213 +- ...ole_assignment_approval_step_operations.py | 459 +- ...le_assignment_approval_steps_operations.py | 125 +- .../v2021_01_01_preview/models/__init__.py | 71 +- .../_authorization_management_client_enums.py | 40 +- .../v2021_01_01_preview/models/_models.py | 416 -- .../v2021_01_01_preview/models/_models_py3.py | 406 +- .../v2021_01_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 20 +- .../operations/_operations.py | 156 +- .../v2021_01_01_preview/operations/_patch.py | 20 + .../_role_assignment_approval_operations.py | 257 +- ...ole_assignment_approval_step_operations.py | 521 ++- ...le_assignment_approval_steps_operations.py | 152 +- ...ope_role_assignment_approval_operations.py | 274 +- ...ole_assignment_approval_step_operations.py | 572 ++- ...le_assignment_approval_steps_operations.py | 160 +- .../v2021_03_01_preview/__init__.py | 13 +- .../_authorization_management_client.py | 161 +- .../v2021_03_01_preview/_configuration.py | 58 +- .../v2021_03_01_preview/_metadata.json | 33 +- .../v2021_03_01_preview/_patch.py | 20 + .../v2021_03_01_preview/_vendor.py | 27 + .../v2021_03_01_preview/_version.py | 2 +- .../v2021_03_01_preview/aio/__init__.py | 13 +- .../aio/_authorization_management_client.py | 149 +- .../v2021_03_01_preview/aio/_configuration.py | 55 +- .../v2021_03_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 32 +- ...cess_review_default_settings_operations.py | 240 +- ...ss_review_instance_decisions_operations.py | 149 +- ...review_instance_my_decisions_operations.py | 391 +- .../_access_review_instance_operations.py | 411 +- ...ces_assigned_for_my_approval_operations.py | 216 +- .../_access_review_instances_operations.py | 219 +- ...ons_assigned_for_my_approval_operations.py | 134 +- ..._review_schedule_definitions_operations.py | 477 +- .../aio/operations/_operations.py | 125 +- .../aio/operations/_patch.py | 20 + .../v2021_03_01_preview/models/__init__.py | 169 +- .../_authorization_management_client_enums.py | 109 +- .../v2021_03_01_preview/models/_models.py | 1352 ------ .../v2021_03_01_preview/models/_models_py3.py | 1644 ++++--- .../v2021_03_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 32 +- ...cess_review_default_settings_operations.py | 306 +- ...ss_review_instance_decisions_operations.py | 192 +- ...review_instance_my_decisions_operations.py | 497 ++- .../_access_review_instance_operations.py | 575 ++- ...ces_assigned_for_my_approval_operations.py | 278 +- .../_access_review_instances_operations.py | 286 +- ...ons_assigned_for_my_approval_operations.py | 167 +- ..._review_schedule_definitions_operations.py | 636 ++- .../operations/_operations.py | 156 +- .../v2021_03_01_preview/operations/_patch.py | 20 + .../v2021_07_01_preview/__init__.py | 24 + .../_authorization_management_client.py | 173 + .../v2021_07_01_preview/_configuration.py | 69 + .../v2021_07_01_preview/_metadata.json | 112 + .../v2021_07_01_preview/_patch.py | 20 + .../v2021_07_01_preview/_vendor.py | 27 + .../v2021_07_01_preview/_version.py | 9 + .../v2021_07_01_preview/aio/__init__.py | 21 + .../aio/_authorization_management_client.py | 170 + .../v2021_07_01_preview/aio/_configuration.py | 66 + .../v2021_07_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 45 + ...cess_review_default_settings_operations.py | 213 + ...instance_contacted_reviewers_operations.py | 136 + ...ss_review_instance_decisions_operations.py | 142 + ...review_instance_my_decisions_operations.py | 357 ++ .../_access_review_instance_operations.py | 341 ++ ...ces_assigned_for_my_approval_operations.py | 200 + .../_access_review_instances_operations.py | 342 ++ ...ons_assigned_for_my_approval_operations.py | 135 + ..._review_schedule_definitions_operations.py | 432 ++ .../aio/operations/_operations.py | 126 + .../aio/operations/_patch.py | 20 + ...instance_contacted_reviewers_operations.py | 135 + .../v2021_07_01_preview/models/__init__.py | 95 + .../_authorization_management_client_enums.py | 162 + .../v2021_07_01_preview/models/_models_py3.py | 2041 +++++++++ .../v2021_07_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 45 + ...cess_review_default_settings_operations.py | 273 ++ ...instance_contacted_reviewers_operations.py | 168 + ...ss_review_instance_decisions_operations.py | 178 + ...review_instance_my_decisions_operations.py | 448 ++ .../_access_review_instance_operations.py | 488 +++ ...ces_assigned_for_my_approval_operations.py | 256 ++ .../_access_review_instances_operations.py | 433 ++ ...ons_assigned_for_my_approval_operations.py | 157 + ..._review_schedule_definitions_operations.py | 572 +++ .../operations/_operations.py | 148 + .../v2021_07_01_preview/operations/_patch.py | 20 + ...instance_contacted_reviewers_operations.py | 166 + .../v2021_07_01_preview/py.typed | 1 + .../v2021_12_01_preview/__init__.py | 24 + .../_authorization_management_client.py | 308 ++ .../v2021_12_01_preview/_configuration.py | 63 + .../v2021_12_01_preview/_metadata.json | 131 + .../v2021_12_01_preview/_patch.py | 20 + .../v2021_12_01_preview/_vendor.py | 27 + .../v2021_12_01_preview/_version.py | 9 + .../v2021_12_01_preview/aio/__init__.py | 21 + .../aio/_authorization_management_client.py | 305 ++ .../v2021_12_01_preview/aio/_configuration.py | 60 + .../v2021_12_01_preview/aio/_patch.py | 20 + .../aio/operations/__init__.py | 89 + ...cess_review_default_settings_operations.py | 213 + ..._history_definition_instance_operations.py | 114 + ...history_definition_instances_operations.py | 126 + ...ss_review_history_definition_operations.py | 230 + ...s_review_history_definitions_operations.py | 187 + ...instance_contacted_reviewers_operations.py | 131 + ...ss_review_instance_decisions_operations.py | 137 + ...review_instance_my_decisions_operations.py | 352 ++ .../_access_review_instance_operations.py | 341 ++ ...ces_assigned_for_my_approval_operations.py | 195 + .../_access_review_instances_operations.py | 337 ++ ...ons_assigned_for_my_approval_operations.py | 130 + ..._review_schedule_definitions_operations.py | 427 ++ .../_alert_configurations_operations.py | 316 ++ .../_alert_definitions_operations.py | 187 + .../operations/_alert_incidents_operations.py | 255 ++ .../operations/_alert_operation_operations.py | 162 + .../aio/operations/_alerts_operations.py | 549 +++ .../aio/operations/_operations.py | 121 + .../aio/operations/_patch.py | 20 + ...cess_review_default_settings_operations.py | 226 + ..._history_definition_instance_operations.py | 118 + ...history_definition_instances_operations.py | 130 + ...ss_review_history_definition_operations.py | 249 ++ ...s_review_history_definitions_operations.py | 196 + ...instance_contacted_reviewers_operations.py | 133 + ...ss_review_instance_decisions_operations.py | 139 + ...scope_access_review_instance_operations.py | 436 ++ ...cope_access_review_instances_operations.py | 352 ++ ..._review_schedule_definitions_operations.py | 451 ++ ...instance_contacted_reviewers_operations.py | 130 + .../v2021_12_01_preview/models/__init__.py | 165 + .../_authorization_management_client_enums.py | 199 + .../v2021_12_01_preview/models/_models_py3.py | 3868 +++++++++++++++++ .../v2021_12_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 89 + ...cess_review_default_settings_operations.py | 273 ++ ..._history_definition_instance_operations.py | 148 + ...history_definition_instances_operations.py | 157 + ...ss_review_history_definition_operations.py | 292 ++ ...s_review_history_definitions_operations.py | 244 ++ ...instance_contacted_reviewers_operations.py | 163 + ...ss_review_instance_decisions_operations.py | 173 + ...review_instance_my_decisions_operations.py | 443 ++ .../_access_review_instance_operations.py | 488 +++ ...ces_assigned_for_my_approval_operations.py | 251 ++ .../_access_review_instances_operations.py | 428 ++ ...ons_assigned_for_my_approval_operations.py | 152 + ..._review_schedule_definitions_operations.py | 567 +++ .../_alert_configurations_operations.py | 397 ++ .../_alert_definitions_operations.py | 243 ++ .../operations/_alert_incidents_operations.py | 339 ++ .../operations/_alert_operation_operations.py | 216 + .../operations/_alerts_operations.py | 673 +++ .../operations/_operations.py | 143 + .../v2021_12_01_preview/operations/_patch.py | 20 + ...cess_review_default_settings_operations.py | 280 ++ ..._history_definition_instance_operations.py | 150 + ...history_definition_instances_operations.py | 161 + ...ss_review_history_definition_operations.py | 308 ++ ...s_review_history_definitions_operations.py | 247 ++ ...instance_contacted_reviewers_operations.py | 165 + ...ss_review_instance_decisions_operations.py | 175 + ...scope_access_review_instance_operations.py | 581 +++ ...cope_access_review_instances_operations.py | 443 ++ ..._review_schedule_definitions_operations.py | 588 +++ ...instance_contacted_reviewers_operations.py | 161 + .../v2021_12_01_preview/py.typed | 1 + .../authorization/v2022_04_01/__init__.py | 24 + .../_authorization_management_client.py | 125 + .../v2022_04_01/_configuration.py | 69 + .../authorization/v2022_04_01/_metadata.json | 106 + .../mgmt/authorization/v2022_04_01/_patch.py | 20 + .../mgmt/authorization/v2022_04_01/_vendor.py | 27 + .../authorization/v2022_04_01/_version.py | 9 + .../authorization/v2022_04_01/aio/__init__.py | 21 + .../aio/_authorization_management_client.py | 122 + .../v2022_04_01/aio/_configuration.py | 66 + .../authorization/v2022_04_01/aio/_patch.py | 20 + .../v2022_04_01/aio/operations/__init__.py | 27 + .../_deny_assignments_operations.py | 557 +++ .../v2022_04_01/aio/operations/_patch.py | 20 + .../aio/operations/_permissions_operations.py | 229 + ...provider_operations_metadata_operations.py | 191 + .../_role_assignments_operations.py | 1001 +++++ .../_role_definitions_operations.py | 449 ++ .../v2022_04_01/models/__init__.py | 99 + .../_authorization_management_client_enums.py | 76 + .../v2022_04_01/models/_models_py3.py | 1733 ++++++++ .../v2022_04_01/models/_patch.py | 20 + .../v2022_04_01/operations/__init__.py | 27 + .../_deny_assignments_operations.py | 737 ++++ .../v2022_04_01/operations/_patch.py | 20 + .../operations/_permissions_operations.py | 304 ++ ...provider_operations_metadata_operations.py | 244 ++ .../_role_assignments_operations.py | 1318 ++++++ .../_role_definitions_operations.py | 573 +++ .../mgmt/authorization/v2022_04_01/py.typed | 1 + ...gmtAuthorizationtest_list_by_resource.json | 56 +- shared_requirements.txt | 4 +- 518 files changed, 88134 insertions(+), 29239 deletions(-) create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_serialization.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/_patch.py delete mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_models.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_patch.py delete mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_models.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_patch.py delete mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_models.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_patch.py delete mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_models.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/_patch.py delete mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_models.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/_patch.py delete mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_models.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/_patch.py delete mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_models.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/_patch.py delete mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_models.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_authorization_management_client.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_configuration.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_metadata.json create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_version.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_authorization_management_client.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_configuration.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_eligible_child_resources_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedule_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedule_requests_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedules_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedule_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedule_requests_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedules_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_management_policies_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_management_policy_assignments_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_authorization_management_client_enums.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_models_py3.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_eligible_child_resources_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedule_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedule_requests_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedules_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedule_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedule_requests_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedules_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_management_policies_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_management_policy_assignments_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/py.typed create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_patch.py delete mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_models.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_patch.py delete mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_models.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_patch.py delete mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_models.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_authorization_management_client.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_configuration.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_metadata.json create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_version.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_authorization_management_client.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_configuration.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_default_settings_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_contacted_reviewers_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_decisions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_schedule_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_authorization_management_client_enums.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_models_py3.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_default_settings_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_contacted_reviewers_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_decisions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_my_decisions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_schedule_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/py.typed create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_authorization_management_client.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_configuration.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_metadata.json create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_version.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_authorization_management_client.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_configuration.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_default_settings_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_instance_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_contacted_reviewers_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_decisions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_schedule_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_configurations_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_incidents_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_operation_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alerts_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_default_settings_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_instance_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_contacted_reviewers_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_decisions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_schedule_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_authorization_management_client_enums.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_models_py3.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_default_settings_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_instance_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_contacted_reviewers_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_decisions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_my_decisions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_schedule_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_configurations_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_incidents_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_operation_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alerts_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_default_settings_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_instance_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_contacted_reviewers_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_decisions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instances_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_schedule_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/py.typed create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_authorization_management_client.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_configuration.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_metadata.json create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_vendor.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_version.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_authorization_management_client.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_configuration.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_deny_assignments_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_permissions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_provider_operations_metadata_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_role_assignments_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_role_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_authorization_management_client_enums.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_models_py3.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/__init__.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_deny_assignments_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_patch.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_permissions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_provider_operations_metadata_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_role_assignments_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_role_definitions_operations.py create mode 100644 sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/py.typed diff --git a/sdk/authorization/azure-mgmt-authorization/CHANGELOG.md b/sdk/authorization/azure-mgmt-authorization/CHANGELOG.md index 9a010207172..c2475b79334 100644 --- a/sdk/authorization/azure-mgmt-authorization/CHANGELOG.md +++ b/sdk/authorization/azure-mgmt-authorization/CHANGELOG.md @@ -1,5 +1,61 @@ # Release History +## 3.0.0 (2022-10-11) + +### Features Added + + - Added operation AccessReviewInstancesOperations.create + - Added operation group AccessReviewHistoryDefinitionInstanceOperations + - Added operation group AccessReviewHistoryDefinitionInstancesOperations + - Added operation group AccessReviewHistoryDefinitionOperations + - Added operation group AccessReviewHistoryDefinitionsOperations + - Added operation group AccessReviewInstanceContactedReviewersOperations + - Added operation group AlertConfigurationsOperations + - Added operation group AlertDefinitionsOperations + - Added operation group AlertIncidentsOperations + - Added operation group AlertOperationOperations + - Added operation group AlertsOperations + - Added operation group ScopeAccessReviewDefaultSettingsOperations + - Added operation group ScopeAccessReviewHistoryDefinitionInstanceOperations + - Added operation group ScopeAccessReviewHistoryDefinitionInstancesOperations + - Added operation group ScopeAccessReviewHistoryDefinitionOperations + - Added operation group ScopeAccessReviewHistoryDefinitionsOperations + - Added operation group ScopeAccessReviewInstanceContactedReviewersOperations + - Added operation group ScopeAccessReviewInstanceDecisionsOperations + - Added operation group ScopeAccessReviewInstanceOperations + - Added operation group ScopeAccessReviewInstancesOperations + - Added operation group ScopeAccessReviewScheduleDefinitionsOperations + - Added operation group TenantLevelAccessReviewInstanceContactedReviewersOperations + - Model AccessReviewDecision has a new parameter insights + - Model AccessReviewDecision has a new parameter membership_types + - Model AccessReviewDecisionProperties has a new parameter insights + - Model AccessReviewDecisionProperties has a new parameter membership_types + - Model AccessReviewDefaultSettings has a new parameter recommendation_look_back_duration + - Model AccessReviewInstance has a new parameter backup_reviewers + - Model AccessReviewInstance has a new parameter reviewers + - Model AccessReviewInstance has a new parameter reviewers_type + - Model AccessReviewScheduleDefinition has a new parameter exclude_resource_id + - Model AccessReviewScheduleDefinition has a new parameter exclude_role_definition_id + - Model AccessReviewScheduleDefinition has a new parameter expand_nested_memberships + - Model AccessReviewScheduleDefinition has a new parameter include_access_below_resource + - Model AccessReviewScheduleDefinition has a new parameter include_inherited_access + - Model AccessReviewScheduleDefinition has a new parameter recommendation_look_back_duration + - Model AccessReviewScheduleDefinitionProperties has a new parameter exclude_resource_id + - Model AccessReviewScheduleDefinitionProperties has a new parameter exclude_role_definition_id + - Model AccessReviewScheduleDefinitionProperties has a new parameter expand_nested_memberships + - Model AccessReviewScheduleDefinitionProperties has a new parameter include_access_below_resource + - Model AccessReviewScheduleDefinitionProperties has a new parameter include_inherited_access + - Model AccessReviewScheduleDefinitionProperties has a new parameter recommendation_look_back_duration + - Model AccessReviewScheduleSettings has a new parameter recommendation_look_back_duration + - Model DenyAssignmentPermission has a new parameter condition + - Model DenyAssignmentPermission has a new parameter condition_version + +### Breaking Changes + + - Operation RoleAssignmentsOperations.list_for_scope has a new parameter skip_token + - Removed operation RoleAssignmentsOperations.validate + - Removed operation RoleAssignmentsOperations.validate_by_id + ## 2.0.0 (2021-09-26) **Features** diff --git a/sdk/authorization/azure-mgmt-authorization/MANIFEST.in b/sdk/authorization/azure-mgmt-authorization/MANIFEST.in index f309d2f0d9c..70e792b1120 100644 --- a/sdk/authorization/azure-mgmt-authorization/MANIFEST.in +++ b/sdk/authorization/azure-mgmt-authorization/MANIFEST.in @@ -1,5 +1,6 @@ include _meta.json recursive-include tests *.py *.json +recursive-include samples *.py *.md include *.md include azure/__init__.py include azure/mgmt/__init__.py diff --git a/sdk/authorization/azure-mgmt-authorization/_meta.json b/sdk/authorization/azure-mgmt-authorization/_meta.json index 93b83d2d442..9c7eec68d8a 100644 --- a/sdk/authorization/azure-mgmt-authorization/_meta.json +++ b/sdk/authorization/azure-mgmt-authorization/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.4.5", + "autorest": "3.9.2", "use": [ - "@autorest/python@5.8.4", - "@autorest/modelerfour@4.19.2" + "@autorest/python@6.1.9", + "@autorest/modelerfour@4.24.3" ], - "commit": "ac1c84fa8c897975b88a38a66dd64d54312a1422", + "commit": "89e402f0f66ddc54494411dab813d973016ef9e1", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/authorization/resource-manager/readme.md --multiapi --python --python-mode=update --python-sdks-folder=/home/vsts/work/1/s/azure-sdk-for-python/sdk --track2 --use=@autorest/python@5.8.4 --use=@autorest/modelerfour@4.19.2 --version=3.4.5", + "autorest_command": "autorest specification/authorization/resource-manager/readme.md --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --use=@autorest/python@6.1.9 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/authorization/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/__init__.py index 5ecb0b8c8b0..918a9284afb 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/__init__.py @@ -14,3 +14,7 @@ patch_sdk() except ImportError: pass + +from ._version import VERSION + +__version__ = VERSION diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_authorization_management_client.py index b276347dde3..7c304d130eb 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_authorization_management_client.py @@ -9,21 +9,18 @@ # regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING from azure.mgmt.core import ARMPipelineClient from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapiclient import MultiApiClientMixin -from msrest import Deserializer, Serializer from ._configuration import AuthorizationManagementClientConfiguration +from ._serialization import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse class _SDKClient(object): def __init__(self, *args, **kwargs): @@ -33,7 +30,7 @@ def __init__(self, *args, **kwargs): pass class AuthorizationManagementClient(MultiApiClientMixin, _SDKClient): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role definitions and role assignments. A role definition describes the set of actions that can be performed on resources. A role assignment grants access to Azure Active Directory users. + """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to get deny assignments. A deny assignment describes the set of actions on resources that are denied for Azure Active Directory users. This ready contains multiple API versions, to help you deal with all of the Azure clouds (Azure Stack, Azure Government, Azure China, etc.). @@ -43,9 +40,9 @@ class AuthorizationManagementClient(MultiApiClientMixin, _SDKClient): The api-version parameter sets the default API version if the operation group is not described in the profile. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :param api_version: API version to use if no profile is provided, or if missing in profile. :type api_version: str @@ -53,28 +50,75 @@ class AuthorizationManagementClient(MultiApiClientMixin, _SDKClient): :type base_url: str :param profile: A profile definition, from KnownProfiles to dict. :type profile: azure.profiles.KnownProfiles + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ - DEFAULT_API_VERSION = '2015-07-01' + DEFAULT_API_VERSION = '2022-04-01' _PROFILE_TAG = "azure.mgmt.authorization.AuthorizationManagementClient" LATEST_PROFILE = ProfileDefinition({ _PROFILE_TAG: { None: DEFAULT_API_VERSION, + 'access_review_default_settings': '2021-12-01-preview', + 'access_review_history_definition': '2021-12-01-preview', + 'access_review_history_definition_instance': '2021-12-01-preview', + 'access_review_history_definition_instances': '2021-12-01-preview', + 'access_review_history_definitions': '2021-12-01-preview', + 'access_review_instance': '2021-12-01-preview', + 'access_review_instance_contacted_reviewers': '2021-12-01-preview', + 'access_review_instance_decisions': '2021-12-01-preview', + 'access_review_instance_my_decisions': '2021-12-01-preview', + 'access_review_instances': '2021-12-01-preview', + 'access_review_instances_assigned_for_my_approval': '2021-12-01-preview', + 'access_review_schedule_definitions': '2021-12-01-preview', + 'access_review_schedule_definitions_assigned_for_my_approval': '2021-12-01-preview', + 'alert_configurations': '2021-12-01-preview', + 'alert_definitions': '2021-12-01-preview', + 'alert_incidents': '2021-12-01-preview', + 'alert_operation': '2021-12-01-preview', + 'alerts': '2021-12-01-preview', + 'classic_administrators': '2015-07-01', + 'eligible_child_resources': '2020-10-01', + 'global_administrator': '2015-07-01', + 'operations': '2021-12-01-preview', + 'role_assignment_approval': '2021-01-01-preview', + 'role_assignment_approval_step': '2021-01-01-preview', + 'role_assignment_approval_steps': '2021-01-01-preview', + 'role_assignment_metrics': '2019-08-01-preview', + 'role_assignment_schedule_instances': '2020-10-01', + 'role_assignment_schedule_requests': '2020-10-01', + 'role_assignment_schedules': '2020-10-01', + 'role_eligibility_schedule_instances': '2020-10-01', + 'role_eligibility_schedule_requests': '2020-10-01', + 'role_eligibility_schedules': '2020-10-01', + 'role_management_policies': '2020-10-01', + 'role_management_policy_assignments': '2020-10-01', + 'scope_access_review_default_settings': '2021-12-01-preview', + 'scope_access_review_history_definition': '2021-12-01-preview', + 'scope_access_review_history_definition_instance': '2021-12-01-preview', + 'scope_access_review_history_definition_instances': '2021-12-01-preview', + 'scope_access_review_history_definitions': '2021-12-01-preview', + 'scope_access_review_instance': '2021-12-01-preview', + 'scope_access_review_instance_contacted_reviewers': '2021-12-01-preview', + 'scope_access_review_instance_decisions': '2021-12-01-preview', + 'scope_access_review_instances': '2021-12-01-preview', + 'scope_access_review_schedule_definitions': '2021-12-01-preview', + 'scope_role_assignment_approval': '2021-01-01-preview', + 'scope_role_assignment_approval_step': '2021-01-01-preview', + 'scope_role_assignment_approval_steps': '2021-01-01-preview', + 'tenant_level_access_review_instance_contacted_reviewers': '2021-12-01-preview', }}, _PROFILE_TAG + " latest" ) def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str + credential: "TokenCredential", + subscription_id: str, api_version=None, # type: Optional[str] - base_url=None, # type: Optional[str] + base_url: str = "https://management.azure.com", profile=KnownProfiles.default, # type: KnownProfiles **kwargs # type: Any ): - if not base_url: - base_url = 'https://management.azure.com' self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) super(AuthorizationManagementClient, self).__init__( @@ -98,9 +142,13 @@ def models(cls, api_version=DEFAULT_API_VERSION): * 2018-09-01-preview: :mod:`v2018_09_01_preview.models` * 2019-08-01-preview: :mod:`v2019_08_01_preview.models` * 2020-04-01-preview: :mod:`v2020_04_01_preview.models` + * 2020-10-01: :mod:`v2020_10_01.models` * 2020-10-01-preview: :mod:`v2020_10_01_preview.models` * 2021-01-01-preview: :mod:`v2021_01_01_preview.models` * 2021-03-01-preview: :mod:`v2021_03_01_preview.models` + * 2021-07-01-preview: :mod:`v2021_07_01_preview.models` + * 2021-12-01-preview: :mod:`v2021_12_01_preview.models` + * 2022-04-01: :mod:`v2022_04_01.models` """ if api_version == '2015-06-01': from .v2015_06_01 import models @@ -126,6 +174,9 @@ def models(cls, api_version=DEFAULT_API_VERSION): elif api_version == '2020-04-01-preview': from .v2020_04_01_preview import models return models + elif api_version == '2020-10-01': + from .v2020_10_01 import models + return models elif api_version == '2020-10-01-preview': from .v2020_10_01_preview import models return models @@ -135,6 +186,15 @@ def models(cls, api_version=DEFAULT_API_VERSION): elif api_version == '2021-03-01-preview': from .v2021_03_01_preview import models return models + elif api_version == '2021-07-01-preview': + from .v2021_07_01_preview import models + return models + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview import models + return models + elif api_version == '2022-04-01': + from .v2022_04_01 import models + return models raise ValueError("API version {} is not available".format(api_version)) @property @@ -143,14 +203,77 @@ def access_review_default_settings(self): * 2018-05-01-preview: :class:`AccessReviewDefaultSettingsOperations` * 2021-03-01-preview: :class:`AccessReviewDefaultSettingsOperations` + * 2021-07-01-preview: :class:`AccessReviewDefaultSettingsOperations` + * 2021-12-01-preview: :class:`AccessReviewDefaultSettingsOperations` """ api_version = self._get_api_version('access_review_default_settings') if api_version == '2018-05-01-preview': from .v2018_05_01_preview.operations import AccessReviewDefaultSettingsOperations as OperationClass elif api_version == '2021-03-01-preview': from .v2021_03_01_preview.operations import AccessReviewDefaultSettingsOperations as OperationClass + elif api_version == '2021-07-01-preview': + from .v2021_07_01_preview.operations import AccessReviewDefaultSettingsOperations as OperationClass + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewDefaultSettingsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_default_settings'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def access_review_history_definition(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AccessReviewHistoryDefinitionOperations` + """ + api_version = self._get_api_version('access_review_history_definition') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewHistoryDefinitionOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'access_review_history_definition'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def access_review_history_definition_instance(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AccessReviewHistoryDefinitionInstanceOperations` + """ + api_version = self._get_api_version('access_review_history_definition_instance') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewHistoryDefinitionInstanceOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'access_review_history_definition_instance'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def access_review_history_definition_instances(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AccessReviewHistoryDefinitionInstancesOperations` + """ + api_version = self._get_api_version('access_review_history_definition_instances') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewHistoryDefinitionInstancesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'access_review_history_definition_instances'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def access_review_history_definitions(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AccessReviewHistoryDefinitionsOperations` + """ + api_version = self._get_api_version('access_review_history_definitions') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewHistoryDefinitionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'access_review_history_definitions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -159,14 +282,38 @@ def access_review_instance(self): * 2018-05-01-preview: :class:`AccessReviewInstanceOperations` * 2021-03-01-preview: :class:`AccessReviewInstanceOperations` + * 2021-07-01-preview: :class:`AccessReviewInstanceOperations` + * 2021-12-01-preview: :class:`AccessReviewInstanceOperations` """ api_version = self._get_api_version('access_review_instance') if api_version == '2018-05-01-preview': from .v2018_05_01_preview.operations import AccessReviewInstanceOperations as OperationClass elif api_version == '2021-03-01-preview': from .v2021_03_01_preview.operations import AccessReviewInstanceOperations as OperationClass + elif api_version == '2021-07-01-preview': + from .v2021_07_01_preview.operations import AccessReviewInstanceOperations as OperationClass + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewInstanceOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_instance'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def access_review_instance_contacted_reviewers(self): + """Instance depends on the API version: + + * 2021-07-01-preview: :class:`AccessReviewInstanceContactedReviewersOperations` + * 2021-12-01-preview: :class:`AccessReviewInstanceContactedReviewersOperations` + """ + api_version = self._get_api_version('access_review_instance_contacted_reviewers') + if api_version == '2021-07-01-preview': + from .v2021_07_01_preview.operations import AccessReviewInstanceContactedReviewersOperations as OperationClass + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewInstanceContactedReviewersOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'access_review_instance_contacted_reviewers'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -175,14 +322,21 @@ def access_review_instance_decisions(self): * 2018-05-01-preview: :class:`AccessReviewInstanceDecisionsOperations` * 2021-03-01-preview: :class:`AccessReviewInstanceDecisionsOperations` + * 2021-07-01-preview: :class:`AccessReviewInstanceDecisionsOperations` + * 2021-12-01-preview: :class:`AccessReviewInstanceDecisionsOperations` """ api_version = self._get_api_version('access_review_instance_decisions') if api_version == '2018-05-01-preview': from .v2018_05_01_preview.operations import AccessReviewInstanceDecisionsOperations as OperationClass elif api_version == '2021-03-01-preview': from .v2021_03_01_preview.operations import AccessReviewInstanceDecisionsOperations as OperationClass + elif api_version == '2021-07-01-preview': + from .v2021_07_01_preview.operations import AccessReviewInstanceDecisionsOperations as OperationClass + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewInstanceDecisionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_instance_decisions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -191,14 +345,21 @@ def access_review_instance_my_decisions(self): * 2018-05-01-preview: :class:`AccessReviewInstanceMyDecisionsOperations` * 2021-03-01-preview: :class:`AccessReviewInstanceMyDecisionsOperations` + * 2021-07-01-preview: :class:`AccessReviewInstanceMyDecisionsOperations` + * 2021-12-01-preview: :class:`AccessReviewInstanceMyDecisionsOperations` """ api_version = self._get_api_version('access_review_instance_my_decisions') if api_version == '2018-05-01-preview': from .v2018_05_01_preview.operations import AccessReviewInstanceMyDecisionsOperations as OperationClass elif api_version == '2021-03-01-preview': from .v2021_03_01_preview.operations import AccessReviewInstanceMyDecisionsOperations as OperationClass + elif api_version == '2021-07-01-preview': + from .v2021_07_01_preview.operations import AccessReviewInstanceMyDecisionsOperations as OperationClass + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewInstanceMyDecisionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_instance_my_decisions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -207,14 +368,21 @@ def access_review_instances(self): * 2018-05-01-preview: :class:`AccessReviewInstancesOperations` * 2021-03-01-preview: :class:`AccessReviewInstancesOperations` + * 2021-07-01-preview: :class:`AccessReviewInstancesOperations` + * 2021-12-01-preview: :class:`AccessReviewInstancesOperations` """ api_version = self._get_api_version('access_review_instances') if api_version == '2018-05-01-preview': from .v2018_05_01_preview.operations import AccessReviewInstancesOperations as OperationClass elif api_version == '2021-03-01-preview': from .v2021_03_01_preview.operations import AccessReviewInstancesOperations as OperationClass + elif api_version == '2021-07-01-preview': + from .v2021_07_01_preview.operations import AccessReviewInstancesOperations as OperationClass + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewInstancesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_instances'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -223,14 +391,21 @@ def access_review_instances_assigned_for_my_approval(self): * 2018-05-01-preview: :class:`AccessReviewInstancesAssignedForMyApprovalOperations` * 2021-03-01-preview: :class:`AccessReviewInstancesAssignedForMyApprovalOperations` + * 2021-07-01-preview: :class:`AccessReviewInstancesAssignedForMyApprovalOperations` + * 2021-12-01-preview: :class:`AccessReviewInstancesAssignedForMyApprovalOperations` """ api_version = self._get_api_version('access_review_instances_assigned_for_my_approval') if api_version == '2018-05-01-preview': from .v2018_05_01_preview.operations import AccessReviewInstancesAssignedForMyApprovalOperations as OperationClass elif api_version == '2021-03-01-preview': from .v2021_03_01_preview.operations import AccessReviewInstancesAssignedForMyApprovalOperations as OperationClass + elif api_version == '2021-07-01-preview': + from .v2021_07_01_preview.operations import AccessReviewInstancesAssignedForMyApprovalOperations as OperationClass + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewInstancesAssignedForMyApprovalOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_instances_assigned_for_my_approval'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -239,14 +414,21 @@ def access_review_schedule_definitions(self): * 2018-05-01-preview: :class:`AccessReviewScheduleDefinitionsOperations` * 2021-03-01-preview: :class:`AccessReviewScheduleDefinitionsOperations` + * 2021-07-01-preview: :class:`AccessReviewScheduleDefinitionsOperations` + * 2021-12-01-preview: :class:`AccessReviewScheduleDefinitionsOperations` """ api_version = self._get_api_version('access_review_schedule_definitions') if api_version == '2018-05-01-preview': from .v2018_05_01_preview.operations import AccessReviewScheduleDefinitionsOperations as OperationClass elif api_version == '2021-03-01-preview': from .v2021_03_01_preview.operations import AccessReviewScheduleDefinitionsOperations as OperationClass + elif api_version == '2021-07-01-preview': + from .v2021_07_01_preview.operations import AccessReviewScheduleDefinitionsOperations as OperationClass + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewScheduleDefinitionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_schedule_definitions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -255,14 +437,91 @@ def access_review_schedule_definitions_assigned_for_my_approval(self): * 2018-05-01-preview: :class:`AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations` * 2021-03-01-preview: :class:`AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations` + * 2021-07-01-preview: :class:`AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations` + * 2021-12-01-preview: :class:`AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations` """ api_version = self._get_api_version('access_review_schedule_definitions_assigned_for_my_approval') if api_version == '2018-05-01-preview': from .v2018_05_01_preview.operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations as OperationClass elif api_version == '2021-03-01-preview': from .v2021_03_01_preview.operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations as OperationClass + elif api_version == '2021-07-01-preview': + from .v2021_07_01_preview.operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations as OperationClass + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_schedule_definitions_assigned_for_my_approval'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def alert_configurations(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AlertConfigurationsOperations` + """ + api_version = self._get_api_version('alert_configurations') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AlertConfigurationsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'alert_configurations'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def alert_definitions(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AlertDefinitionsOperations` + """ + api_version = self._get_api_version('alert_definitions') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AlertDefinitionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'alert_definitions'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def alert_incidents(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AlertIncidentsOperations` + """ + api_version = self._get_api_version('alert_incidents') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AlertIncidentsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'alert_incidents'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def alert_operation(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AlertOperationOperations` + """ + api_version = self._get_api_version('alert_operation') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AlertOperationOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'alert_operation'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def alerts(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AlertsOperations` + """ + api_version = self._get_api_version('alerts') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import AlertsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'alerts'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -279,6 +538,7 @@ def classic_administrators(self): from .v2015_07_01.operations import ClassicAdministratorsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'classic_administrators'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -286,25 +546,33 @@ def deny_assignments(self): """Instance depends on the API version: * 2018-07-01-preview: :class:`DenyAssignmentsOperations` + * 2022-04-01: :class:`DenyAssignmentsOperations` """ api_version = self._get_api_version('deny_assignments') if api_version == '2018-07-01-preview': from .v2018_07_01_preview.operations import DenyAssignmentsOperations as OperationClass + elif api_version == '2022-04-01': + from .v2022_04_01.operations import DenyAssignmentsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'deny_assignments'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def eligible_child_resources(self): """Instance depends on the API version: + * 2020-10-01: :class:`EligibleChildResourcesOperations` * 2020-10-01-preview: :class:`EligibleChildResourcesOperations` """ api_version = self._get_api_version('eligible_child_resources') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from .v2020_10_01.operations import EligibleChildResourcesOperations as OperationClass + elif api_version == '2020-10-01-preview': from .v2020_10_01_preview.operations import EligibleChildResourcesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'eligible_child_resources'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -318,6 +586,7 @@ def global_administrator(self): from .v2015_07_01.operations import GlobalAdministratorOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'global_administrator'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -327,6 +596,8 @@ def operations(self): * 2018-05-01-preview: :class:`Operations` * 2021-01-01-preview: :class:`Operations` * 2021-03-01-preview: :class:`Operations` + * 2021-07-01-preview: :class:`Operations` + * 2021-12-01-preview: :class:`Operations` """ api_version = self._get_api_version('operations') if api_version == '2018-05-01-preview': @@ -335,8 +606,13 @@ def operations(self): from .v2021_01_01_preview.operations import Operations as OperationClass elif api_version == '2021-03-01-preview': from .v2021_03_01_preview.operations import Operations as OperationClass + elif api_version == '2021-07-01-preview': + from .v2021_07_01_preview.operations import Operations as OperationClass + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import Operations as OperationClass else: raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -345,14 +621,18 @@ def permissions(self): * 2015-07-01: :class:`PermissionsOperations` * 2018-01-01-preview: :class:`PermissionsOperations` + * 2022-04-01: :class:`PermissionsOperations` """ api_version = self._get_api_version('permissions') if api_version == '2015-07-01': from .v2015_07_01.operations import PermissionsOperations as OperationClass elif api_version == '2018-01-01-preview': from .v2018_01_01_preview.operations import PermissionsOperations as OperationClass + elif api_version == '2022-04-01': + from .v2022_04_01.operations import PermissionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'permissions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -361,14 +641,18 @@ def provider_operations_metadata(self): * 2015-07-01: :class:`ProviderOperationsMetadataOperations` * 2018-01-01-preview: :class:`ProviderOperationsMetadataOperations` + * 2022-04-01: :class:`ProviderOperationsMetadataOperations` """ api_version = self._get_api_version('provider_operations_metadata') if api_version == '2015-07-01': from .v2015_07_01.operations import ProviderOperationsMetadataOperations as OperationClass elif api_version == '2018-01-01-preview': from .v2018_01_01_preview.operations import ProviderOperationsMetadataOperations as OperationClass + elif api_version == '2022-04-01': + from .v2022_04_01.operations import ProviderOperationsMetadataOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'provider_operations_metadata'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -382,6 +666,7 @@ def role_assignment_approval(self): from .v2021_01_01_preview.operations import RoleAssignmentApprovalOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_approval'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -395,6 +680,7 @@ def role_assignment_approval_step(self): from .v2021_01_01_preview.operations import RoleAssignmentApprovalStepOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_approval_step'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -408,6 +694,7 @@ def role_assignment_approval_steps(self): from .v2021_01_01_preview.operations import RoleAssignmentApprovalStepsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_approval_steps'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -421,45 +708,58 @@ def role_assignment_metrics(self): from .v2019_08_01_preview.operations import RoleAssignmentMetricsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_metrics'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_assignment_schedule_instances(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleAssignmentScheduleInstancesOperations` * 2020-10-01-preview: :class:`RoleAssignmentScheduleInstancesOperations` """ api_version = self._get_api_version('role_assignment_schedule_instances') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from .v2020_10_01.operations import RoleAssignmentScheduleInstancesOperations as OperationClass + elif api_version == '2020-10-01-preview': from .v2020_10_01_preview.operations import RoleAssignmentScheduleInstancesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_schedule_instances'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_assignment_schedule_requests(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleAssignmentScheduleRequestsOperations` * 2020-10-01-preview: :class:`RoleAssignmentScheduleRequestsOperations` """ api_version = self._get_api_version('role_assignment_schedule_requests') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from .v2020_10_01.operations import RoleAssignmentScheduleRequestsOperations as OperationClass + elif api_version == '2020-10-01-preview': from .v2020_10_01_preview.operations import RoleAssignmentScheduleRequestsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_schedule_requests'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_assignment_schedules(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleAssignmentSchedulesOperations` * 2020-10-01-preview: :class:`RoleAssignmentSchedulesOperations` """ api_version = self._get_api_version('role_assignment_schedules') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from .v2020_10_01.operations import RoleAssignmentSchedulesOperations as OperationClass + elif api_version == '2020-10-01-preview': from .v2020_10_01_preview.operations import RoleAssignmentSchedulesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_schedules'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -471,6 +771,7 @@ def role_assignments(self): * 2018-09-01-preview: :class:`RoleAssignmentsOperations` * 2020-04-01-preview: :class:`RoleAssignmentsOperations` * 2020-10-01-preview: :class:`RoleAssignmentsOperations` + * 2022-04-01: :class:`RoleAssignmentsOperations` """ api_version = self._get_api_version('role_assignments') if api_version == '2015-07-01': @@ -483,8 +784,11 @@ def role_assignments(self): from .v2020_04_01_preview.operations import RoleAssignmentsOperations as OperationClass elif api_version == '2020-10-01-preview': from .v2020_10_01_preview.operations import RoleAssignmentsOperations as OperationClass + elif api_version == '2022-04-01': + from .v2022_04_01.operations import RoleAssignmentsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignments'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -493,79 +797,243 @@ def role_definitions(self): * 2015-07-01: :class:`RoleDefinitionsOperations` * 2018-01-01-preview: :class:`RoleDefinitionsOperations` + * 2022-04-01: :class:`RoleDefinitionsOperations` """ api_version = self._get_api_version('role_definitions') if api_version == '2015-07-01': from .v2015_07_01.operations import RoleDefinitionsOperations as OperationClass elif api_version == '2018-01-01-preview': from .v2018_01_01_preview.operations import RoleDefinitionsOperations as OperationClass + elif api_version == '2022-04-01': + from .v2022_04_01.operations import RoleDefinitionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_definitions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_eligibility_schedule_instances(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleEligibilityScheduleInstancesOperations` * 2020-10-01-preview: :class:`RoleEligibilityScheduleInstancesOperations` """ api_version = self._get_api_version('role_eligibility_schedule_instances') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from .v2020_10_01.operations import RoleEligibilityScheduleInstancesOperations as OperationClass + elif api_version == '2020-10-01-preview': from .v2020_10_01_preview.operations import RoleEligibilityScheduleInstancesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_eligibility_schedule_instances'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_eligibility_schedule_requests(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleEligibilityScheduleRequestsOperations` * 2020-10-01-preview: :class:`RoleEligibilityScheduleRequestsOperations` """ api_version = self._get_api_version('role_eligibility_schedule_requests') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from .v2020_10_01.operations import RoleEligibilityScheduleRequestsOperations as OperationClass + elif api_version == '2020-10-01-preview': from .v2020_10_01_preview.operations import RoleEligibilityScheduleRequestsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_eligibility_schedule_requests'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_eligibility_schedules(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleEligibilitySchedulesOperations` * 2020-10-01-preview: :class:`RoleEligibilitySchedulesOperations` """ api_version = self._get_api_version('role_eligibility_schedules') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from .v2020_10_01.operations import RoleEligibilitySchedulesOperations as OperationClass + elif api_version == '2020-10-01-preview': from .v2020_10_01_preview.operations import RoleEligibilitySchedulesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_eligibility_schedules'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_management_policies(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleManagementPoliciesOperations` * 2020-10-01-preview: :class:`RoleManagementPoliciesOperations` """ api_version = self._get_api_version('role_management_policies') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from .v2020_10_01.operations import RoleManagementPoliciesOperations as OperationClass + elif api_version == '2020-10-01-preview': from .v2020_10_01_preview.operations import RoleManagementPoliciesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_management_policies'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_management_policy_assignments(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleManagementPolicyAssignmentsOperations` * 2020-10-01-preview: :class:`RoleManagementPolicyAssignmentsOperations` """ api_version = self._get_api_version('role_management_policy_assignments') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from .v2020_10_01.operations import RoleManagementPolicyAssignmentsOperations as OperationClass + elif api_version == '2020-10-01-preview': from .v2020_10_01_preview.operations import RoleManagementPolicyAssignmentsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_management_policy_assignments'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_default_settings(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewDefaultSettingsOperations` + """ + api_version = self._get_api_version('scope_access_review_default_settings') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import ScopeAccessReviewDefaultSettingsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_default_settings'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_history_definition(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewHistoryDefinitionOperations` + """ + api_version = self._get_api_version('scope_access_review_history_definition') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import ScopeAccessReviewHistoryDefinitionOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_history_definition'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_history_definition_instance(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewHistoryDefinitionInstanceOperations` + """ + api_version = self._get_api_version('scope_access_review_history_definition_instance') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import ScopeAccessReviewHistoryDefinitionInstanceOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_history_definition_instance'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_history_definition_instances(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewHistoryDefinitionInstancesOperations` + """ + api_version = self._get_api_version('scope_access_review_history_definition_instances') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import ScopeAccessReviewHistoryDefinitionInstancesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_history_definition_instances'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_history_definitions(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewHistoryDefinitionsOperations` + """ + api_version = self._get_api_version('scope_access_review_history_definitions') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import ScopeAccessReviewHistoryDefinitionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_history_definitions'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_instance(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewInstanceOperations` + """ + api_version = self._get_api_version('scope_access_review_instance') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import ScopeAccessReviewInstanceOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_instance'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_instance_contacted_reviewers(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewInstanceContactedReviewersOperations` + """ + api_version = self._get_api_version('scope_access_review_instance_contacted_reviewers') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import ScopeAccessReviewInstanceContactedReviewersOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_instance_contacted_reviewers'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_instance_decisions(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewInstanceDecisionsOperations` + """ + api_version = self._get_api_version('scope_access_review_instance_decisions') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import ScopeAccessReviewInstanceDecisionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_instance_decisions'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_instances(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewInstancesOperations` + """ + api_version = self._get_api_version('scope_access_review_instances') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import ScopeAccessReviewInstancesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_instances'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_schedule_definitions(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewScheduleDefinitionsOperations` + """ + api_version = self._get_api_version('scope_access_review_schedule_definitions') + if api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import ScopeAccessReviewScheduleDefinitionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_schedule_definitions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -579,6 +1047,7 @@ def scope_role_assignment_approval(self): from .v2021_01_01_preview.operations import ScopeRoleAssignmentApprovalOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'scope_role_assignment_approval'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -592,6 +1061,7 @@ def scope_role_assignment_approval_step(self): from .v2021_01_01_preview.operations import ScopeRoleAssignmentApprovalStepOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'scope_role_assignment_approval_step'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -605,6 +1075,24 @@ def scope_role_assignment_approval_steps(self): from .v2021_01_01_preview.operations import ScopeRoleAssignmentApprovalStepsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'scope_role_assignment_approval_steps'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def tenant_level_access_review_instance_contacted_reviewers(self): + """Instance depends on the API version: + + * 2021-07-01-preview: :class:`TenantLevelAccessReviewInstanceContactedReviewersOperations` + * 2021-12-01-preview: :class:`TenantLevelAccessReviewInstanceContactedReviewersOperations` + """ + api_version = self._get_api_version('tenant_level_access_review_instance_contacted_reviewers') + if api_version == '2021-07-01-preview': + from .v2021_07_01_preview.operations import TenantLevelAccessReviewInstanceContactedReviewersOperations as OperationClass + elif api_version == '2021-12-01-preview': + from .v2021_12_01_preview.operations import TenantLevelAccessReviewInstanceContactedReviewersOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'tenant_level_access_review_instance_contacted_reviewers'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) def close(self): diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_configuration.py index 23336d3cc79..2456ec0c141 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_configuration.py @@ -8,18 +8,16 @@ # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential class AuthorizationManagementClientConfiguration(Configuration): @@ -28,16 +26,16 @@ class AuthorizationManagementClientConfiguration(Configuration): Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str + credential: "TokenCredential", + subscription_id: str, **kwargs # type: Any ): # type: (...) -> None @@ -68,4 +66,4 @@ def _configure( self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_serialization.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_serialization.py new file mode 100644 index 00000000000..240df16c57f --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_serialization.py @@ -0,0 +1,2006 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding='utf-8') + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r'^(application|text)/([a-z+.]+\+)?json$') + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, 'read'): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding='utf-8-sig') + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if 'content-type' in headers: + content_type = headers['content-type'].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds()/3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + +try: + from datetime import timezone + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0 + } + + def __init__(self, classes=None): + self.serialize_type = { + 'iso-8601': Serializer.serialize_iso, + 'rfc-1123': Serializer.serialize_rfc, + 'unix-time': Serializer.serialize_unix, + 'duration': Serializer.serialize_duration, + 'date': Serializer.serialize_date, + 'time': Serializer.serialize_time, + 'decimal': Serializer.serialize_decimal, + 'long': Serializer.serialize_long, + 'bytearray': Serializer.serialize_bytearray, + 'base64': Serializer.serialize_base64, + 'object': self.serialize_object, + '[]': self.serialize_iter, + '{}': self.serialize_dict + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data( + target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data( + target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get('readonly', False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == '': + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc['type'], **kwargs) + + + if is_xml_model_serialization: + xml_desc = attr_desc.get('xml', {}) + xml_name = xml_desc.get('name', attr_desc['key']) + xml_prefix = xml_desc.get('prefix', None) + xml_ns = xml_desc.get('ns', None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if 'name' not in getattr(orig_attr, '_xml_map', {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node( + xml_name, + xml_prefix, + xml_ns + ) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format( + attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip('[]{}') + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback( + SerializationError, "Unable to build a model: "+str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == 'bool': + output = json.dumps(output) + + if kwargs.get('skip_quote') is True: + output = str(output) + else: + output = quote(str(output), safe='') + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [ + self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" + for d + in data + ] + if not kwargs.get('skip_quote', False): + data = [ + quote(str(d), safe='') + for d + in data + ] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == 'bool': + output = json.dumps(output) + if kwargs.get('skip_quote') is True: + output = str(output) + else: + output = quote(str(output), safe='') + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ['[str]']: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == 'bool': + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type]( + data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback( + SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == 'str': + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ['' if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if 'xml' in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get('xml', {}) + xml_name = xml_desc.get('name') + if not xml_name: + xml_name = serialization_ctxt['key'] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node( + xml_name, + xml_desc.get('prefix', None), + xml_desc.get('ns', None) + ) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node( + node_name, + xml_desc.get('prefix', None), + xml_desc.get('ns', None) + ) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data( + value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if 'xml' in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt['xml'] + xml_name = xml_desc['name'] + + final_result = _create_xml_node( + xml_name, + xml_desc.get('prefix', None), + xml_desc.get('ns', None) + ) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object( + value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object( + obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode('ascii') + return encoded.strip('=').replace('+', '-').replace('/', '_') + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning( + "Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], utc.tm_mday, + Serializer.months[utc.tm_mon], utc.tm_year, + utc.tm_hour, utc.tm_min, utc.tm_sec) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning( + "Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6,'0').rstrip('0').ljust(3, '0') + if microseconds: + microseconds = '.'+microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, + utc.tm_hour, utc.tm_min, utc.tm_sec) + return date + microseconds + 'Z' + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning( + "Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc['key'] + working_data = data + + while '.' in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = '.'.join(dict_keys[1:]) + + return working_data.get(key) + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc['key'] + working_data = data + + while '.' in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = '.'.join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + """ + key = attr_desc['key'] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc['key'] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get('name', internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get('xml', {}) + xml_name = xml_desc.get('name', attr_desc['key']) + + # Look for a children + is_iter_type = attr_desc['type'].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get('ns', internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or 'name' not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and 'name' in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + )) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: 'str', int: 'int', bool: 'bool', float: 'float'} + + valid_date = re.compile( + r'\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}' + r'\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?') + + def __init__(self, classes=None): + self.deserialize_type = { + 'iso-8601': Deserializer.deserialize_iso, + 'rfc-1123': Deserializer.deserialize_rfc, + 'unix-time': Deserializer.deserialize_unix, + 'duration': Deserializer.deserialize_duration, + 'date': Deserializer.deserialize_date, + 'time': Deserializer.deserialize_time, + 'decimal': Deserializer.deserialize_decimal, + 'long': Deserializer.deserialize_long, + 'bytearray': Deserializer.deserialize_bytearray, + 'base64': Deserializer.deserialize_base64, + 'object': self.deserialize_object, + '[]': self.deserialize_iter, + '{}': self.deserialize_dict + } + self.deserialize_expected_types = { + 'duration': (isodate.Duration, datetime.timedelta), + 'iso-8601': (datetime.datetime) + } + self.dependencies = dict(classes) if classes else {} + self.key_extractors = [ + rest_key_extractor, + xml_key_extractor + ] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, '_validation', {}).items() + if config.get('constant')] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig['type'] + internal_data_type = local_type.strip('[]{}') + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr( + data, + attr, + self._deserialize(local_type, value) + ) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == '': + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip('[]{}') + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ("Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" ) + _LOGGER.warning( + msg, + found_value, + key_extractor, + attr + ) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc['type']) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != '': + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = {_decode_attribute_map_key(_FLATTEN.split(desc['key'])[0]) + for desc in attribute_map.values() if desc['key'] != ''} + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", + exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + #Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics( + raw_data.text(), + raw_data.headers + ) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, '_content_consumed'): + return RawDeserializer.deserialize_from_http_generics( + raw_data.text, + raw_data.headers + ) + + if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, 'read'): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, '_subtype_map', {}) + try: + readonly = [k for k, v in response._validation.items() + if v.get('readonly')] + const = [k for k, v in response._validation.items() + if v.get('constant')] + kwargs = {k: v for k, v in attrs.items() + if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format( + kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format( + iter_type, + type(attr) + )) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x['key']: self.deserialize_data(x['value'], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, 'str') + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object( + value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object( + obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return '' + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == 'bool': + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ['true', '1']: + return True + elif attr.lower() in ['false', '0']: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == 'str': + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = '=' * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace('-', '+').replace('_', '/') + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except(ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], + tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0)/60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split('.') + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except(ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_version.py index 88729157c48..63bcd0444b1 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/_version.py @@ -5,4 +5,4 @@ # license information. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/aio/_authorization_management_client.py index 931b122b8db..f0f6bd29133 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/aio/_authorization_management_client.py @@ -11,12 +11,11 @@ from typing import Any, Optional, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapiclient import MultiApiClientMixin -from msrest import Deserializer, Serializer +from .._serialization import Deserializer, Serializer from ._configuration import AuthorizationManagementClientConfiguration if TYPE_CHECKING: @@ -31,7 +30,7 @@ def __init__(self, *args, **kwargs): pass class AuthorizationManagementClient(MultiApiClientMixin, _SDKClient): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role definitions and role assignments. A role definition describes the set of actions that can be performed on resources. A role assignment grants access to Azure Active Directory users. + """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to get deny assignments. A deny assignment describes the set of actions on resources that are denied for Azure Active Directory users. This ready contains multiple API versions, to help you deal with all of the Azure clouds (Azure Stack, Azure Government, Azure China, etc.). @@ -41,9 +40,9 @@ class AuthorizationManagementClient(MultiApiClientMixin, _SDKClient): The api-version parameter sets the default API version if the operation group is not described in the profile. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :param api_version: API version to use if no profile is provided, or if missing in profile. :type api_version: str @@ -51,13 +50,62 @@ class AuthorizationManagementClient(MultiApiClientMixin, _SDKClient): :type base_url: str :param profile: A profile definition, from KnownProfiles to dict. :type profile: azure.profiles.KnownProfiles + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ - DEFAULT_API_VERSION = '2015-07-01' + DEFAULT_API_VERSION = '2022-04-01' _PROFILE_TAG = "azure.mgmt.authorization.AuthorizationManagementClient" LATEST_PROFILE = ProfileDefinition({ _PROFILE_TAG: { None: DEFAULT_API_VERSION, + 'access_review_default_settings': '2021-12-01-preview', + 'access_review_history_definition': '2021-12-01-preview', + 'access_review_history_definition_instance': '2021-12-01-preview', + 'access_review_history_definition_instances': '2021-12-01-preview', + 'access_review_history_definitions': '2021-12-01-preview', + 'access_review_instance': '2021-12-01-preview', + 'access_review_instance_contacted_reviewers': '2021-12-01-preview', + 'access_review_instance_decisions': '2021-12-01-preview', + 'access_review_instance_my_decisions': '2021-12-01-preview', + 'access_review_instances': '2021-12-01-preview', + 'access_review_instances_assigned_for_my_approval': '2021-12-01-preview', + 'access_review_schedule_definitions': '2021-12-01-preview', + 'access_review_schedule_definitions_assigned_for_my_approval': '2021-12-01-preview', + 'alert_configurations': '2021-12-01-preview', + 'alert_definitions': '2021-12-01-preview', + 'alert_incidents': '2021-12-01-preview', + 'alert_operation': '2021-12-01-preview', + 'alerts': '2021-12-01-preview', + 'classic_administrators': '2015-07-01', + 'eligible_child_resources': '2020-10-01', + 'global_administrator': '2015-07-01', + 'operations': '2021-12-01-preview', + 'role_assignment_approval': '2021-01-01-preview', + 'role_assignment_approval_step': '2021-01-01-preview', + 'role_assignment_approval_steps': '2021-01-01-preview', + 'role_assignment_metrics': '2019-08-01-preview', + 'role_assignment_schedule_instances': '2020-10-01', + 'role_assignment_schedule_requests': '2020-10-01', + 'role_assignment_schedules': '2020-10-01', + 'role_eligibility_schedule_instances': '2020-10-01', + 'role_eligibility_schedule_requests': '2020-10-01', + 'role_eligibility_schedules': '2020-10-01', + 'role_management_policies': '2020-10-01', + 'role_management_policy_assignments': '2020-10-01', + 'scope_access_review_default_settings': '2021-12-01-preview', + 'scope_access_review_history_definition': '2021-12-01-preview', + 'scope_access_review_history_definition_instance': '2021-12-01-preview', + 'scope_access_review_history_definition_instances': '2021-12-01-preview', + 'scope_access_review_history_definitions': '2021-12-01-preview', + 'scope_access_review_instance': '2021-12-01-preview', + 'scope_access_review_instance_contacted_reviewers': '2021-12-01-preview', + 'scope_access_review_instance_decisions': '2021-12-01-preview', + 'scope_access_review_instances': '2021-12-01-preview', + 'scope_access_review_schedule_definitions': '2021-12-01-preview', + 'scope_role_assignment_approval': '2021-01-01-preview', + 'scope_role_assignment_approval_step': '2021-01-01-preview', + 'scope_role_assignment_approval_steps': '2021-01-01-preview', + 'tenant_level_access_review_instance_contacted_reviewers': '2021-12-01-preview', }}, _PROFILE_TAG + " latest" ) @@ -67,12 +115,10 @@ def __init__( credential: "AsyncTokenCredential", subscription_id: str, api_version: Optional[str] = None, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", profile: KnownProfiles = KnownProfiles.default, **kwargs # type: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) super(AuthorizationManagementClient, self).__init__( @@ -96,9 +142,13 @@ def models(cls, api_version=DEFAULT_API_VERSION): * 2018-09-01-preview: :mod:`v2018_09_01_preview.models` * 2019-08-01-preview: :mod:`v2019_08_01_preview.models` * 2020-04-01-preview: :mod:`v2020_04_01_preview.models` + * 2020-10-01: :mod:`v2020_10_01.models` * 2020-10-01-preview: :mod:`v2020_10_01_preview.models` * 2021-01-01-preview: :mod:`v2021_01_01_preview.models` * 2021-03-01-preview: :mod:`v2021_03_01_preview.models` + * 2021-07-01-preview: :mod:`v2021_07_01_preview.models` + * 2021-12-01-preview: :mod:`v2021_12_01_preview.models` + * 2022-04-01: :mod:`v2022_04_01.models` """ if api_version == '2015-06-01': from ..v2015_06_01 import models @@ -124,6 +174,9 @@ def models(cls, api_version=DEFAULT_API_VERSION): elif api_version == '2020-04-01-preview': from ..v2020_04_01_preview import models return models + elif api_version == '2020-10-01': + from ..v2020_10_01 import models + return models elif api_version == '2020-10-01-preview': from ..v2020_10_01_preview import models return models @@ -133,6 +186,15 @@ def models(cls, api_version=DEFAULT_API_VERSION): elif api_version == '2021-03-01-preview': from ..v2021_03_01_preview import models return models + elif api_version == '2021-07-01-preview': + from ..v2021_07_01_preview import models + return models + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview import models + return models + elif api_version == '2022-04-01': + from ..v2022_04_01 import models + return models raise ValueError("API version {} is not available".format(api_version)) @property @@ -141,14 +203,77 @@ def access_review_default_settings(self): * 2018-05-01-preview: :class:`AccessReviewDefaultSettingsOperations` * 2021-03-01-preview: :class:`AccessReviewDefaultSettingsOperations` + * 2021-07-01-preview: :class:`AccessReviewDefaultSettingsOperations` + * 2021-12-01-preview: :class:`AccessReviewDefaultSettingsOperations` """ api_version = self._get_api_version('access_review_default_settings') if api_version == '2018-05-01-preview': from ..v2018_05_01_preview.aio.operations import AccessReviewDefaultSettingsOperations as OperationClass elif api_version == '2021-03-01-preview': from ..v2021_03_01_preview.aio.operations import AccessReviewDefaultSettingsOperations as OperationClass + elif api_version == '2021-07-01-preview': + from ..v2021_07_01_preview.aio.operations import AccessReviewDefaultSettingsOperations as OperationClass + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewDefaultSettingsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_default_settings'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def access_review_history_definition(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AccessReviewHistoryDefinitionOperations` + """ + api_version = self._get_api_version('access_review_history_definition') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewHistoryDefinitionOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'access_review_history_definition'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def access_review_history_definition_instance(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AccessReviewHistoryDefinitionInstanceOperations` + """ + api_version = self._get_api_version('access_review_history_definition_instance') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewHistoryDefinitionInstanceOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'access_review_history_definition_instance'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def access_review_history_definition_instances(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AccessReviewHistoryDefinitionInstancesOperations` + """ + api_version = self._get_api_version('access_review_history_definition_instances') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewHistoryDefinitionInstancesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'access_review_history_definition_instances'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def access_review_history_definitions(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AccessReviewHistoryDefinitionsOperations` + """ + api_version = self._get_api_version('access_review_history_definitions') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewHistoryDefinitionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'access_review_history_definitions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -157,14 +282,38 @@ def access_review_instance(self): * 2018-05-01-preview: :class:`AccessReviewInstanceOperations` * 2021-03-01-preview: :class:`AccessReviewInstanceOperations` + * 2021-07-01-preview: :class:`AccessReviewInstanceOperations` + * 2021-12-01-preview: :class:`AccessReviewInstanceOperations` """ api_version = self._get_api_version('access_review_instance') if api_version == '2018-05-01-preview': from ..v2018_05_01_preview.aio.operations import AccessReviewInstanceOperations as OperationClass elif api_version == '2021-03-01-preview': from ..v2021_03_01_preview.aio.operations import AccessReviewInstanceOperations as OperationClass + elif api_version == '2021-07-01-preview': + from ..v2021_07_01_preview.aio.operations import AccessReviewInstanceOperations as OperationClass + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewInstanceOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_instance'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def access_review_instance_contacted_reviewers(self): + """Instance depends on the API version: + + * 2021-07-01-preview: :class:`AccessReviewInstanceContactedReviewersOperations` + * 2021-12-01-preview: :class:`AccessReviewInstanceContactedReviewersOperations` + """ + api_version = self._get_api_version('access_review_instance_contacted_reviewers') + if api_version == '2021-07-01-preview': + from ..v2021_07_01_preview.aio.operations import AccessReviewInstanceContactedReviewersOperations as OperationClass + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewInstanceContactedReviewersOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'access_review_instance_contacted_reviewers'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -173,14 +322,21 @@ def access_review_instance_decisions(self): * 2018-05-01-preview: :class:`AccessReviewInstanceDecisionsOperations` * 2021-03-01-preview: :class:`AccessReviewInstanceDecisionsOperations` + * 2021-07-01-preview: :class:`AccessReviewInstanceDecisionsOperations` + * 2021-12-01-preview: :class:`AccessReviewInstanceDecisionsOperations` """ api_version = self._get_api_version('access_review_instance_decisions') if api_version == '2018-05-01-preview': from ..v2018_05_01_preview.aio.operations import AccessReviewInstanceDecisionsOperations as OperationClass elif api_version == '2021-03-01-preview': from ..v2021_03_01_preview.aio.operations import AccessReviewInstanceDecisionsOperations as OperationClass + elif api_version == '2021-07-01-preview': + from ..v2021_07_01_preview.aio.operations import AccessReviewInstanceDecisionsOperations as OperationClass + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewInstanceDecisionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_instance_decisions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -189,14 +345,21 @@ def access_review_instance_my_decisions(self): * 2018-05-01-preview: :class:`AccessReviewInstanceMyDecisionsOperations` * 2021-03-01-preview: :class:`AccessReviewInstanceMyDecisionsOperations` + * 2021-07-01-preview: :class:`AccessReviewInstanceMyDecisionsOperations` + * 2021-12-01-preview: :class:`AccessReviewInstanceMyDecisionsOperations` """ api_version = self._get_api_version('access_review_instance_my_decisions') if api_version == '2018-05-01-preview': from ..v2018_05_01_preview.aio.operations import AccessReviewInstanceMyDecisionsOperations as OperationClass elif api_version == '2021-03-01-preview': from ..v2021_03_01_preview.aio.operations import AccessReviewInstanceMyDecisionsOperations as OperationClass + elif api_version == '2021-07-01-preview': + from ..v2021_07_01_preview.aio.operations import AccessReviewInstanceMyDecisionsOperations as OperationClass + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewInstanceMyDecisionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_instance_my_decisions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -205,14 +368,21 @@ def access_review_instances(self): * 2018-05-01-preview: :class:`AccessReviewInstancesOperations` * 2021-03-01-preview: :class:`AccessReviewInstancesOperations` + * 2021-07-01-preview: :class:`AccessReviewInstancesOperations` + * 2021-12-01-preview: :class:`AccessReviewInstancesOperations` """ api_version = self._get_api_version('access_review_instances') if api_version == '2018-05-01-preview': from ..v2018_05_01_preview.aio.operations import AccessReviewInstancesOperations as OperationClass elif api_version == '2021-03-01-preview': from ..v2021_03_01_preview.aio.operations import AccessReviewInstancesOperations as OperationClass + elif api_version == '2021-07-01-preview': + from ..v2021_07_01_preview.aio.operations import AccessReviewInstancesOperations as OperationClass + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewInstancesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_instances'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -221,14 +391,21 @@ def access_review_instances_assigned_for_my_approval(self): * 2018-05-01-preview: :class:`AccessReviewInstancesAssignedForMyApprovalOperations` * 2021-03-01-preview: :class:`AccessReviewInstancesAssignedForMyApprovalOperations` + * 2021-07-01-preview: :class:`AccessReviewInstancesAssignedForMyApprovalOperations` + * 2021-12-01-preview: :class:`AccessReviewInstancesAssignedForMyApprovalOperations` """ api_version = self._get_api_version('access_review_instances_assigned_for_my_approval') if api_version == '2018-05-01-preview': from ..v2018_05_01_preview.aio.operations import AccessReviewInstancesAssignedForMyApprovalOperations as OperationClass elif api_version == '2021-03-01-preview': from ..v2021_03_01_preview.aio.operations import AccessReviewInstancesAssignedForMyApprovalOperations as OperationClass + elif api_version == '2021-07-01-preview': + from ..v2021_07_01_preview.aio.operations import AccessReviewInstancesAssignedForMyApprovalOperations as OperationClass + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewInstancesAssignedForMyApprovalOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_instances_assigned_for_my_approval'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -237,14 +414,21 @@ def access_review_schedule_definitions(self): * 2018-05-01-preview: :class:`AccessReviewScheduleDefinitionsOperations` * 2021-03-01-preview: :class:`AccessReviewScheduleDefinitionsOperations` + * 2021-07-01-preview: :class:`AccessReviewScheduleDefinitionsOperations` + * 2021-12-01-preview: :class:`AccessReviewScheduleDefinitionsOperations` """ api_version = self._get_api_version('access_review_schedule_definitions') if api_version == '2018-05-01-preview': from ..v2018_05_01_preview.aio.operations import AccessReviewScheduleDefinitionsOperations as OperationClass elif api_version == '2021-03-01-preview': from ..v2021_03_01_preview.aio.operations import AccessReviewScheduleDefinitionsOperations as OperationClass + elif api_version == '2021-07-01-preview': + from ..v2021_07_01_preview.aio.operations import AccessReviewScheduleDefinitionsOperations as OperationClass + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewScheduleDefinitionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_schedule_definitions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -253,14 +437,91 @@ def access_review_schedule_definitions_assigned_for_my_approval(self): * 2018-05-01-preview: :class:`AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations` * 2021-03-01-preview: :class:`AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations` + * 2021-07-01-preview: :class:`AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations` + * 2021-12-01-preview: :class:`AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations` """ api_version = self._get_api_version('access_review_schedule_definitions_assigned_for_my_approval') if api_version == '2018-05-01-preview': from ..v2018_05_01_preview.aio.operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations as OperationClass elif api_version == '2021-03-01-preview': from ..v2021_03_01_preview.aio.operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations as OperationClass + elif api_version == '2021-07-01-preview': + from ..v2021_07_01_preview.aio.operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations as OperationClass + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'access_review_schedule_definitions_assigned_for_my_approval'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def alert_configurations(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AlertConfigurationsOperations` + """ + api_version = self._get_api_version('alert_configurations') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AlertConfigurationsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'alert_configurations'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def alert_definitions(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AlertDefinitionsOperations` + """ + api_version = self._get_api_version('alert_definitions') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AlertDefinitionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'alert_definitions'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def alert_incidents(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AlertIncidentsOperations` + """ + api_version = self._get_api_version('alert_incidents') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AlertIncidentsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'alert_incidents'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def alert_operation(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AlertOperationOperations` + """ + api_version = self._get_api_version('alert_operation') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AlertOperationOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'alert_operation'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def alerts(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`AlertsOperations` + """ + api_version = self._get_api_version('alerts') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import AlertsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'alerts'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -277,6 +538,7 @@ def classic_administrators(self): from ..v2015_07_01.aio.operations import ClassicAdministratorsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'classic_administrators'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -284,25 +546,33 @@ def deny_assignments(self): """Instance depends on the API version: * 2018-07-01-preview: :class:`DenyAssignmentsOperations` + * 2022-04-01: :class:`DenyAssignmentsOperations` """ api_version = self._get_api_version('deny_assignments') if api_version == '2018-07-01-preview': from ..v2018_07_01_preview.aio.operations import DenyAssignmentsOperations as OperationClass + elif api_version == '2022-04-01': + from ..v2022_04_01.aio.operations import DenyAssignmentsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'deny_assignments'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def eligible_child_resources(self): """Instance depends on the API version: + * 2020-10-01: :class:`EligibleChildResourcesOperations` * 2020-10-01-preview: :class:`EligibleChildResourcesOperations` """ api_version = self._get_api_version('eligible_child_resources') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from ..v2020_10_01.aio.operations import EligibleChildResourcesOperations as OperationClass + elif api_version == '2020-10-01-preview': from ..v2020_10_01_preview.aio.operations import EligibleChildResourcesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'eligible_child_resources'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -316,6 +586,7 @@ def global_administrator(self): from ..v2015_07_01.aio.operations import GlobalAdministratorOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'global_administrator'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -325,6 +596,8 @@ def operations(self): * 2018-05-01-preview: :class:`Operations` * 2021-01-01-preview: :class:`Operations` * 2021-03-01-preview: :class:`Operations` + * 2021-07-01-preview: :class:`Operations` + * 2021-12-01-preview: :class:`Operations` """ api_version = self._get_api_version('operations') if api_version == '2018-05-01-preview': @@ -333,8 +606,13 @@ def operations(self): from ..v2021_01_01_preview.aio.operations import Operations as OperationClass elif api_version == '2021-03-01-preview': from ..v2021_03_01_preview.aio.operations import Operations as OperationClass + elif api_version == '2021-07-01-preview': + from ..v2021_07_01_preview.aio.operations import Operations as OperationClass + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import Operations as OperationClass else: raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -343,14 +621,18 @@ def permissions(self): * 2015-07-01: :class:`PermissionsOperations` * 2018-01-01-preview: :class:`PermissionsOperations` + * 2022-04-01: :class:`PermissionsOperations` """ api_version = self._get_api_version('permissions') if api_version == '2015-07-01': from ..v2015_07_01.aio.operations import PermissionsOperations as OperationClass elif api_version == '2018-01-01-preview': from ..v2018_01_01_preview.aio.operations import PermissionsOperations as OperationClass + elif api_version == '2022-04-01': + from ..v2022_04_01.aio.operations import PermissionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'permissions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -359,14 +641,18 @@ def provider_operations_metadata(self): * 2015-07-01: :class:`ProviderOperationsMetadataOperations` * 2018-01-01-preview: :class:`ProviderOperationsMetadataOperations` + * 2022-04-01: :class:`ProviderOperationsMetadataOperations` """ api_version = self._get_api_version('provider_operations_metadata') if api_version == '2015-07-01': from ..v2015_07_01.aio.operations import ProviderOperationsMetadataOperations as OperationClass elif api_version == '2018-01-01-preview': from ..v2018_01_01_preview.aio.operations import ProviderOperationsMetadataOperations as OperationClass + elif api_version == '2022-04-01': + from ..v2022_04_01.aio.operations import ProviderOperationsMetadataOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'provider_operations_metadata'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -380,6 +666,7 @@ def role_assignment_approval(self): from ..v2021_01_01_preview.aio.operations import RoleAssignmentApprovalOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_approval'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -393,6 +680,7 @@ def role_assignment_approval_step(self): from ..v2021_01_01_preview.aio.operations import RoleAssignmentApprovalStepOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_approval_step'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -406,6 +694,7 @@ def role_assignment_approval_steps(self): from ..v2021_01_01_preview.aio.operations import RoleAssignmentApprovalStepsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_approval_steps'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -419,45 +708,58 @@ def role_assignment_metrics(self): from ..v2019_08_01_preview.aio.operations import RoleAssignmentMetricsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_metrics'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_assignment_schedule_instances(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleAssignmentScheduleInstancesOperations` * 2020-10-01-preview: :class:`RoleAssignmentScheduleInstancesOperations` """ api_version = self._get_api_version('role_assignment_schedule_instances') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from ..v2020_10_01.aio.operations import RoleAssignmentScheduleInstancesOperations as OperationClass + elif api_version == '2020-10-01-preview': from ..v2020_10_01_preview.aio.operations import RoleAssignmentScheduleInstancesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_schedule_instances'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_assignment_schedule_requests(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleAssignmentScheduleRequestsOperations` * 2020-10-01-preview: :class:`RoleAssignmentScheduleRequestsOperations` """ api_version = self._get_api_version('role_assignment_schedule_requests') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from ..v2020_10_01.aio.operations import RoleAssignmentScheduleRequestsOperations as OperationClass + elif api_version == '2020-10-01-preview': from ..v2020_10_01_preview.aio.operations import RoleAssignmentScheduleRequestsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_schedule_requests'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_assignment_schedules(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleAssignmentSchedulesOperations` * 2020-10-01-preview: :class:`RoleAssignmentSchedulesOperations` """ api_version = self._get_api_version('role_assignment_schedules') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from ..v2020_10_01.aio.operations import RoleAssignmentSchedulesOperations as OperationClass + elif api_version == '2020-10-01-preview': from ..v2020_10_01_preview.aio.operations import RoleAssignmentSchedulesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignment_schedules'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -469,6 +771,7 @@ def role_assignments(self): * 2018-09-01-preview: :class:`RoleAssignmentsOperations` * 2020-04-01-preview: :class:`RoleAssignmentsOperations` * 2020-10-01-preview: :class:`RoleAssignmentsOperations` + * 2022-04-01: :class:`RoleAssignmentsOperations` """ api_version = self._get_api_version('role_assignments') if api_version == '2015-07-01': @@ -481,8 +784,11 @@ def role_assignments(self): from ..v2020_04_01_preview.aio.operations import RoleAssignmentsOperations as OperationClass elif api_version == '2020-10-01-preview': from ..v2020_10_01_preview.aio.operations import RoleAssignmentsOperations as OperationClass + elif api_version == '2022-04-01': + from ..v2022_04_01.aio.operations import RoleAssignmentsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_assignments'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -491,79 +797,243 @@ def role_definitions(self): * 2015-07-01: :class:`RoleDefinitionsOperations` * 2018-01-01-preview: :class:`RoleDefinitionsOperations` + * 2022-04-01: :class:`RoleDefinitionsOperations` """ api_version = self._get_api_version('role_definitions') if api_version == '2015-07-01': from ..v2015_07_01.aio.operations import RoleDefinitionsOperations as OperationClass elif api_version == '2018-01-01-preview': from ..v2018_01_01_preview.aio.operations import RoleDefinitionsOperations as OperationClass + elif api_version == '2022-04-01': + from ..v2022_04_01.aio.operations import RoleDefinitionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_definitions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_eligibility_schedule_instances(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleEligibilityScheduleInstancesOperations` * 2020-10-01-preview: :class:`RoleEligibilityScheduleInstancesOperations` """ api_version = self._get_api_version('role_eligibility_schedule_instances') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from ..v2020_10_01.aio.operations import RoleEligibilityScheduleInstancesOperations as OperationClass + elif api_version == '2020-10-01-preview': from ..v2020_10_01_preview.aio.operations import RoleEligibilityScheduleInstancesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_eligibility_schedule_instances'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_eligibility_schedule_requests(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleEligibilityScheduleRequestsOperations` * 2020-10-01-preview: :class:`RoleEligibilityScheduleRequestsOperations` """ api_version = self._get_api_version('role_eligibility_schedule_requests') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from ..v2020_10_01.aio.operations import RoleEligibilityScheduleRequestsOperations as OperationClass + elif api_version == '2020-10-01-preview': from ..v2020_10_01_preview.aio.operations import RoleEligibilityScheduleRequestsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_eligibility_schedule_requests'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_eligibility_schedules(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleEligibilitySchedulesOperations` * 2020-10-01-preview: :class:`RoleEligibilitySchedulesOperations` """ api_version = self._get_api_version('role_eligibility_schedules') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from ..v2020_10_01.aio.operations import RoleEligibilitySchedulesOperations as OperationClass + elif api_version == '2020-10-01-preview': from ..v2020_10_01_preview.aio.operations import RoleEligibilitySchedulesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_eligibility_schedules'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_management_policies(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleManagementPoliciesOperations` * 2020-10-01-preview: :class:`RoleManagementPoliciesOperations` """ api_version = self._get_api_version('role_management_policies') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from ..v2020_10_01.aio.operations import RoleManagementPoliciesOperations as OperationClass + elif api_version == '2020-10-01-preview': from ..v2020_10_01_preview.aio.operations import RoleManagementPoliciesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_management_policies'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property def role_management_policy_assignments(self): """Instance depends on the API version: + * 2020-10-01: :class:`RoleManagementPolicyAssignmentsOperations` * 2020-10-01-preview: :class:`RoleManagementPolicyAssignmentsOperations` """ api_version = self._get_api_version('role_management_policy_assignments') - if api_version == '2020-10-01-preview': + if api_version == '2020-10-01': + from ..v2020_10_01.aio.operations import RoleManagementPolicyAssignmentsOperations as OperationClass + elif api_version == '2020-10-01-preview': from ..v2020_10_01_preview.aio.operations import RoleManagementPolicyAssignmentsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'role_management_policy_assignments'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_default_settings(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewDefaultSettingsOperations` + """ + api_version = self._get_api_version('scope_access_review_default_settings') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import ScopeAccessReviewDefaultSettingsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_default_settings'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_history_definition(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewHistoryDefinitionOperations` + """ + api_version = self._get_api_version('scope_access_review_history_definition') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import ScopeAccessReviewHistoryDefinitionOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_history_definition'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_history_definition_instance(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewHistoryDefinitionInstanceOperations` + """ + api_version = self._get_api_version('scope_access_review_history_definition_instance') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import ScopeAccessReviewHistoryDefinitionInstanceOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_history_definition_instance'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_history_definition_instances(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewHistoryDefinitionInstancesOperations` + """ + api_version = self._get_api_version('scope_access_review_history_definition_instances') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import ScopeAccessReviewHistoryDefinitionInstancesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_history_definition_instances'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_history_definitions(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewHistoryDefinitionsOperations` + """ + api_version = self._get_api_version('scope_access_review_history_definitions') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import ScopeAccessReviewHistoryDefinitionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_history_definitions'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_instance(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewInstanceOperations` + """ + api_version = self._get_api_version('scope_access_review_instance') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import ScopeAccessReviewInstanceOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_instance'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_instance_contacted_reviewers(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewInstanceContactedReviewersOperations` + """ + api_version = self._get_api_version('scope_access_review_instance_contacted_reviewers') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import ScopeAccessReviewInstanceContactedReviewersOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_instance_contacted_reviewers'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_instance_decisions(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewInstanceDecisionsOperations` + """ + api_version = self._get_api_version('scope_access_review_instance_decisions') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import ScopeAccessReviewInstanceDecisionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_instance_decisions'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_instances(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewInstancesOperations` + """ + api_version = self._get_api_version('scope_access_review_instances') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import ScopeAccessReviewInstancesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_instances'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def scope_access_review_schedule_definitions(self): + """Instance depends on the API version: + + * 2021-12-01-preview: :class:`ScopeAccessReviewScheduleDefinitionsOperations` + """ + api_version = self._get_api_version('scope_access_review_schedule_definitions') + if api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import ScopeAccessReviewScheduleDefinitionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'scope_access_review_schedule_definitions'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -577,6 +1047,7 @@ def scope_role_assignment_approval(self): from ..v2021_01_01_preview.aio.operations import ScopeRoleAssignmentApprovalOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'scope_role_assignment_approval'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -590,6 +1061,7 @@ def scope_role_assignment_approval_step(self): from ..v2021_01_01_preview.aio.operations import ScopeRoleAssignmentApprovalStepOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'scope_role_assignment_approval_step'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -603,6 +1075,24 @@ def scope_role_assignment_approval_steps(self): from ..v2021_01_01_preview.aio.operations import ScopeRoleAssignmentApprovalStepsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'scope_role_assignment_approval_steps'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def tenant_level_access_review_instance_contacted_reviewers(self): + """Instance depends on the API version: + + * 2021-07-01-preview: :class:`TenantLevelAccessReviewInstanceContactedReviewersOperations` + * 2021-12-01-preview: :class:`TenantLevelAccessReviewInstanceContactedReviewersOperations` + """ + api_version = self._get_api_version('tenant_level_access_review_instance_contacted_reviewers') + if api_version == '2021-07-01-preview': + from ..v2021_07_01_preview.aio.operations import TenantLevelAccessReviewInstanceContactedReviewersOperations as OperationClass + elif api_version == '2021-12-01-preview': + from ..v2021_12_01_preview.aio.operations import TenantLevelAccessReviewInstanceContactedReviewersOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'tenant_level_access_review_instance_contacted_reviewers'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) async def close(self): diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/aio/_configuration.py index cf4c9ef9bf9..502298fa495 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/aio/_configuration.py @@ -12,7 +12,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -26,9 +26,9 @@ class AuthorizationManagementClientConfiguration(Configuration): Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str """ @@ -64,4 +64,4 @@ def _configure( self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/models.py index 3fc87a882b8..d83931c4919 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/models.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/models.py @@ -5,3 +5,8 @@ # license information. # -------------------------------------------------------------------------- from .v2015_07_01.models import * +from .v2019_08_01_preview.models import * +from .v2020_10_01.models import * +from .v2021_01_01_preview.models import * +from .v2021_12_01_preview.models import * +from .v2022_04_01.models import * diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/__init__.py index ae11ad3e4d9..9eb8d3ec28c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AuthorizationManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_authorization_management_client.py index 0dca81078c2..741bc9176d5 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_authorization_management_client.py @@ -6,73 +6,83 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ClassicAdministratorsOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import ClassicAdministratorsOperations -from . import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role definitions and role assignments. A role definition describes the set of actions that can be performed on resources. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + definitions and role assignments. A role definition describes the set of actions that can be + performed on resources. A role assignment grants access to Azure Active Directory users. :ivar classic_administrators: ClassicAdministratorsOperations operations - :vartype classic_administrators: azure.mgmt.authorization.v2015_06_01.operations.ClassicAdministratorsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype classic_administrators: + azure.mgmt.authorization.v2015_06_01.operations.ClassicAdministratorsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2015-06-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.classic_administrators = ClassicAdministratorsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_configuration.py index 9f3e1d52165..f4e0aa46402 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_configuration.py @@ -6,66 +6,64 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-06-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2015-06-01") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2015-06-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_metadata.json index 93f9a8785b8..cfef4806a84 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_metadata.json +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_metadata.json @@ -5,25 +5,25 @@ "name": "AuthorizationManagementClient", "filename": "_authorization_management_client", "description": "Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role definitions and role assignments. A role definition describes the set of actions that can be performed on resources. A role assignment grants access to Azure Active Directory users.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, "azure_arm": true, "has_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -54,7 +54,7 @@ "required": false }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -74,7 +74,7 @@ "required": false }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -91,11 +91,10 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "classic_administrators": "ClassicAdministratorsOperations" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_version.py index 48944bf3938..cac9f5d10f8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/__init__.py index ffc49d028e4..dd28625b36f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._authorization_management_client import AuthorizationManagementClient -__all__ = ['AuthorizationManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_authorization_management_client.py index cb8cddb257e..7cdba0c76b9 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_authorization_management_client.py @@ -6,69 +6,83 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ClassicAdministratorsOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import ClassicAdministratorsOperations -from .. import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role definitions and role assignments. A role definition describes the set of actions that can be performed on resources. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + definitions and role assignments. A role definition describes the set of actions that can be + performed on resources. A role assignment grants access to Azure Active Directory users. :ivar classic_administrators: ClassicAdministratorsOperations operations - :vartype classic_administrators: azure.mgmt.authorization.v2015_06_01.aio.operations.ClassicAdministratorsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype classic_administrators: + azure.mgmt.authorization.v2015_06_01.aio.operations.ClassicAdministratorsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2015-06-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.classic_administrators = ClassicAdministratorsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_configuration.py index 1310486fc39..eb55f967b88 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,49 +19,48 @@ from azure.core.credentials_async import AsyncTokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-06-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2015-06-01") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2015-06-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/__init__.py index 649828c5f3b..9e01044d00f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/__init__.py @@ -8,6 +8,12 @@ from ._classic_administrators_operations import ClassicAdministratorsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'ClassicAdministratorsOperations', + "ClassicAdministratorsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/_classic_administrators_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/_classic_administrators_operations.py index 824b5fc117b..49501032e89 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/_classic_administrators_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/_classic_administrators_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,86 +6,103 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._classic_administrators_operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ClassicAdministratorsOperations: - """ClassicAdministratorsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ClassicAdministratorsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_06_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_06_01.aio.AuthorizationManagementClient`'s + :attr:`classic_administrators` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.ClassicAdministratorListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.ClassicAdministrator"]: """Gets service administrator, account administrator, and co-administrators for the subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ClassicAdministratorListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_06_01.models.ClassicAdministratorListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ClassicAdministrator or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_06_01.models.ClassicAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ClassicAdministratorListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ClassicAdministratorListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-06-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ClassicAdministratorListResult', pipeline_response) + deserialized = self._deserialize("ClassicAdministratorListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -93,17 +111,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/__init__.py index 32a64afe535..2880be4b939 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/__init__.py @@ -6,23 +6,21 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ClassicAdministrator - from ._models_py3 import ClassicAdministratorListResult - from ._models_py3 import ErrorAdditionalInfo - from ._models_py3 import ErrorDetail - from ._models_py3 import ErrorResponse -except (SyntaxError, ImportError): - from ._models import ClassicAdministrator # type: ignore - from ._models import ClassicAdministratorListResult # type: ignore - from ._models import ErrorAdditionalInfo # type: ignore - from ._models import ErrorDetail # type: ignore - from ._models import ErrorResponse # type: ignore +from ._models_py3 import ClassicAdministrator +from ._models_py3 import ClassicAdministratorListResult +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ClassicAdministrator', - 'ClassicAdministratorListResult', - 'ErrorAdditionalInfo', - 'ErrorDetail', - 'ErrorResponse', + "ClassicAdministrator", + "ClassicAdministratorListResult", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_models.py deleted file mode 100644 index fcb7089a661..00000000000 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_models.py +++ /dev/null @@ -1,163 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class ClassicAdministrator(msrest.serialization.Model): - """Classic Administrators. - - :param id: The ID of the administrator. - :type id: str - :param name: The name of the administrator. - :type name: str - :param type: The type of the administrator. - :type type: str - :param email_address: The email address of the administrator. - :type email_address: str - :param role: The role of the administrator. - :type role: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'email_address': {'key': 'properties.emailAddress', 'type': 'str'}, - 'role': {'key': 'properties.role', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ClassicAdministrator, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.name = kwargs.get('name', None) - self.type = kwargs.get('type', None) - self.email_address = kwargs.get('email_address', None) - self.role = kwargs.get('role', None) - - -class ClassicAdministratorListResult(msrest.serialization.Model): - """ClassicAdministrator list result information. - - :param value: An array of administrators. - :type value: list[~azure.mgmt.authorization.v2015_06_01.models.ClassicAdministrator] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[ClassicAdministrator]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ClassicAdministratorListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class ErrorAdditionalInfo(msrest.serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(msrest.serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.authorization.v2015_06_01.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.mgmt.authorization.v2015_06_01.models.ErrorAdditionalInfo] - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(msrest.serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2015_06_01.models.ErrorDetail - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_models_py3.py index 9c121234dcd..d03ac48443d 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_models_py3.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -6,46 +7,61 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import List, Optional +from typing import List, Optional, TYPE_CHECKING -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class ClassicAdministrator(msrest.serialization.Model): + +class ClassicAdministrator(_serialization.Model): """Classic Administrators. - :param id: The ID of the administrator. - :type id: str - :param name: The name of the administrator. - :type name: str - :param type: The type of the administrator. - :type type: str - :param email_address: The email address of the administrator. - :type email_address: str - :param role: The role of the administrator. - :type role: str + :ivar id: The ID of the administrator. + :vartype id: str + :ivar name: The name of the administrator. + :vartype name: str + :ivar type: The type of the administrator. + :vartype type: str + :ivar email_address: The email address of the administrator. + :vartype email_address: str + :ivar role: The role of the administrator. + :vartype role: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'email_address': {'key': 'properties.emailAddress', 'type': 'str'}, - 'role': {'key': 'properties.role', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "email_address": {"key": "properties.emailAddress", "type": "str"}, + "role": {"key": "properties.role", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, email_address: Optional[str] = None, role: Optional[str] = None, **kwargs ): - super(ClassicAdministrator, self).__init__(**kwargs) + """ + :keyword id: The ID of the administrator. + :paramtype id: str + :keyword name: The name of the administrator. + :paramtype name: str + :keyword type: The type of the administrator. + :paramtype type: str + :keyword email_address: The email address of the administrator. + :paramtype email_address: str + :keyword role: The role of the administrator. + :paramtype role: str + """ + super().__init__(**kwargs) self.id = id self.name = name self.type = type @@ -53,33 +69,35 @@ def __init__( self.role = role -class ClassicAdministratorListResult(msrest.serialization.Model): +class ClassicAdministratorListResult(_serialization.Model): """ClassicAdministrator list result information. - :param value: An array of administrators. - :type value: list[~azure.mgmt.authorization.v2015_06_01.models.ClassicAdministrator] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: An array of administrators. + :vartype value: list[~azure.mgmt.authorization.v2015_06_01.models.ClassicAdministrator] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ClassicAdministrator]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ClassicAdministrator]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["ClassicAdministrator"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.ClassicAdministrator"]] = None, next_link: Optional[str] = None, **kwargs ): - super(ClassicAdministratorListResult, self).__init__(**kwargs) + """ + :keyword value: An array of administrators. + :paramtype value: list[~azure.mgmt.authorization.v2015_06_01.models.ClassicAdministrator] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ErrorAdditionalInfo(msrest.serialization.Model): +class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. @@ -87,29 +105,27 @@ class ErrorAdditionalInfo(msrest.serialization.Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: any + :vartype info: JSON """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None -class ErrorDetail(msrest.serialization.Model): +class ErrorDetail(_serialization.Model): """The error detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -128,26 +144,24 @@ class ErrorDetail(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -155,22 +169,21 @@ def __init__( self.additional_info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2015_06_01.models.ErrorDetail + :ivar error: The error object. + :vartype error: ~azure.mgmt.authorization.v2015_06_01.models.ErrorDetail """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, + "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__( - self, - *, - error: Optional["ErrorDetail"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.authorization.v2015_06_01.models.ErrorDetail + """ + super().__init__(**kwargs) self.error = error diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/__init__.py index 649828c5f3b..9e01044d00f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/__init__.py @@ -8,6 +8,12 @@ from ._classic_administrators_operations import ClassicAdministratorsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'ClassicAdministratorsOperations', + "ClassicAdministratorsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/_classic_administrators_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/_classic_administrators_operations.py index d1a65c48396..e9efdd59d62 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/_classic_administrators_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/_classic_administrators_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,91 +6,132 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } -class ClassicAdministratorsOperations(object): - """ClassicAdministratorsOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_06_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ClassicAdministratorsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_06_01.AuthorizationManagementClient`'s + :attr:`classic_administrators` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ClassicAdministratorListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.ClassicAdministrator"]: """Gets service administrator, account administrator, and co-administrators for the subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ClassicAdministratorListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_06_01.models.ClassicAdministratorListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ClassicAdministrator or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_06_01.models.ClassicAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ClassicAdministratorListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ClassicAdministratorListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-06-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ClassicAdministratorListResult', pipeline_response) + deserialized = self._deserialize("ClassicAdministratorListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -98,17 +140,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_06_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/__init__.py index ae11ad3e4d9..9eb8d3ec28c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AuthorizationManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_authorization_management_client.py index b40276826ca..78926d77a8f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_authorization_management_client.py @@ -6,98 +6,117 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + ClassicAdministratorsOperations, + GlobalAdministratorOperations, + PermissionsOperations, + ProviderOperationsMetadataOperations, + RoleAssignmentsOperations, + RoleDefinitionsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import PermissionsOperations -from .operations import RoleDefinitionsOperations -from .operations import ProviderOperationsMetadataOperations -from .operations import GlobalAdministratorOperations -from .operations import RoleAssignmentsOperations -from .operations import ClassicAdministratorsOperations -from . import models -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role definitions and role assignments. A role definition describes the set of actions that can be performed on resources. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + definitions and role assignments. A role definition describes the set of actions that can be + performed on resources. A role assignment grants access to Azure Active Directory users. :ivar permissions: PermissionsOperations operations :vartype permissions: azure.mgmt.authorization.v2015_07_01.operations.PermissionsOperations :ivar role_definitions: RoleDefinitionsOperations operations - :vartype role_definitions: azure.mgmt.authorization.v2015_07_01.operations.RoleDefinitionsOperations + :vartype role_definitions: + azure.mgmt.authorization.v2015_07_01.operations.RoleDefinitionsOperations :ivar provider_operations_metadata: ProviderOperationsMetadataOperations operations - :vartype provider_operations_metadata: azure.mgmt.authorization.v2015_07_01.operations.ProviderOperationsMetadataOperations + :vartype provider_operations_metadata: + azure.mgmt.authorization.v2015_07_01.operations.ProviderOperationsMetadataOperations :ivar global_administrator: GlobalAdministratorOperations operations - :vartype global_administrator: azure.mgmt.authorization.v2015_07_01.operations.GlobalAdministratorOperations + :vartype global_administrator: + azure.mgmt.authorization.v2015_07_01.operations.GlobalAdministratorOperations :ivar role_assignments: RoleAssignmentsOperations operations - :vartype role_assignments: azure.mgmt.authorization.v2015_07_01.operations.RoleAssignmentsOperations + :vartype role_assignments: + azure.mgmt.authorization.v2015_07_01.operations.RoleAssignmentsOperations :ivar classic_administrators: ClassicAdministratorsOperations operations - :vartype classic_administrators: azure.mgmt.authorization.v2015_07_01.operations.ClassicAdministratorsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype classic_administrators: + azure.mgmt.authorization.v2015_07_01.operations.ClassicAdministratorsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2015-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.permissions = PermissionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.permissions = PermissionsOperations(self._client, self._config, self._serialize, self._deserialize) self.role_definitions = RoleDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.provider_operations_metadata = ProviderOperationsMetadataOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.global_administrator = GlobalAdministratorOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignments = RoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.classic_administrators = ClassicAdministratorsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_configuration.py index 1f5e4f5da82..ca09948b8d4 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_configuration.py @@ -6,66 +6,64 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2015-07-01") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2015-07-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_metadata.json index 49f02d47074..ae96668f87b 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_metadata.json +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_metadata.json @@ -5,25 +5,25 @@ "name": "AuthorizationManagementClient", "filename": "_authorization_management_client", "description": "Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role definitions and role assignments. A role definition describes the set of actions that can be performed on resources. A role assignment grants access to Azure Active Directory users.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, "azure_arm": true, "has_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -54,7 +54,7 @@ "required": false }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -74,7 +74,7 @@ "required": false }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -91,11 +91,10 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "permissions": "PermissionsOperations", diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_version.py index 48944bf3938..cac9f5d10f8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/__init__.py index ffc49d028e4..dd28625b36f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._authorization_management_client import AuthorizationManagementClient -__all__ = ['AuthorizationManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_authorization_management_client.py index 1061b48b1e9..1b1376b5421 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_authorization_management_client.py @@ -6,94 +6,117 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + ClassicAdministratorsOperations, + GlobalAdministratorOperations, + PermissionsOperations, + ProviderOperationsMetadataOperations, + RoleAssignmentsOperations, + RoleDefinitionsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import PermissionsOperations -from .operations import RoleDefinitionsOperations -from .operations import ProviderOperationsMetadataOperations -from .operations import GlobalAdministratorOperations -from .operations import RoleAssignmentsOperations -from .operations import ClassicAdministratorsOperations -from .. import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role definitions and role assignments. A role definition describes the set of actions that can be performed on resources. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + definitions and role assignments. A role definition describes the set of actions that can be + performed on resources. A role assignment grants access to Azure Active Directory users. :ivar permissions: PermissionsOperations operations :vartype permissions: azure.mgmt.authorization.v2015_07_01.aio.operations.PermissionsOperations :ivar role_definitions: RoleDefinitionsOperations operations - :vartype role_definitions: azure.mgmt.authorization.v2015_07_01.aio.operations.RoleDefinitionsOperations + :vartype role_definitions: + azure.mgmt.authorization.v2015_07_01.aio.operations.RoleDefinitionsOperations :ivar provider_operations_metadata: ProviderOperationsMetadataOperations operations - :vartype provider_operations_metadata: azure.mgmt.authorization.v2015_07_01.aio.operations.ProviderOperationsMetadataOperations + :vartype provider_operations_metadata: + azure.mgmt.authorization.v2015_07_01.aio.operations.ProviderOperationsMetadataOperations :ivar global_administrator: GlobalAdministratorOperations operations - :vartype global_administrator: azure.mgmt.authorization.v2015_07_01.aio.operations.GlobalAdministratorOperations + :vartype global_administrator: + azure.mgmt.authorization.v2015_07_01.aio.operations.GlobalAdministratorOperations :ivar role_assignments: RoleAssignmentsOperations operations - :vartype role_assignments: azure.mgmt.authorization.v2015_07_01.aio.operations.RoleAssignmentsOperations + :vartype role_assignments: + azure.mgmt.authorization.v2015_07_01.aio.operations.RoleAssignmentsOperations :ivar classic_administrators: ClassicAdministratorsOperations operations - :vartype classic_administrators: azure.mgmt.authorization.v2015_07_01.aio.operations.ClassicAdministratorsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype classic_administrators: + azure.mgmt.authorization.v2015_07_01.aio.operations.ClassicAdministratorsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2015-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.permissions = PermissionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.permissions = PermissionsOperations(self._client, self._config, self._serialize, self._deserialize) self.role_definitions = RoleDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.provider_operations_metadata = ProviderOperationsMetadataOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.global_administrator = GlobalAdministratorOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignments = RoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.classic_administrators = ClassicAdministratorsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_configuration.py index a75a520500e..2494b3a2715 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,49 +19,48 @@ from azure.core.credentials_async import AsyncTokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2015-07-01") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2015-07-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/__init__.py index 751b809fce0..dc8d1317eb2 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/__init__.py @@ -13,11 +13,17 @@ from ._role_assignments_operations import RoleAssignmentsOperations from ._classic_administrators_operations import ClassicAdministratorsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'PermissionsOperations', - 'RoleDefinitionsOperations', - 'ProviderOperationsMetadataOperations', - 'GlobalAdministratorOperations', - 'RoleAssignmentsOperations', - 'ClassicAdministratorsOperations', + "PermissionsOperations", + "RoleDefinitionsOperations", + "ProviderOperationsMetadataOperations", + "GlobalAdministratorOperations", + "RoleAssignmentsOperations", + "ClassicAdministratorsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_classic_administrators_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_classic_administrators_operations.py index 32391e0679d..333247eafc8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_classic_administrators_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_classic_administrators_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,86 +6,103 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._classic_administrators_operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ClassicAdministratorsOperations: - """ClassicAdministratorsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ClassicAdministratorsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.aio.AuthorizationManagementClient`'s + :attr:`classic_administrators` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.ClassicAdministratorListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.ClassicAdministrator"]: """Gets service administrator, account administrator, and co-administrators for the subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ClassicAdministratorListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.ClassicAdministratorListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ClassicAdministrator or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.ClassicAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ClassicAdministratorListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ClassicAdministratorListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ClassicAdministratorListResult', pipeline_response) + deserialized = self._deserialize("ClassicAdministratorListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -93,17 +111,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_global_administrator_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_global_administrator_operations.py index 058e2936425..5b899a29570 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_global_administrator_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_global_administrator_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,81 +6,94 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._global_administrator_operations import build_elevate_access_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class GlobalAdministratorOperations: - """GlobalAdministratorOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class GlobalAdministratorOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.aio.AuthorizationManagementClient`'s + :attr:`global_administrator` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def elevate_access( - self, - **kwargs: Any - ) -> None: + @distributed_trace_async + async def elevate_access(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """Elevates access for a Global Administrator. :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct URL - url = self.elevate_access.metadata['url'] # type: ignore + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_elevate_access_request( + api_version=api_version, + template_url=self.elevate_access.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - elevate_access.metadata = {'url': '/providers/Microsoft.Authorization/elevateAccess'} # type: ignore + elevate_access.metadata = {"url": "/providers/Microsoft.Authorization/elevateAccess"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_permissions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_permissions_operations.py index b050a906cff..41440ce2d7b 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_permissions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_permissions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,90 +6,106 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._permissions_operations import build_list_for_resource_group_request, build_list_for_resource_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PermissionsOperations: - """PermissionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PermissionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.aio.AuthorizationManagementClient`'s + :attr:`permissions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list_for_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.PermissionGetResult"]: + @distributed_trace + def list_for_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Permission"]: """Gets all permissions the caller has for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PermissionGetResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.PermissionGetResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PermissionGetResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PermissionGetResult', pipeline_response) + deserialized = self._deserialize("PermissionGetResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -97,21 +114,23 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions"} # type: ignore + @distributed_trace def list_for_resource( self, resource_group_name: str, @@ -120,62 +139,71 @@ def list_for_resource( resource_type: str, resource_name: str, **kwargs: Any - ) -> AsyncIterable["_models.PermissionGetResult"]: + ) -> AsyncIterable["_models.Permission"]: """Gets all permissions the caller has for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get the permissions for. + :param resource_name: The name of the resource to get the permissions for. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PermissionGetResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.PermissionGetResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PermissionGetResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str'), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PermissionGetResult', pipeline_response) + deserialized = self._deserialize("PermissionGetResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -184,17 +212,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_provider_operations_metadata_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_provider_operations_metadata_operations.py index c8e7457bb26..924ac5ccf61 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_provider_operations_metadata_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_provider_operations_metadata_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,146 +6,166 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._provider_operations_metadata_operations import build_get_request, build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ProviderOperationsMetadataOperations: - """ProviderOperationsMetadataOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ProviderOperationsMetadataOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.aio.AuthorizationManagementClient`'s + :attr:`provider_operations_metadata` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace_async async def get( - self, - resource_provider_namespace: str, - expand: Optional[str] = "resourceTypes", - **kwargs: Any - ) -> "_models.ProviderOperationsMetadata": + self, resource_provider_namespace: str, expand: str = "resourceTypes", **kwargs: Any + ) -> _models.ProviderOperationsMetadata: """Gets provider operations metadata for the specified resource provider. - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param expand: Specifies whether to expand the values. + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ProviderOperationsMetadata, or the result of cls(response) + :return: ProviderOperationsMetadata or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.ProviderOperationsMetadata - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProviderOperationsMetadata"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadata] + + request = build_get_request( + resource_provider_namespace=resource_provider_namespace, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ProviderOperationsMetadata', pipeline_response) + deserialized = self._deserialize("ProviderOperationsMetadata", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}'} # type: ignore - def list( - self, - expand: Optional[str] = "resourceTypes", - **kwargs: Any - ) -> AsyncIterable["_models.ProviderOperationsMetadataListResult"]: + get.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}"} # type: ignore + + @distributed_trace + def list(self, expand: str = "resourceTypes", **kwargs: Any) -> AsyncIterable["_models.ProviderOperationsMetadata"]: """Gets provider operations metadata for all resource providers. - :param expand: Specifies whether to expand the values. + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProviderOperationsMetadataListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperationsMetadataListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ProviderOperationsMetadata or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperationsMetadata] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProviderOperationsMetadataListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadataListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ProviderOperationsMetadataListResult', pipeline_response) + deserialized = self._deserialize("ProviderOperationsMetadataListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -153,17 +174,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/providerOperations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_role_assignments_operations.py index eb201def655..9cba2302967 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_role_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,42 +6,65 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_assignments_operations import ( + build_create_by_id_request, + build_create_request, + build_delete_by_id_request, + build_delete_request, + build_get_by_id_request, + build_get_request, + build_list_for_resource_group_request, + build_list_for_resource_request, + build_list_for_scope_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentsOperations: - """RoleAssignmentsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.aio.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_resource( self, resource_group_name: str, @@ -50,68 +74,76 @@ def list_for_resource( resource_name: str, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + ) -> AsyncIterable["_models.RoleAssignment"]: """Gets role assignments for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get role assignments for. + :param resource_name: The name of the resource to get role assignments for. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str'), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -120,76 +152,83 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace def list_for_resource_group( - self, - resource_group_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """Gets role assignments for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -198,88 +237,125 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def delete( - self, - scope: str, - role_assignment_name: str, - **kwargs: Any - ) -> Optional["_models.RoleAssignment"]: + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace_async + async def delete(self, scope: str, role_assignment_name: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. - :param scope: The scope of the role assignment to delete. + :param scope: The scope of the role assignment to delete. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to delete. + :param role_assignment_name: The name of the role assignment to delete. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload async def create( self, scope: str, role_assignment_name: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: IO, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignment": + ) -> _models.RoleAssignment: """Creates a role assignment. :param scope: The scope of the role assignment to create. The scope can be any REST resource @@ -287,354 +363,475 @@ async def create( '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to create. It can be any valid - GUID. + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. :type parameters: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentCreateParameters + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - async def get( - self, - scope: str, - role_assignment_name: str, - **kwargs: Any - ) -> "_models.RoleAssignment": + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, role_assignment_name: str, **kwargs: Any) -> _models.RoleAssignment: """Get the specified role assignment. - :param scope: The scope of the role assignment. + :param scope: The scope of the role assignment. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to get. + :param role_assignment_name: The name of the role assignment to get. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - async def delete_by_id( - self, - role_assignment_id: str, - **kwargs: Any - ) -> Optional["_models.RoleAssignment"]: + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace_async + async def delete_by_id(self, role_assignment_id: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. :param role_assignment_id: The fully qualified ID of the role assignment, including the scope, resource name and resource type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. + Required. :type role_assignment_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_delete_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore + delete_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @overload async def create_by_id( self, role_assignment_id: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignment": + ) -> _models.RoleAssignment: """Creates a role assignment by ID. :param role_assignment_id: The fully qualified ID of the role assignment, including the scope, resource name and resource type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. + Required. :type role_assignment_id: str - :param parameters: Parameters for the role assignment. + :param parameters: Parameters for the role assignment. Required. :type parameters: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, role_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment, including the scope, + resource name and resource type. Use the format, + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, role_assignment_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment, including the scope, + resource name and resource type. Use the format, + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentCreateParameters + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore - async def get_by_id( - self, - role_assignment_id: str, - **kwargs: Any - ) -> "_models.RoleAssignment": + create_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, role_assignment_id: str, **kwargs: Any) -> _models.RoleAssignment: """Gets a role assignment by ID. :param role_assignment_id: The fully qualified ID of the role assignment, including the scope, resource name and resource type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. + Required. :type role_assignment_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore - def list( - self, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + get_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.RoleAssignment"]: """Gets all role assignments for the subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -643,75 +840,81 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """Gets role assignments for a scope. - :param scope: The scope of the role assignments. + :param scope: The scope of the role assignments. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -720,17 +923,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_role_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_role_definitions_operations.py index 1de28f66337..9093cc69aea 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_role_definitions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/aio/operations/_role_definitions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,279 +6,365 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_definitions_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_by_id_request, + build_get_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleDefinitionsOperations: - """RoleDefinitionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.aio.AuthorizationManagementClient`'s + :attr:`role_definitions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def delete( - self, - scope: str, - role_definition_id: str, - **kwargs: Any - ) -> Optional["_models.RoleDefinition"]: + @distributed_trace_async + async def delete(self, scope: str, role_definition_id: str, **kwargs: Any) -> Optional[_models.RoleDefinition]: """Deletes a role definition. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition to delete. + :param role_definition_id: The ID of the role definition to delete. Required. :type role_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleDefinition"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleDefinition]] + + request = build_delete_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore - async def get( - self, - scope: str, - role_definition_id: str, - **kwargs: Any - ) -> "_models.RoleDefinition": + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, role_definition_id: str, **kwargs: Any) -> _models.RoleDefinition: """Get role definition by name (GUID). - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition. + :param role_definition_id: The ID of the role definition. Required. :type role_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @overload async def create_or_update( self, scope: str, role_definition_id: str, - role_definition: "_models.RoleDefinition", + role_definition: _models.RoleDefinition, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleDefinition": + ) -> _models.RoleDefinition: """Creates or updates a role definition. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition. + :param role_definition_id: The ID of the role definition. Required. :type role_definition_id: str - :param role_definition: The values for the role definition. + :param role_definition: The values for the role definition. Required. :type role_definition: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + scope: str, + role_definition_id: str, + role_definition: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Required. + :type role_definition: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, scope: str, role_definition_id: str, role_definition: Union[_models.RoleDefinition, IO], **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Is either a model type or a IO + type. Required. + :type role_definition: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(role_definition, 'RoleDefinition') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(role_definition, (IO, bytes)): + _content = role_definition + else: + _json = self._serialize.body(role_definition, "RoleDefinition") + + request = build_create_or_update_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore - def list( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleDefinitionListResult"]: + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace + def list(self, scope: str, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.RoleDefinition"]: """Get all role definitions that are applicable at scope and above. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str :param filter: The filter to apply on the operation. Use atScopeAndBelow filter to search below - the given scope as well. + the given scope as well. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("RoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -286,75 +373,77 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get_by_id( - self, - role_definition_id: str, - **kwargs: Any - ) -> "_models.RoleDefinition": + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, role_definition_id: str, **kwargs: Any) -> _models.RoleDefinition: """Gets a role definition by ID. :param role_definition_id: The fully qualified role definition ID. Use the format, /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for subscription level role definitions, or /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for tenant level role - definitions. + definitions. Required. :type role_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleDefinitionId}'} # type: ignore + + get_by_id.metadata = {"url": "/{roleDefinitionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/__init__.py index 0440ade890b..6081c8853a0 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/__init__.py @@ -6,68 +6,51 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ClassicAdministrator - from ._models_py3 import ClassicAdministratorListResult - from ._models_py3 import ErrorAdditionalInfo - from ._models_py3 import ErrorDetail - from ._models_py3 import ErrorResponse - from ._models_py3 import Permission - from ._models_py3 import PermissionGetResult - from ._models_py3 import ProviderOperation - from ._models_py3 import ProviderOperationsMetadata - from ._models_py3 import ProviderOperationsMetadataListResult - from ._models_py3 import ResourceType - from ._models_py3 import RoleAssignment - from ._models_py3 import RoleAssignmentCreateParameters - from ._models_py3 import RoleAssignmentFilter - from ._models_py3 import RoleAssignmentListResult - from ._models_py3 import RoleAssignmentProperties - from ._models_py3 import RoleAssignmentPropertiesWithScope - from ._models_py3 import RoleDefinition - from ._models_py3 import RoleDefinitionFilter - from ._models_py3 import RoleDefinitionListResult -except (SyntaxError, ImportError): - from ._models import ClassicAdministrator # type: ignore - from ._models import ClassicAdministratorListResult # type: ignore - from ._models import ErrorAdditionalInfo # type: ignore - from ._models import ErrorDetail # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import Permission # type: ignore - from ._models import PermissionGetResult # type: ignore - from ._models import ProviderOperation # type: ignore - from ._models import ProviderOperationsMetadata # type: ignore - from ._models import ProviderOperationsMetadataListResult # type: ignore - from ._models import ResourceType # type: ignore - from ._models import RoleAssignment # type: ignore - from ._models import RoleAssignmentCreateParameters # type: ignore - from ._models import RoleAssignmentFilter # type: ignore - from ._models import RoleAssignmentListResult # type: ignore - from ._models import RoleAssignmentProperties # type: ignore - from ._models import RoleAssignmentPropertiesWithScope # type: ignore - from ._models import RoleDefinition # type: ignore - from ._models import RoleDefinitionFilter # type: ignore - from ._models import RoleDefinitionListResult # type: ignore +from ._models_py3 import ClassicAdministrator +from ._models_py3 import ClassicAdministratorListResult +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import Permission +from ._models_py3 import PermissionGetResult +from ._models_py3 import ProviderOperation +from ._models_py3 import ProviderOperationsMetadata +from ._models_py3 import ProviderOperationsMetadataListResult +from ._models_py3 import ResourceType +from ._models_py3 import RoleAssignment +from ._models_py3 import RoleAssignmentCreateParameters +from ._models_py3 import RoleAssignmentFilter +from ._models_py3 import RoleAssignmentListResult +from ._models_py3 import RoleAssignmentProperties +from ._models_py3 import RoleAssignmentPropertiesWithScope +from ._models_py3 import RoleDefinition +from ._models_py3 import RoleDefinitionFilter +from ._models_py3 import RoleDefinitionListResult +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ClassicAdministrator', - 'ClassicAdministratorListResult', - 'ErrorAdditionalInfo', - 'ErrorDetail', - 'ErrorResponse', - 'Permission', - 'PermissionGetResult', - 'ProviderOperation', - 'ProviderOperationsMetadata', - 'ProviderOperationsMetadataListResult', - 'ResourceType', - 'RoleAssignment', - 'RoleAssignmentCreateParameters', - 'RoleAssignmentFilter', - 'RoleAssignmentListResult', - 'RoleAssignmentProperties', - 'RoleAssignmentPropertiesWithScope', - 'RoleDefinition', - 'RoleDefinitionFilter', - 'RoleDefinitionListResult', + "ClassicAdministrator", + "ClassicAdministratorListResult", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "Permission", + "PermissionGetResult", + "ProviderOperation", + "ProviderOperationsMetadata", + "ProviderOperationsMetadataListResult", + "ResourceType", + "RoleAssignment", + "RoleAssignmentCreateParameters", + "RoleAssignmentFilter", + "RoleAssignmentListResult", + "RoleAssignmentProperties", + "RoleAssignmentPropertiesWithScope", + "RoleDefinition", + "RoleDefinitionFilter", + "RoleDefinitionListResult", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_models.py deleted file mode 100644 index b8bd200b487..00000000000 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_models.py +++ /dev/null @@ -1,595 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class ClassicAdministrator(msrest.serialization.Model): - """Classic Administrators. - - :param id: The ID of the administrator. - :type id: str - :param name: The name of the administrator. - :type name: str - :param type: The type of the administrator. - :type type: str - :param email_address: The email address of the administrator. - :type email_address: str - :param role: The role of the administrator. - :type role: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'email_address': {'key': 'properties.emailAddress', 'type': 'str'}, - 'role': {'key': 'properties.role', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ClassicAdministrator, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.name = kwargs.get('name', None) - self.type = kwargs.get('type', None) - self.email_address = kwargs.get('email_address', None) - self.role = kwargs.get('role', None) - - -class ClassicAdministratorListResult(msrest.serialization.Model): - """ClassicAdministrator list result information. - - :param value: An array of administrators. - :type value: list[~azure.mgmt.authorization.v2015_07_01.models.ClassicAdministrator] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[ClassicAdministrator]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ClassicAdministratorListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class ErrorAdditionalInfo(msrest.serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(msrest.serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.authorization.v2015_07_01.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.mgmt.authorization.v2015_07_01.models.ErrorAdditionalInfo] - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(msrest.serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2015_07_01.models.ErrorDetail - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class Permission(msrest.serialization.Model): - """Role definition permissions. - - :param actions: Allowed actions. - :type actions: list[str] - :param not_actions: Denied actions. - :type not_actions: list[str] - """ - - _attribute_map = { - 'actions': {'key': 'actions', 'type': '[str]'}, - 'not_actions': {'key': 'notActions', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(Permission, self).__init__(**kwargs) - self.actions = kwargs.get('actions', None) - self.not_actions = kwargs.get('not_actions', None) - - -class PermissionGetResult(msrest.serialization.Model): - """Permissions information. - - :param value: An array of permissions. - :type value: list[~azure.mgmt.authorization.v2015_07_01.models.Permission] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Permission]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PermissionGetResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class ProviderOperation(msrest.serialization.Model): - """Operation. - - :param name: The operation name. - :type name: str - :param display_name: The operation display name. - :type display_name: str - :param description: The operation description. - :type description: str - :param origin: The operation origin. - :type origin: str - :param properties: The operation properties. - :type properties: any - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'origin': {'key': 'origin', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(ProviderOperation, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.display_name = kwargs.get('display_name', None) - self.description = kwargs.get('description', None) - self.origin = kwargs.get('origin', None) - self.properties = kwargs.get('properties', None) - - -class ProviderOperationsMetadata(msrest.serialization.Model): - """Provider Operations metadata. - - :param id: The provider id. - :type id: str - :param name: The provider name. - :type name: str - :param type: The provider type. - :type type: str - :param display_name: The provider display name. - :type display_name: str - :param resource_types: The provider resource types. - :type resource_types: list[~azure.mgmt.authorization.v2015_07_01.models.ResourceType] - :param operations: The provider operations. - :type operations: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperation] - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'resource_types': {'key': 'resourceTypes', 'type': '[ResourceType]'}, - 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, - } - - def __init__( - self, - **kwargs - ): - super(ProviderOperationsMetadata, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.name = kwargs.get('name', None) - self.type = kwargs.get('type', None) - self.display_name = kwargs.get('display_name', None) - self.resource_types = kwargs.get('resource_types', None) - self.operations = kwargs.get('operations', None) - - -class ProviderOperationsMetadataListResult(msrest.serialization.Model): - """Provider operations metadata list. - - :param value: The list of providers. - :type value: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperationsMetadata] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[ProviderOperationsMetadata]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class ResourceType(msrest.serialization.Model): - """Resource Type. - - :param name: The resource type name. - :type name: str - :param display_name: The resource type display name. - :type display_name: str - :param operations: The resource type operations. - :type operations: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperation] - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, - } - - def __init__( - self, - **kwargs - ): - super(ResourceType, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.display_name = kwargs.get('display_name', None) - self.operations = kwargs.get('operations', None) - - -class RoleAssignment(msrest.serialization.Model): - """Role Assignments. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role assignment ID. - :vartype id: str - :ivar name: The role assignment name. - :vartype name: str - :ivar type: The role assignment type. - :vartype type: str - :param properties: Role assignment properties. - :type properties: - ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentPropertiesWithScope - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'RoleAssignmentPropertiesWithScope'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignment, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.properties = kwargs.get('properties', None) - - -class RoleAssignmentCreateParameters(msrest.serialization.Model): - """Role assignment create parameters. - - All required parameters must be populated in order to send to Azure. - - :param properties: Required. Role assignment properties. - :type properties: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentProperties - """ - - _validation = { - 'properties': {'required': True}, - } - - _attribute_map = { - 'properties': {'key': 'properties', 'type': 'RoleAssignmentProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentCreateParameters, self).__init__(**kwargs) - self.properties = kwargs['properties'] - - -class RoleAssignmentFilter(msrest.serialization.Model): - """Role Assignments filter. - - :param principal_id: Returns role assignment of the specific principal. - :type principal_id: str - """ - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentFilter, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - - -class RoleAssignmentListResult(msrest.serialization.Model): - """Role assignment list operation result. - - :param value: Role assignment list. - :type value: list[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RoleAssignmentProperties(msrest.serialization.Model): - """Role assignment properties. - - All required parameters must be populated in order to send to Azure. - - :param role_definition_id: Required. The role definition ID used in the role assignment. - :type role_definition_id: str - :param principal_id: Required. The principal ID assigned to the role. This maps to the ID - inside the Active Directory. It can point to a user, service principal, or security group. - :type principal_id: str - """ - - _validation = { - 'role_definition_id': {'required': True}, - 'principal_id': {'required': True}, - } - - _attribute_map = { - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'principalId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentProperties, self).__init__(**kwargs) - self.role_definition_id = kwargs['role_definition_id'] - self.principal_id = kwargs['principal_id'] - - -class RoleAssignmentPropertiesWithScope(msrest.serialization.Model): - """Role assignment properties with scope. - - :param scope: The role assignment scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - """ - - _attribute_map = { - 'scope': {'key': 'scope', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'principalId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentPropertiesWithScope, self).__init__(**kwargs) - self.scope = kwargs.get('scope', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.principal_id = kwargs.get('principal_id', None) - - -class RoleDefinition(msrest.serialization.Model): - """Role definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role definition ID. - :vartype id: str - :ivar name: The role definition name. - :vartype name: str - :ivar type: The role definition type. - :vartype type: str - :param role_name: The role name. - :type role_name: str - :param description: The role definition description. - :type description: str - :param role_type: The role type. - :type role_type: str - :param permissions: Role definition permissions. - :type permissions: list[~azure.mgmt.authorization.v2015_07_01.models.Permission] - :param assignable_scopes: Role definition assignable scopes. - :type assignable_scopes: list[str] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'role_name': {'key': 'properties.roleName', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'role_type': {'key': 'properties.type', 'type': 'str'}, - 'permissions': {'key': 'properties.permissions', 'type': '[Permission]'}, - 'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleDefinition, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.role_name = kwargs.get('role_name', None) - self.description = kwargs.get('description', None) - self.role_type = kwargs.get('role_type', None) - self.permissions = kwargs.get('permissions', None) - self.assignable_scopes = kwargs.get('assignable_scopes', None) - - -class RoleDefinitionFilter(msrest.serialization.Model): - """Role Definitions filter. - - :param role_name: Returns role definition with the specific name. - :type role_name: str - """ - - _attribute_map = { - 'role_name': {'key': 'roleName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleDefinitionFilter, self).__init__(**kwargs) - self.role_name = kwargs.get('role_name', None) - - -class RoleDefinitionListResult(msrest.serialization.Model): - """Role definition list operation result. - - :param value: Role definition list. - :type value: list[~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleDefinition]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleDefinitionListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_models_py3.py index bf01a81e0ea..4328a93efcd 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_models_py3.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -6,46 +7,67 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, List, Optional +import sys +from typing import Any, List, Optional, TYPE_CHECKING -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class ClassicAdministrator(msrest.serialization.Model): + +class ClassicAdministrator(_serialization.Model): """Classic Administrators. - :param id: The ID of the administrator. - :type id: str - :param name: The name of the administrator. - :type name: str - :param type: The type of the administrator. - :type type: str - :param email_address: The email address of the administrator. - :type email_address: str - :param role: The role of the administrator. - :type role: str + :ivar id: The ID of the administrator. + :vartype id: str + :ivar name: The name of the administrator. + :vartype name: str + :ivar type: The type of the administrator. + :vartype type: str + :ivar email_address: The email address of the administrator. + :vartype email_address: str + :ivar role: The role of the administrator. + :vartype role: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'email_address': {'key': 'properties.emailAddress', 'type': 'str'}, - 'role': {'key': 'properties.role', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "email_address": {"key": "properties.emailAddress", "type": "str"}, + "role": {"key": "properties.role", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, email_address: Optional[str] = None, role: Optional[str] = None, **kwargs ): - super(ClassicAdministrator, self).__init__(**kwargs) + """ + :keyword id: The ID of the administrator. + :paramtype id: str + :keyword name: The name of the administrator. + :paramtype name: str + :keyword type: The type of the administrator. + :paramtype type: str + :keyword email_address: The email address of the administrator. + :paramtype email_address: str + :keyword role: The role of the administrator. + :paramtype role: str + """ + super().__init__(**kwargs) self.id = id self.name = name self.type = type @@ -53,33 +75,35 @@ def __init__( self.role = role -class ClassicAdministratorListResult(msrest.serialization.Model): +class ClassicAdministratorListResult(_serialization.Model): """ClassicAdministrator list result information. - :param value: An array of administrators. - :type value: list[~azure.mgmt.authorization.v2015_07_01.models.ClassicAdministrator] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: An array of administrators. + :vartype value: list[~azure.mgmt.authorization.v2015_07_01.models.ClassicAdministrator] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ClassicAdministrator]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ClassicAdministrator]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["ClassicAdministrator"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.ClassicAdministrator"]] = None, next_link: Optional[str] = None, **kwargs ): - super(ClassicAdministratorListResult, self).__init__(**kwargs) + """ + :keyword value: An array of administrators. + :paramtype value: list[~azure.mgmt.authorization.v2015_07_01.models.ClassicAdministrator] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ErrorAdditionalInfo(msrest.serialization.Model): +class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. @@ -87,29 +111,27 @@ class ErrorAdditionalInfo(msrest.serialization.Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: any + :vartype info: JSON """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None -class ErrorDetail(msrest.serialization.Model): +class ErrorDetail(_serialization.Model): """The error detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -128,26 +150,24 @@ class ErrorDetail(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -155,100 +175,101 @@ def __init__( self.additional_info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2015_07_01.models.ErrorDetail + :ivar error: The error object. + :vartype error: ~azure.mgmt.authorization.v2015_07_01.models.ErrorDetail """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, + "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__( - self, - *, - error: Optional["ErrorDetail"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.authorization.v2015_07_01.models.ErrorDetail + """ + super().__init__(**kwargs) self.error = error -class Permission(msrest.serialization.Model): +class Permission(_serialization.Model): """Role definition permissions. - :param actions: Allowed actions. - :type actions: list[str] - :param not_actions: Denied actions. - :type not_actions: list[str] + :ivar actions: Allowed actions. + :vartype actions: list[str] + :ivar not_actions: Denied actions. + :vartype not_actions: list[str] """ _attribute_map = { - 'actions': {'key': 'actions', 'type': '[str]'}, - 'not_actions': {'key': 'notActions', 'type': '[str]'}, + "actions": {"key": "actions", "type": "[str]"}, + "not_actions": {"key": "notActions", "type": "[str]"}, } - def __init__( - self, - *, - actions: Optional[List[str]] = None, - not_actions: Optional[List[str]] = None, - **kwargs - ): - super(Permission, self).__init__(**kwargs) + def __init__(self, *, actions: Optional[List[str]] = None, not_actions: Optional[List[str]] = None, **kwargs): + """ + :keyword actions: Allowed actions. + :paramtype actions: list[str] + :keyword not_actions: Denied actions. + :paramtype not_actions: list[str] + """ + super().__init__(**kwargs) self.actions = actions self.not_actions = not_actions -class PermissionGetResult(msrest.serialization.Model): +class PermissionGetResult(_serialization.Model): """Permissions information. - :param value: An array of permissions. - :type value: list[~azure.mgmt.authorization.v2015_07_01.models.Permission] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: An array of permissions. + :vartype value: list[~azure.mgmt.authorization.v2015_07_01.models.Permission] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Permission]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Permission]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["Permission"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.Permission"]] = None, next_link: Optional[str] = None, **kwargs ): - super(PermissionGetResult, self).__init__(**kwargs) + """ + :keyword value: An array of permissions. + :paramtype value: list[~azure.mgmt.authorization.v2015_07_01.models.Permission] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ProviderOperation(msrest.serialization.Model): +class ProviderOperation(_serialization.Model): """Operation. - :param name: The operation name. - :type name: str - :param display_name: The operation display name. - :type display_name: str - :param description: The operation description. - :type description: str - :param origin: The operation origin. - :type origin: str - :param properties: The operation properties. - :type properties: any + :ivar name: The operation name. + :vartype name: str + :ivar display_name: The operation display name. + :vartype display_name: str + :ivar description: The operation description. + :vartype description: str + :ivar origin: The operation origin. + :vartype origin: str + :ivar properties: The operation properties. + :vartype properties: JSON """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'origin': {'key': 'origin', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'object'}, + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "origin": {"key": "origin", "type": "str"}, + "properties": {"key": "properties", "type": "object"}, } def __init__( @@ -258,10 +279,22 @@ def __init__( display_name: Optional[str] = None, description: Optional[str] = None, origin: Optional[str] = None, - properties: Optional[Any] = None, + properties: Optional[JSON] = None, **kwargs ): - super(ProviderOperation, self).__init__(**kwargs) + """ + :keyword name: The operation name. + :paramtype name: str + :keyword display_name: The operation display name. + :paramtype display_name: str + :keyword description: The operation description. + :paramtype description: str + :keyword origin: The operation origin. + :paramtype origin: str + :keyword properties: The operation properties. + :paramtype properties: JSON + """ + super().__init__(**kwargs) self.name = name self.display_name = display_name self.description = description @@ -269,44 +302,58 @@ def __init__( self.properties = properties -class ProviderOperationsMetadata(msrest.serialization.Model): +class ProviderOperationsMetadata(_serialization.Model): """Provider Operations metadata. - :param id: The provider id. - :type id: str - :param name: The provider name. - :type name: str - :param type: The provider type. - :type type: str - :param display_name: The provider display name. - :type display_name: str - :param resource_types: The provider resource types. - :type resource_types: list[~azure.mgmt.authorization.v2015_07_01.models.ResourceType] - :param operations: The provider operations. - :type operations: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperation] + :ivar id: The provider id. + :vartype id: str + :ivar name: The provider name. + :vartype name: str + :ivar type: The provider type. + :vartype type: str + :ivar display_name: The provider display name. + :vartype display_name: str + :ivar resource_types: The provider resource types. + :vartype resource_types: list[~azure.mgmt.authorization.v2015_07_01.models.ResourceType] + :ivar operations: The provider operations. + :vartype operations: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperation] """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'resource_types': {'key': 'resourceTypes', 'type': '[ResourceType]'}, - 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "resource_types": {"key": "resourceTypes", "type": "[ResourceType]"}, + "operations": {"key": "operations", "type": "[ProviderOperation]"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, display_name: Optional[str] = None, - resource_types: Optional[List["ResourceType"]] = None, - operations: Optional[List["ProviderOperation"]] = None, + resource_types: Optional[List["_models.ResourceType"]] = None, + operations: Optional[List["_models.ProviderOperation"]] = None, **kwargs ): - super(ProviderOperationsMetadata, self).__init__(**kwargs) + """ + :keyword id: The provider id. + :paramtype id: str + :keyword name: The provider name. + :paramtype name: str + :keyword type: The provider type. + :paramtype type: str + :keyword display_name: The provider display name. + :paramtype display_name: str + :keyword resource_types: The provider resource types. + :paramtype resource_types: list[~azure.mgmt.authorization.v2015_07_01.models.ResourceType] + :keyword operations: The provider operations. + :paramtype operations: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperation] + """ + super().__init__(**kwargs) self.id = id self.name = name self.type = type @@ -315,47 +362,53 @@ def __init__( self.operations = operations -class ProviderOperationsMetadataListResult(msrest.serialization.Model): +class ProviderOperationsMetadataListResult(_serialization.Model): """Provider operations metadata list. - :param value: The list of providers. - :type value: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperationsMetadata] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: The list of providers. + :vartype value: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperationsMetadata] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ProviderOperationsMetadata]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ProviderOperationsMetadata]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["ProviderOperationsMetadata"]] = None, + value: Optional[List["_models.ProviderOperationsMetadata"]] = None, next_link: Optional[str] = None, **kwargs ): - super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) + """ + :keyword value: The list of providers. + :paramtype value: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperationsMetadata] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ResourceType(msrest.serialization.Model): +class ResourceType(_serialization.Model): """Resource Type. - :param name: The resource type name. - :type name: str - :param display_name: The resource type display name. - :type display_name: str - :param operations: The resource type operations. - :type operations: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperation] + :ivar name: The resource type name. + :vartype name: str + :ivar display_name: The resource type display name. + :vartype display_name: str + :ivar operations: The resource type operations. + :vartype operations: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperation] """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "operations": {"key": "operations", "type": "[ProviderOperation]"}, } def __init__( @@ -363,16 +416,24 @@ def __init__( *, name: Optional[str] = None, display_name: Optional[str] = None, - operations: Optional[List["ProviderOperation"]] = None, + operations: Optional[List["_models.ProviderOperation"]] = None, **kwargs ): - super(ResourceType, self).__init__(**kwargs) + """ + :keyword name: The resource type name. + :paramtype name: str + :keyword display_name: The resource type display name. + :paramtype display_name: str + :keyword operations: The resource type operations. + :paramtype operations: list[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperation] + """ + super().__init__(**kwargs) self.name = name self.display_name = display_name self.operations = operations -class RoleAssignment(msrest.serialization.Model): +class RoleAssignment(_serialization.Model): """Role Assignments. Variables are only populated by the server, and will be ignored when sending a request. @@ -383,160 +444,161 @@ class RoleAssignment(msrest.serialization.Model): :vartype name: str :ivar type: The role assignment type. :vartype type: str - :param properties: Role assignment properties. - :type properties: + :ivar properties: Role assignment properties. + :vartype properties: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentPropertiesWithScope """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'RoleAssignmentPropertiesWithScope'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "RoleAssignmentPropertiesWithScope"}, } - def __init__( - self, - *, - properties: Optional["RoleAssignmentPropertiesWithScope"] = None, - **kwargs - ): - super(RoleAssignment, self).__init__(**kwargs) + def __init__(self, *, properties: Optional["_models.RoleAssignmentPropertiesWithScope"] = None, **kwargs): + """ + :keyword properties: Role assignment properties. + :paramtype properties: + ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentPropertiesWithScope + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None self.properties = properties -class RoleAssignmentCreateParameters(msrest.serialization.Model): +class RoleAssignmentCreateParameters(_serialization.Model): """Role assignment create parameters. All required parameters must be populated in order to send to Azure. - :param properties: Required. Role assignment properties. - :type properties: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentProperties + :ivar properties: Role assignment properties. Required. + :vartype properties: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentProperties """ _validation = { - 'properties': {'required': True}, + "properties": {"required": True}, } _attribute_map = { - 'properties': {'key': 'properties', 'type': 'RoleAssignmentProperties'}, + "properties": {"key": "properties", "type": "RoleAssignmentProperties"}, } - def __init__( - self, - *, - properties: "RoleAssignmentProperties", - **kwargs - ): - super(RoleAssignmentCreateParameters, self).__init__(**kwargs) + def __init__(self, *, properties: "_models.RoleAssignmentProperties", **kwargs): + """ + :keyword properties: Role assignment properties. Required. + :paramtype properties: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentProperties + """ + super().__init__(**kwargs) self.properties = properties -class RoleAssignmentFilter(msrest.serialization.Model): +class RoleAssignmentFilter(_serialization.Model): """Role Assignments filter. - :param principal_id: Returns role assignment of the specific principal. - :type principal_id: str + :ivar principal_id: Returns role assignment of the specific principal. + :vartype principal_id: str """ _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, } - def __init__( - self, - *, - principal_id: Optional[str] = None, - **kwargs - ): - super(RoleAssignmentFilter, self).__init__(**kwargs) + def __init__(self, *, principal_id: Optional[str] = None, **kwargs): + """ + :keyword principal_id: Returns role assignment of the specific principal. + :paramtype principal_id: str + """ + super().__init__(**kwargs) self.principal_id = principal_id -class RoleAssignmentListResult(msrest.serialization.Model): +class RoleAssignmentListResult(_serialization.Model): """Role assignment list operation result. - :param value: Role assignment list. - :type value: list[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Role assignment list. + :vartype value: list[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["RoleAssignment"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.RoleAssignment"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleAssignmentListResult, self).__init__(**kwargs) + """ + :keyword value: Role assignment list. + :paramtype value: list[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class RoleAssignmentProperties(msrest.serialization.Model): +class RoleAssignmentProperties(_serialization.Model): """Role assignment properties. All required parameters must be populated in order to send to Azure. - :param role_definition_id: Required. The role definition ID used in the role assignment. - :type role_definition_id: str - :param principal_id: Required. The principal ID assigned to the role. This maps to the ID - inside the Active Directory. It can point to a user, service principal, or security group. - :type principal_id: str + :ivar role_definition_id: The role definition ID used in the role assignment. Required. + :vartype role_definition_id: str + :ivar principal_id: The principal ID assigned to the role. This maps to the ID inside the + Active Directory. It can point to a user, service principal, or security group. Required. + :vartype principal_id: str """ _validation = { - 'role_definition_id': {'required': True}, - 'principal_id': {'required': True}, + "role_definition_id": {"required": True}, + "principal_id": {"required": True}, } _attribute_map = { - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'principalId', 'type': 'str'}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "principal_id": {"key": "principalId", "type": "str"}, } - def __init__( - self, - *, - role_definition_id: str, - principal_id: str, - **kwargs - ): - super(RoleAssignmentProperties, self).__init__(**kwargs) + def __init__(self, *, role_definition_id: str, principal_id: str, **kwargs): + """ + :keyword role_definition_id: The role definition ID used in the role assignment. Required. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID assigned to the role. This maps to the ID inside the + Active Directory. It can point to a user, service principal, or security group. Required. + :paramtype principal_id: str + """ + super().__init__(**kwargs) self.role_definition_id = role_definition_id self.principal_id = principal_id -class RoleAssignmentPropertiesWithScope(msrest.serialization.Model): +class RoleAssignmentPropertiesWithScope(_serialization.Model): """Role assignment properties with scope. - :param scope: The role assignment scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str + :ivar scope: The role assignment scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str """ _attribute_map = { - 'scope': {'key': 'scope', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'principalId', 'type': 'str'}, + "scope": {"key": "scope", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "principal_id": {"key": "principalId", "type": "str"}, } def __init__( @@ -547,13 +609,21 @@ def __init__( principal_id: Optional[str] = None, **kwargs ): - super(RoleAssignmentPropertiesWithScope, self).__init__(**kwargs) + """ + :keyword scope: The role assignment scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + """ + super().__init__(**kwargs) self.scope = scope self.role_definition_id = role_definition_id self.principal_id = principal_id -class RoleDefinition(msrest.serialization.Model): +class RoleDefinition(_serialization.Model): """Role definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -564,33 +634,33 @@ class RoleDefinition(msrest.serialization.Model): :vartype name: str :ivar type: The role definition type. :vartype type: str - :param role_name: The role name. - :type role_name: str - :param description: The role definition description. - :type description: str - :param role_type: The role type. - :type role_type: str - :param permissions: Role definition permissions. - :type permissions: list[~azure.mgmt.authorization.v2015_07_01.models.Permission] - :param assignable_scopes: Role definition assignable scopes. - :type assignable_scopes: list[str] + :ivar role_name: The role name. + :vartype role_name: str + :ivar description: The role definition description. + :vartype description: str + :ivar role_type: The role type. + :vartype role_type: str + :ivar permissions: Role definition permissions. + :vartype permissions: list[~azure.mgmt.authorization.v2015_07_01.models.Permission] + :ivar assignable_scopes: Role definition assignable scopes. + :vartype assignable_scopes: list[str] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'role_name': {'key': 'properties.roleName', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'role_type': {'key': 'properties.type', 'type': 'str'}, - 'permissions': {'key': 'properties.permissions', 'type': '[Permission]'}, - 'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "role_name": {"key": "properties.roleName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "role_type": {"key": "properties.type", "type": "str"}, + "permissions": {"key": "properties.permissions", "type": "[Permission]"}, + "assignable_scopes": {"key": "properties.assignableScopes", "type": "[str]"}, } def __init__( @@ -599,11 +669,23 @@ def __init__( role_name: Optional[str] = None, description: Optional[str] = None, role_type: Optional[str] = None, - permissions: Optional[List["Permission"]] = None, + permissions: Optional[List["_models.Permission"]] = None, assignable_scopes: Optional[List[str]] = None, **kwargs ): - super(RoleDefinition, self).__init__(**kwargs) + """ + :keyword role_name: The role name. + :paramtype role_name: str + :keyword description: The role definition description. + :paramtype description: str + :keyword role_type: The role type. + :paramtype role_type: str + :keyword permissions: Role definition permissions. + :paramtype permissions: list[~azure.mgmt.authorization.v2015_07_01.models.Permission] + :keyword assignable_scopes: Role definition assignable scopes. + :paramtype assignable_scopes: list[str] + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -614,48 +696,49 @@ def __init__( self.assignable_scopes = assignable_scopes -class RoleDefinitionFilter(msrest.serialization.Model): +class RoleDefinitionFilter(_serialization.Model): """Role Definitions filter. - :param role_name: Returns role definition with the specific name. - :type role_name: str + :ivar role_name: Returns role definition with the specific name. + :vartype role_name: str """ _attribute_map = { - 'role_name': {'key': 'roleName', 'type': 'str'}, + "role_name": {"key": "roleName", "type": "str"}, } - def __init__( - self, - *, - role_name: Optional[str] = None, - **kwargs - ): - super(RoleDefinitionFilter, self).__init__(**kwargs) + def __init__(self, *, role_name: Optional[str] = None, **kwargs): + """ + :keyword role_name: Returns role definition with the specific name. + :paramtype role_name: str + """ + super().__init__(**kwargs) self.role_name = role_name -class RoleDefinitionListResult(msrest.serialization.Model): +class RoleDefinitionListResult(_serialization.Model): """Role definition list operation result. - :param value: Role definition list. - :type value: list[~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Role definition list. + :vartype value: list[~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleDefinition]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["RoleDefinition"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.RoleDefinition"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleDefinitionListResult, self).__init__(**kwargs) + """ + :keyword value: Role definition list. + :paramtype value: list[~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/__init__.py index 751b809fce0..dc8d1317eb2 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/__init__.py @@ -13,11 +13,17 @@ from ._role_assignments_operations import RoleAssignmentsOperations from ._classic_administrators_operations import ClassicAdministratorsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'PermissionsOperations', - 'RoleDefinitionsOperations', - 'ProviderOperationsMetadataOperations', - 'GlobalAdministratorOperations', - 'RoleAssignmentsOperations', - 'ClassicAdministratorsOperations', + "PermissionsOperations", + "RoleDefinitionsOperations", + "ProviderOperationsMetadataOperations", + "GlobalAdministratorOperations", + "RoleAssignmentsOperations", + "ClassicAdministratorsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_classic_administrators_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_classic_administrators_operations.py index ff02d9d6c5f..fe5faa4cf50 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_classic_administrators_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_classic_administrators_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,91 +6,132 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } -class ClassicAdministratorsOperations(object): - """ClassicAdministratorsOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ClassicAdministratorsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.AuthorizationManagementClient`'s + :attr:`classic_administrators` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ClassicAdministratorListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.ClassicAdministrator"]: """Gets service administrator, account administrator, and co-administrators for the subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ClassicAdministratorListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.ClassicAdministratorListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ClassicAdministrator or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.ClassicAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ClassicAdministratorListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ClassicAdministratorListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ClassicAdministratorListResult', pipeline_response) + deserialized = self._deserialize("ClassicAdministratorListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -98,17 +140,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_global_administrator_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_global_administrator_operations.py index bb011b71bae..01c8652445e 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_global_administrator_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_global_administrator_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,86 +6,116 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_elevate_access_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/elevateAccess") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -class GlobalAdministratorOperations(object): - """GlobalAdministratorOperations operations. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + +class GlobalAdministratorOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.AuthorizationManagementClient`'s + :attr:`global_administrator` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def elevate_access( - self, - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def elevate_access(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """Elevates access for a Global Administrator. :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct URL - url = self.elevate_access.metadata['url'] # type: ignore + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_elevate_access_request( + api_version=api_version, + template_url=self.elevate_access.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - elevate_access.metadata = {'url': '/providers/Microsoft.Authorization/elevateAccess'} # type: ignore + elevate_access.metadata = {"url": "/providers/Microsoft.Authorization/elevateAccess"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_permissions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_permissions_operations.py index c5d6a306883..fcd696d6e14 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_permissions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_permissions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,180 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class PermissionsOperations(object): - """PermissionsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_list_for_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PermissionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.AuthorizationManagementClient`'s + :attr:`permissions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list_for_resource_group( - self, - resource_group_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PermissionGetResult"] + @distributed_trace + def list_for_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Permission"]: """Gets all permissions the caller has for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PermissionGetResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.PermissionGetResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PermissionGetResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PermissionGetResult', pipeline_response) + deserialized = self._deserialize("PermissionGetResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -102,86 +188,95 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions'} # type: ignore + return ItemPaged(get_next, extract_data) + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions"} # type: ignore + + @distributed_trace def list_for_resource( self, - resource_group_name, # type: str - resource_provider_namespace, # type: str - parent_resource_path, # type: str - resource_type, # type: str - resource_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PermissionGetResult"] + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + **kwargs: Any + ) -> Iterable["_models.Permission"]: """Gets all permissions the caller has for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get the permissions for. + :param resource_name: The name of the resource to get the permissions for. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PermissionGetResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.PermissionGetResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PermissionGetResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str'), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PermissionGetResult', pipeline_response) + deserialized = self._deserialize("PermissionGetResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -190,17 +285,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_provider_operations_metadata_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_provider_operations_metadata_operations.py index 66d1bcd92e8..4025fada096 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_provider_operations_metadata_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_provider_operations_metadata_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,152 +6,217 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(resource_provider_namespace: str, *, expand: str = "resourceTypes", **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}" + ) + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class ProviderOperationsMetadataOperations(object): - """ProviderOperationsMetadataOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +def build_list_request(*, expand: str = "resourceTypes", **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/providerOperations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ProviderOperationsMetadataOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.AuthorizationManagementClient`'s + :attr:`provider_operations_metadata` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def get( - self, - resource_provider_namespace, # type: str - expand="resourceTypes", # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.ProviderOperationsMetadata" + self, resource_provider_namespace: str, expand: str = "resourceTypes", **kwargs: Any + ) -> _models.ProviderOperationsMetadata: """Gets provider operations metadata for the specified resource provider. - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param expand: Specifies whether to expand the values. + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ProviderOperationsMetadata, or the result of cls(response) + :return: ProviderOperationsMetadata or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.ProviderOperationsMetadata - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProviderOperationsMetadata"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadata] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + request = build_get_request( + resource_provider_namespace=resource_provider_namespace, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ProviderOperationsMetadata', pipeline_response) + deserialized = self._deserialize("ProviderOperationsMetadata", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}'} # type: ignore - - def list( - self, - expand="resourceTypes", # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ProviderOperationsMetadataListResult"] + + get.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}"} # type: ignore + + @distributed_trace + def list(self, expand: str = "resourceTypes", **kwargs: Any) -> Iterable["_models.ProviderOperationsMetadata"]: """Gets provider operations metadata for all resource providers. - :param expand: Specifies whether to expand the values. + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProviderOperationsMetadataListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperationsMetadataListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ProviderOperationsMetadata or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.ProviderOperationsMetadata] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProviderOperationsMetadataListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadataListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ProviderOperationsMetadataListResult', pipeline_response) + deserialized = self._deserialize("ProviderOperationsMetadataListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -159,17 +225,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/providerOperations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_role_assignments_operations.py index 42f104b6928..9816ed8cc94 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_role_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,118 +6,422 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_group_request( + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request(role_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleAssignmentId}") + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_by_id_request(role_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleAssignmentId}") + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentsOperations(object): - """RoleAssignmentsOperations operations. +def build_get_by_id_request(role_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct URL + _url = kwargs.pop("template_url", "/{roleAssignmentId}") + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_resource( self, - resource_group_name, # type: str - resource_provider_namespace, # type: str - parent_resource_path, # type: str - resource_type, # type: str - resource_name, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """Gets role assignments for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get role assignments for. + :param resource_name: The name of the resource to get role assignments for. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str'), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -125,77 +430,83 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_resource_group( - self, - resource_group_name, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """Gets role assignments for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -204,90 +515,125 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) - def delete( - self, - scope, # type: str - role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleAssignment"] + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace + def delete(self, scope: str, role_assignment_name: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. - :param scope: The scope of the role assignment to delete. + :param scope: The scope of the role assignment to delete. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to delete. + :param role_assignment_name: The name of the role assignment to delete. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload + def create( + self, + scope: str, + role_assignment_name: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload def create( self, - scope, # type: str - role_assignment_name, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: """Creates a role assignment. :param scope: The scope of the role assignment to create. The scope can be any REST resource @@ -295,359 +641,475 @@ def create( '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to create. It can be any valid - GUID. + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. :type parameters: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentCreateParameters + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - def get( - self, - scope, # type: str - role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace + def get(self, scope: str, role_assignment_name: str, **kwargs: Any) -> _models.RoleAssignment: """Get the specified role assignment. - :param scope: The scope of the role assignment. + :param scope: The scope of the role assignment. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to get. + :param role_assignment_name: The name of the role assignment to get. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - def delete_by_id( - self, - role_assignment_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleAssignment"] + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace + def delete_by_id(self, role_assignment_id: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. :param role_assignment_id: The fully qualified ID of the role assignment, including the scope, resource name and resource type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. + Required. :type role_assignment_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore + delete_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @overload def create_by_id( self, - role_assignment_id, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + role_assignment_id: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: """Creates a role assignment by ID. :param role_assignment_id: The fully qualified ID of the role assignment, including the scope, resource name and resource type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. + Required. :type role_assignment_id: str - :param parameters: Parameters for the role assignment. + :param parameters: Parameters for the role assignment. Required. :type parameters: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_by_id( + self, role_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment, including the scope, + resource name and resource type. Use the format, + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_by_id( + self, role_assignment_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment, including the scope, + resource name and resource type. Use the format, + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentCreateParameters + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore - def get_by_id( - self, - role_assignment_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + create_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @distributed_trace + def get_by_id(self, role_assignment_id: str, **kwargs: Any) -> _models.RoleAssignment: """Gets a role assignment by ID. :param role_assignment_id: The fully qualified ID of the role assignment, including the scope, resource name and resource type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. + Required. :type role_assignment_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore - def list( - self, - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + get_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.RoleAssignment"]: """Gets all role assignments for the subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -656,76 +1118,81 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """Gets role assignments for a scope. - :param scope: The scope of the role assignments. + :param scope: The scope of the role assignments. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -734,17 +1201,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_role_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_role_definitions_operations.py index be3d299fb60..77504630828 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_role_definitions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2015_07_01/operations/_role_definitions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,287 +6,489 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_delete_request(scope: str, role_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(scope: str, role_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class RoleDefinitionsOperations(object): - """RoleDefinitionsOperations operations. + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2015_07_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +def build_list_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(role_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleDefinitionId}") + path_format_arguments = { + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2015_07_01.AuthorizationManagementClient`'s + :attr:`role_definitions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def delete( - self, - scope, # type: str - role_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleDefinition"] + @distributed_trace + def delete(self, scope: str, role_definition_id: str, **kwargs: Any) -> Optional[_models.RoleDefinition]: """Deletes a role definition. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition to delete. + :param role_definition_id: The ID of the role definition to delete. Required. :type role_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleDefinition"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleDefinition]] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_delete_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore - def get( - self, - scope, # type: str - role_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleDefinition" + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace + def get(self, scope: str, role_definition_id: str, **kwargs: Any) -> _models.RoleDefinition: """Get role definition by name (GUID). - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition. + :param role_definition_id: The ID of the role definition. Required. :type role_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + request = build_get_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @overload def create_or_update( self, - scope, # type: str - role_definition_id, # type: str - role_definition, # type: "_models.RoleDefinition" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleDefinition" + scope: str, + role_definition_id: str, + role_definition: _models.RoleDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleDefinition: """Creates or updates a role definition. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition. + :param role_definition_id: The ID of the role definition. Required. :type role_definition_id: str - :param role_definition: The values for the role definition. + :param role_definition: The values for the role definition. Required. :type role_definition: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + scope: str, + role_definition_id: str, + role_definition: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Required. + :type role_definition: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, scope: str, role_definition_id: str, role_definition: Union[_models.RoleDefinition, IO], **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Is either a model type or a IO + type. Required. + :type role_definition: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(role_definition, 'RoleDefinition') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(role_definition, (IO, bytes)): + _content = role_definition + else: + _json = self._serialize.body(role_definition, "RoleDefinition") + + request = build_create_or_update_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore - def list( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleDefinitionListResult"] + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace + def list(self, scope: str, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.RoleDefinition"]: """Get all role definitions that are applicable at scope and above. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str :param filter: The filter to apply on the operation. Use atScopeAndBelow filter to search below - the given scope as well. + the given scope as well. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleDefinition or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("RoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -294,76 +497,77 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions'} # type: ignore + return ItemPaged(get_next, extract_data) - def get_by_id( - self, - role_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleDefinition" + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions"} # type: ignore + + @distributed_trace + def get_by_id(self, role_definition_id: str, **kwargs: Any) -> _models.RoleDefinition: """Gets a role definition by ID. :param role_definition_id: The fully qualified role definition ID. Use the format, /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for subscription level role definitions, or /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for tenant level role - definitions. + definitions. Required. :type role_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2015_07_01.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2015-07-01" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_by_id_request( + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleDefinitionId}'} # type: ignore + + get_by_id.metadata = {"url": "/{roleDefinitionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/__init__.py index ae11ad3e4d9..9eb8d3ec28c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AuthorizationManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_authorization_management_client.py index 4441499e688..45a20f31367 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_authorization_management_client.py @@ -6,88 +6,102 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + PermissionsOperations, + ProviderOperationsMetadataOperations, + RoleAssignmentsOperations, + RoleDefinitionsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import ProviderOperationsMetadataOperations -from .operations import RoleAssignmentsOperations -from .operations import PermissionsOperations -from .operations import RoleDefinitionsOperations -from . import models -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These calls handle provider operations. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These calls handle provider operations. :ivar provider_operations_metadata: ProviderOperationsMetadataOperations operations - :vartype provider_operations_metadata: azure.mgmt.authorization.v2018_01_01_preview.operations.ProviderOperationsMetadataOperations + :vartype provider_operations_metadata: + azure.mgmt.authorization.v2018_01_01_preview.operations.ProviderOperationsMetadataOperations :ivar role_assignments: RoleAssignmentsOperations operations - :vartype role_assignments: azure.mgmt.authorization.v2018_01_01_preview.operations.RoleAssignmentsOperations + :vartype role_assignments: + azure.mgmt.authorization.v2018_01_01_preview.operations.RoleAssignmentsOperations :ivar permissions: PermissionsOperations operations - :vartype permissions: azure.mgmt.authorization.v2018_01_01_preview.operations.PermissionsOperations + :vartype permissions: + azure.mgmt.authorization.v2018_01_01_preview.operations.PermissionsOperations :ivar role_definitions: RoleDefinitionsOperations operations - :vartype role_definitions: azure.mgmt.authorization.v2018_01_01_preview.operations.RoleDefinitionsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype role_definitions: + azure.mgmt.authorization.v2018_01_01_preview.operations.RoleDefinitionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-01-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.provider_operations_metadata = ProviderOperationsMetadataOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignments = RoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.permissions = PermissionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.permissions = PermissionsOperations(self._client, self._config, self._serialize, self._deserialize) self.role_definitions = RoleDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_configuration.py index 73fe3723d36..2eb0f4a2715 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_configuration.py @@ -6,66 +6,64 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-01-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2018-01-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-01-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_metadata.json index 9d42dccaf7c..f439dbba8f9 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_metadata.json +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_metadata.json @@ -5,25 +5,25 @@ "name": "AuthorizationManagementClient", "filename": "_authorization_management_client", "description": "Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These calls handle provider operations.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, "azure_arm": true, "has_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -54,7 +54,7 @@ "required": false }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -74,7 +74,7 @@ "required": false }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -91,11 +91,10 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "provider_operations_metadata": "ProviderOperationsMetadataOperations", diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_version.py index 48944bf3938..cac9f5d10f8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/__init__.py index ffc49d028e4..dd28625b36f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._authorization_management_client import AuthorizationManagementClient -__all__ = ['AuthorizationManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_authorization_management_client.py index d22ed81ce40..414d979c0f4 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_authorization_management_client.py @@ -6,84 +6,102 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + PermissionsOperations, + ProviderOperationsMetadataOperations, + RoleAssignmentsOperations, + RoleDefinitionsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import ProviderOperationsMetadataOperations -from .operations import RoleAssignmentsOperations -from .operations import PermissionsOperations -from .operations import RoleDefinitionsOperations -from .. import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These calls handle provider operations. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These calls handle provider operations. :ivar provider_operations_metadata: ProviderOperationsMetadataOperations operations - :vartype provider_operations_metadata: azure.mgmt.authorization.v2018_01_01_preview.aio.operations.ProviderOperationsMetadataOperations + :vartype provider_operations_metadata: + azure.mgmt.authorization.v2018_01_01_preview.aio.operations.ProviderOperationsMetadataOperations :ivar role_assignments: RoleAssignmentsOperations operations - :vartype role_assignments: azure.mgmt.authorization.v2018_01_01_preview.aio.operations.RoleAssignmentsOperations + :vartype role_assignments: + azure.mgmt.authorization.v2018_01_01_preview.aio.operations.RoleAssignmentsOperations :ivar permissions: PermissionsOperations operations - :vartype permissions: azure.mgmt.authorization.v2018_01_01_preview.aio.operations.PermissionsOperations + :vartype permissions: + azure.mgmt.authorization.v2018_01_01_preview.aio.operations.PermissionsOperations :ivar role_definitions: RoleDefinitionsOperations operations - :vartype role_definitions: azure.mgmt.authorization.v2018_01_01_preview.aio.operations.RoleDefinitionsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype role_definitions: + azure.mgmt.authorization.v2018_01_01_preview.aio.operations.RoleDefinitionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-01-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.provider_operations_metadata = ProviderOperationsMetadataOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignments = RoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.permissions = PermissionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.permissions = PermissionsOperations(self._client, self._config, self._serialize, self._deserialize) self.role_definitions = RoleDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_configuration.py index d32ebcc2d62..a94cae2aa4d 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,49 +19,48 @@ from azure.core.credentials_async import AsyncTokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-01-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2018-01-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-01-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/__init__.py index be3e88f5724..88276b0bfd9 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/__init__.py @@ -11,9 +11,15 @@ from ._permissions_operations import PermissionsOperations from ._role_definitions_operations import RoleDefinitionsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'ProviderOperationsMetadataOperations', - 'RoleAssignmentsOperations', - 'PermissionsOperations', - 'RoleDefinitionsOperations', + "ProviderOperationsMetadataOperations", + "RoleAssignmentsOperations", + "PermissionsOperations", + "RoleDefinitionsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_permissions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_permissions_operations.py index 0af7174cf8d..b1955371b47 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_permissions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_permissions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,90 +6,106 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._permissions_operations import build_list_for_resource_group_request, build_list_for_resource_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PermissionsOperations: - """PermissionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PermissionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_01_01_preview.aio.AuthorizationManagementClient`'s + :attr:`permissions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list_for_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.PermissionGetResult"]: + @distributed_trace + def list_for_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Permission"]: """Gets all permissions the caller has for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PermissionGetResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.PermissionGetResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PermissionGetResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PermissionGetResult', pipeline_response) + deserialized = self._deserialize("PermissionGetResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -97,21 +114,23 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions"} # type: ignore + @distributed_trace def list_for_resource( self, resource_group_name: str, @@ -120,62 +139,71 @@ def list_for_resource( resource_type: str, resource_name: str, **kwargs: Any - ) -> AsyncIterable["_models.PermissionGetResult"]: + ) -> AsyncIterable["_models.Permission"]: """Gets all permissions the caller has for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get the permissions for. + :param resource_name: The name of the resource to get the permissions for. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PermissionGetResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.PermissionGetResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PermissionGetResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PermissionGetResult', pipeline_response) + deserialized = self._deserialize("PermissionGetResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -184,17 +212,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_provider_operations_metadata_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_provider_operations_metadata_operations.py index 6c6e26e27bb..efa1c118d23 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_provider_operations_metadata_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_provider_operations_metadata_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,146 +6,166 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._provider_operations_metadata_operations import build_get_request, build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ProviderOperationsMetadataOperations: - """ProviderOperationsMetadataOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ProviderOperationsMetadataOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_01_01_preview.aio.AuthorizationManagementClient`'s + :attr:`provider_operations_metadata` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace_async async def get( - self, - resource_provider_namespace: str, - expand: Optional[str] = "resourceTypes", - **kwargs: Any - ) -> "_models.ProviderOperationsMetadata": + self, resource_provider_namespace: str, expand: str = "resourceTypes", **kwargs: Any + ) -> _models.ProviderOperationsMetadata: """Gets provider operations metadata for the specified resource provider. - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param expand: Specifies whether to expand the values. + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ProviderOperationsMetadata, or the result of cls(response) + :return: ProviderOperationsMetadata or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProviderOperationsMetadata"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadata] + + request = build_get_request( + resource_provider_namespace=resource_provider_namespace, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ProviderOperationsMetadata', pipeline_response) + deserialized = self._deserialize("ProviderOperationsMetadata", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}'} # type: ignore - def list( - self, - expand: Optional[str] = "resourceTypes", - **kwargs: Any - ) -> AsyncIterable["_models.ProviderOperationsMetadataListResult"]: + get.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}"} # type: ignore + + @distributed_trace + def list(self, expand: str = "resourceTypes", **kwargs: Any) -> AsyncIterable["_models.ProviderOperationsMetadata"]: """Gets provider operations metadata for all resource providers. - :param expand: Specifies whether to expand the values. + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProviderOperationsMetadataListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadataListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ProviderOperationsMetadata or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProviderOperationsMetadataListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadataListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ProviderOperationsMetadataListResult', pipeline_response) + deserialized = self._deserialize("ProviderOperationsMetadataListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -153,17 +174,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/providerOperations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_role_assignments_operations.py index 776614cc390..e64ff2d7ea2 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_role_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,42 +6,65 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_assignments_operations import ( + build_create_by_id_request, + build_create_request, + build_delete_by_id_request, + build_delete_request, + build_get_by_id_request, + build_get_request, + build_list_for_resource_group_request, + build_list_for_resource_request, + build_list_for_scope_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentsOperations: - """RoleAssignmentsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_01_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_resource( self, resource_group_name: str, @@ -50,68 +74,76 @@ def list_for_resource( resource_name: str, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + ) -> AsyncIterable["_models.RoleAssignment"]: """Gets role assignments for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get role assignments for. + :param resource_name: The name of the resource to get role assignments for. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -120,76 +152,83 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace def list_for_resource_group( - self, - resource_group_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """Gets role assignments for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -198,88 +237,92 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def delete( - self, - scope: str, - role_assignment_name: str, - **kwargs: Any - ) -> Optional["_models.RoleAssignment"]: + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace_async + async def delete(self, scope: str, role_assignment_name: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. - :param scope: The scope of the role assignment to delete. + :param scope: The scope of the role assignment to delete. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to delete. + :param role_assignment_name: The name of the role assignment to delete. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload async def create( self, scope: str, role_assignment_name: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignment": + ) -> _models.RoleAssignment: """Creates a role assignment. :param scope: The scope of the role assignment to create. The scope can be any REST resource @@ -287,345 +330,490 @@ async def create( '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to create. It can be any valid - GUID. + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - async def get( - self, - scope: str, - role_assignment_name: str, - **kwargs: Any - ) -> "_models.RoleAssignment": + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, role_assignment_name: str, **kwargs: Any) -> _models.RoleAssignment: """Get the specified role assignment. - :param scope: The scope of the role assignment. + :param scope: The scope of the role assignment. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to get. + :param role_assignment_name: The name of the role assignment to get. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - async def delete_by_id( - self, - role_id: str, - **kwargs: Any - ) -> Optional["_models.RoleAssignment"]: + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace_async + async def delete_by_id(self, role_id: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. - :param role_id: The ID of the role assignment to delete. + :param role_id: The ID of the role assignment to delete. Required. :type role_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_id.metadata = {'url': '/{roleId}'} # type: ignore + delete_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @overload async def create_by_id( self, role_id: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignment": + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, role_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, role_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: """Creates a role assignment by ID. - :param role_id: The ID of the role assignment to create. + :param role_id: The ID of the role assignment to create. Required. :type role_id: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_id=role_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_by_id.metadata = {'url': '/{roleId}'} # type: ignore - async def get_by_id( - self, - role_id: str, - **kwargs: Any - ) -> "_models.RoleAssignment": + create_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, role_id: str, **kwargs: Any) -> _models.RoleAssignment: """Gets a role assignment by ID. - :param role_id: The ID of the role assignment to get. + :param role_id: The ID of the role assignment to get. Required. :type role_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleId}'} # type: ignore - def list( - self, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + get_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.RoleAssignment"]: """Gets all role assignments for the subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -634,75 +822,81 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """Gets role assignments for a scope. - :param scope: The scope of the role assignments. + :param scope: The scope of the role assignments. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -711,17 +905,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_role_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_role_definitions_operations.py index e280640ef01..1c743fbda7b 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_role_definitions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_role_definitions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,279 +6,366 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_definitions_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_by_id_request, + build_get_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleDefinitionsOperations: - """RoleDefinitionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_01_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_definitions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def delete( - self, - scope: str, - role_definition_id: str, - **kwargs: Any - ) -> Optional["_models.RoleDefinition"]: + @distributed_trace_async + async def delete(self, scope: str, role_definition_id: str, **kwargs: Any) -> Optional[_models.RoleDefinition]: """Deletes a role definition. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition to delete. + :param role_definition_id: The ID of the role definition to delete. Required. :type role_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleDefinition"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleDefinition]] + + request = build_delete_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore - async def get( - self, - scope: str, - role_definition_id: str, - **kwargs: Any - ) -> "_models.RoleDefinition": + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, role_definition_id: str, **kwargs: Any) -> _models.RoleDefinition: """Get role definition by name (GUID). - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition. + :param role_definition_id: The ID of the role definition. Required. :type role_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @overload async def create_or_update( self, scope: str, role_definition_id: str, - role_definition: "_models.RoleDefinition", + role_definition: _models.RoleDefinition, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleDefinition": + ) -> _models.RoleDefinition: """Creates or updates a role definition. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition. + :param role_definition_id: The ID of the role definition. Required. :type role_definition_id: str - :param role_definition: The values for the role definition. + :param role_definition: The values for the role definition. Required. :type role_definition: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + scope: str, + role_definition_id: str, + role_definition: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Required. + :type role_definition: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, scope: str, role_definition_id: str, role_definition: Union[_models.RoleDefinition, IO], **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Is either a model type or a IO + type. Required. + :type role_definition: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(role_definition, 'RoleDefinition') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(role_definition, (IO, bytes)): + _content = role_definition + else: + _json = self._serialize.body(role_definition, "RoleDefinition") + + request = build_create_or_update_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore - def list( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleDefinitionListResult"]: + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace + def list(self, scope: str, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.RoleDefinition"]: """Get all role definitions that are applicable at scope and above. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str :param filter: The filter to apply on the operation. Use atScopeAndBelow filter to search below - the given scope as well. + the given scope as well. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("RoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -286,75 +374,77 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get_by_id( - self, - role_id: str, - **kwargs: Any - ) -> "_models.RoleDefinition": + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, role_id: str, **kwargs: Any) -> _models.RoleDefinition: """Gets a role definition by ID. :param role_id: The fully qualified role definition ID. Use the format, /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for subscription level role definitions, or /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for tenant level role - definitions. + definitions. Required. :type role_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleId}'} # type: ignore + + get_by_id.metadata = {"url": "/{roleId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/__init__.py index 28a31e63398..31dede27de7 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/__init__.py @@ -6,56 +6,43 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ErrorAdditionalInfo - from ._models_py3 import ErrorDetail - from ._models_py3 import ErrorResponse - from ._models_py3 import Permission - from ._models_py3 import PermissionGetResult - from ._models_py3 import ProviderOperation - from ._models_py3 import ProviderOperationsMetadata - from ._models_py3 import ProviderOperationsMetadataListResult - from ._models_py3 import ResourceType - from ._models_py3 import RoleAssignment - from ._models_py3 import RoleAssignmentCreateParameters - from ._models_py3 import RoleAssignmentFilter - from ._models_py3 import RoleAssignmentListResult - from ._models_py3 import RoleDefinition - from ._models_py3 import RoleDefinitionFilter - from ._models_py3 import RoleDefinitionListResult -except (SyntaxError, ImportError): - from ._models import ErrorAdditionalInfo # type: ignore - from ._models import ErrorDetail # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import Permission # type: ignore - from ._models import PermissionGetResult # type: ignore - from ._models import ProviderOperation # type: ignore - from ._models import ProviderOperationsMetadata # type: ignore - from ._models import ProviderOperationsMetadataListResult # type: ignore - from ._models import ResourceType # type: ignore - from ._models import RoleAssignment # type: ignore - from ._models import RoleAssignmentCreateParameters # type: ignore - from ._models import RoleAssignmentFilter # type: ignore - from ._models import RoleAssignmentListResult # type: ignore - from ._models import RoleDefinition # type: ignore - from ._models import RoleDefinitionFilter # type: ignore - from ._models import RoleDefinitionListResult # type: ignore +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import Permission +from ._models_py3 import PermissionGetResult +from ._models_py3 import ProviderOperation +from ._models_py3 import ProviderOperationsMetadata +from ._models_py3 import ProviderOperationsMetadataListResult +from ._models_py3 import ResourceType +from ._models_py3 import RoleAssignment +from ._models_py3 import RoleAssignmentCreateParameters +from ._models_py3 import RoleAssignmentFilter +from ._models_py3 import RoleAssignmentListResult +from ._models_py3 import RoleDefinition +from ._models_py3 import RoleDefinitionFilter +from ._models_py3 import RoleDefinitionListResult +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ErrorAdditionalInfo', - 'ErrorDetail', - 'ErrorResponse', - 'Permission', - 'PermissionGetResult', - 'ProviderOperation', - 'ProviderOperationsMetadata', - 'ProviderOperationsMetadataListResult', - 'ResourceType', - 'RoleAssignment', - 'RoleAssignmentCreateParameters', - 'RoleAssignmentFilter', - 'RoleAssignmentListResult', - 'RoleDefinition', - 'RoleDefinitionFilter', - 'RoleDefinitionListResult', + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "Permission", + "PermissionGetResult", + "ProviderOperation", + "ProviderOperationsMetadata", + "ProviderOperationsMetadataListResult", + "ResourceType", + "RoleAssignment", + "RoleAssignmentCreateParameters", + "RoleAssignmentFilter", + "RoleAssignmentListResult", + "RoleDefinition", + "RoleDefinitionFilter", + "RoleDefinitionListResult", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_models.py deleted file mode 100644 index b85e6f7ca84..00000000000 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_models.py +++ /dev/null @@ -1,521 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class ErrorAdditionalInfo(msrest.serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(msrest.serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorAdditionalInfo] - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(msrest.serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class Permission(msrest.serialization.Model): - """Role definition permissions. - - :param actions: Allowed actions. - :type actions: list[str] - :param not_actions: Denied actions. - :type not_actions: list[str] - :param data_actions: Allowed Data actions. - :type data_actions: list[str] - :param not_data_actions: Denied Data actions. - :type not_data_actions: list[str] - """ - - _attribute_map = { - 'actions': {'key': 'actions', 'type': '[str]'}, - 'not_actions': {'key': 'notActions', 'type': '[str]'}, - 'data_actions': {'key': 'dataActions', 'type': '[str]'}, - 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(Permission, self).__init__(**kwargs) - self.actions = kwargs.get('actions', None) - self.not_actions = kwargs.get('not_actions', None) - self.data_actions = kwargs.get('data_actions', None) - self.not_data_actions = kwargs.get('not_data_actions', None) - - -class PermissionGetResult(msrest.serialization.Model): - """Permissions information. - - :param value: An array of permissions. - :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Permission]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PermissionGetResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class ProviderOperation(msrest.serialization.Model): - """Operation. - - :param name: The operation name. - :type name: str - :param display_name: The operation display name. - :type display_name: str - :param description: The operation description. - :type description: str - :param origin: The operation origin. - :type origin: str - :param properties: The operation properties. - :type properties: any - :param is_data_action: The dataAction flag to specify the operation type. - :type is_data_action: bool - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'origin': {'key': 'origin', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'object'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(ProviderOperation, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.display_name = kwargs.get('display_name', None) - self.description = kwargs.get('description', None) - self.origin = kwargs.get('origin', None) - self.properties = kwargs.get('properties', None) - self.is_data_action = kwargs.get('is_data_action', None) - - -class ProviderOperationsMetadata(msrest.serialization.Model): - """Provider Operations metadata. - - :param id: The provider id. - :type id: str - :param name: The provider name. - :type name: str - :param type: The provider type. - :type type: str - :param display_name: The provider display name. - :type display_name: str - :param resource_types: The provider resource types. - :type resource_types: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] - :param operations: The provider operations. - :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'resource_types': {'key': 'resourceTypes', 'type': '[ResourceType]'}, - 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, - } - - def __init__( - self, - **kwargs - ): - super(ProviderOperationsMetadata, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.name = kwargs.get('name', None) - self.type = kwargs.get('type', None) - self.display_name = kwargs.get('display_name', None) - self.resource_types = kwargs.get('resource_types', None) - self.operations = kwargs.get('operations', None) - - -class ProviderOperationsMetadataListResult(msrest.serialization.Model): - """Provider operations metadata list. - - :param value: The list of providers. - :type value: - list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[ProviderOperationsMetadata]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class ResourceType(msrest.serialization.Model): - """Resource Type. - - :param name: The resource type name. - :type name: str - :param display_name: The resource type display name. - :type display_name: str - :param operations: The resource type operations. - :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, - } - - def __init__( - self, - **kwargs - ): - super(ResourceType, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.display_name = kwargs.get('display_name', None) - self.operations = kwargs.get('operations', None) - - -class RoleAssignment(msrest.serialization.Model): - """Role Assignments. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role assignment ID. - :vartype id: str - :ivar name: The role assignment name. - :vartype name: str - :ivar type: The role assignment type. - :vartype type: str - :param scope: The role assignment scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignment, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = kwargs.get('scope', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.principal_id = kwargs.get('principal_id', None) - self.can_delegate = kwargs.get('can_delegate', None) - - -class RoleAssignmentCreateParameters(msrest.serialization.Model): - """Role assignment create parameters. - - All required parameters must be populated in order to send to Azure. - - :param role_definition_id: Required. The role definition ID used in the role assignment. - :type role_definition_id: str - :param principal_id: Required. The principal ID assigned to the role. This maps to the ID - inside the Active Directory. It can point to a user, service principal, or security group. - :type principal_id: str - :param can_delegate: The delegation flag used for creating a role assignment. - :type can_delegate: bool - """ - - _validation = { - 'role_definition_id': {'required': True}, - 'principal_id': {'required': True}, - } - - _attribute_map = { - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentCreateParameters, self).__init__(**kwargs) - self.role_definition_id = kwargs['role_definition_id'] - self.principal_id = kwargs['principal_id'] - self.can_delegate = kwargs.get('can_delegate', None) - - -class RoleAssignmentFilter(msrest.serialization.Model): - """Role Assignments filter. - - :param principal_id: Returns role assignment of the specific principal. - :type principal_id: str - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool - """ - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'can_delegate': {'key': 'canDelegate', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentFilter, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - self.can_delegate = kwargs.get('can_delegate', None) - - -class RoleAssignmentListResult(msrest.serialization.Model): - """Role assignment list operation result. - - :param value: Role assignment list. - :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RoleDefinition(msrest.serialization.Model): - """Role definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role definition ID. - :vartype id: str - :ivar name: The role definition name. - :vartype name: str - :ivar type: The role definition type. - :vartype type: str - :param role_name: The role name. - :type role_name: str - :param description: The role definition description. - :type description: str - :param role_type: The role type. - :type role_type: str - :param permissions: Role definition permissions. - :type permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] - :param assignable_scopes: Role definition assignable scopes. - :type assignable_scopes: list[str] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'role_name': {'key': 'properties.roleName', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'role_type': {'key': 'properties.type', 'type': 'str'}, - 'permissions': {'key': 'properties.permissions', 'type': '[Permission]'}, - 'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleDefinition, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.role_name = kwargs.get('role_name', None) - self.description = kwargs.get('description', None) - self.role_type = kwargs.get('role_type', None) - self.permissions = kwargs.get('permissions', None) - self.assignable_scopes = kwargs.get('assignable_scopes', None) - - -class RoleDefinitionFilter(msrest.serialization.Model): - """Role Definitions filter. - - :param role_name: Returns role definition with the specific name. - :type role_name: str - :param type: Returns role definition with the specific type. - :type type: str - """ - - _attribute_map = { - 'role_name': {'key': 'roleName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleDefinitionFilter, self).__init__(**kwargs) - self.role_name = kwargs.get('role_name', None) - self.type = kwargs.get('type', None) - - -class RoleDefinitionListResult(msrest.serialization.Model): - """Role definition list operation result. - - :param value: Role definition list. - :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleDefinition]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleDefinitionListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_models_py3.py index 86a699aa985..3e95a246032 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_models_py3.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -6,13 +7,22 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, List, Optional +import sys +from typing import Any, List, Optional, TYPE_CHECKING -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class ErrorAdditionalInfo(msrest.serialization.Model): + +class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. @@ -20,29 +30,27 @@ class ErrorAdditionalInfo(msrest.serialization.Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: any + :vartype info: JSON """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None -class ErrorDetail(msrest.serialization.Model): +class ErrorDetail(_serialization.Model): """The error detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -61,26 +69,24 @@ class ErrorDetail(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -88,45 +94,44 @@ def __init__( self.additional_info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail + :ivar error: The error object. + :vartype error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, + "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__( - self, - *, - error: Optional["ErrorDetail"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail + """ + super().__init__(**kwargs) self.error = error -class Permission(msrest.serialization.Model): +class Permission(_serialization.Model): """Role definition permissions. - :param actions: Allowed actions. - :type actions: list[str] - :param not_actions: Denied actions. - :type not_actions: list[str] - :param data_actions: Allowed Data actions. - :type data_actions: list[str] - :param not_data_actions: Denied Data actions. - :type not_data_actions: list[str] + :ivar actions: Allowed actions. + :vartype actions: list[str] + :ivar not_actions: Denied actions. + :vartype not_actions: list[str] + :ivar data_actions: Allowed Data actions. + :vartype data_actions: list[str] + :ivar not_data_actions: Denied Data actions. + :vartype not_data_actions: list[str] """ _attribute_map = { - 'actions': {'key': 'actions', 'type': '[str]'}, - 'not_actions': {'key': 'notActions', 'type': '[str]'}, - 'data_actions': {'key': 'dataActions', 'type': '[str]'}, - 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, + "actions": {"key": "actions", "type": "[str]"}, + "not_actions": {"key": "notActions", "type": "[str]"}, + "data_actions": {"key": "dataActions", "type": "[str]"}, + "not_data_actions": {"key": "notDataActions", "type": "[str]"}, } def __init__( @@ -138,63 +143,75 @@ def __init__( not_data_actions: Optional[List[str]] = None, **kwargs ): - super(Permission, self).__init__(**kwargs) + """ + :keyword actions: Allowed actions. + :paramtype actions: list[str] + :keyword not_actions: Denied actions. + :paramtype not_actions: list[str] + :keyword data_actions: Allowed Data actions. + :paramtype data_actions: list[str] + :keyword not_data_actions: Denied Data actions. + :paramtype not_data_actions: list[str] + """ + super().__init__(**kwargs) self.actions = actions self.not_actions = not_actions self.data_actions = data_actions self.not_data_actions = not_data_actions -class PermissionGetResult(msrest.serialization.Model): +class PermissionGetResult(_serialization.Model): """Permissions information. - :param value: An array of permissions. - :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: An array of permissions. + :vartype value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Permission]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Permission]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["Permission"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.Permission"]] = None, next_link: Optional[str] = None, **kwargs ): - super(PermissionGetResult, self).__init__(**kwargs) + """ + :keyword value: An array of permissions. + :paramtype value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ProviderOperation(msrest.serialization.Model): +class ProviderOperation(_serialization.Model): """Operation. - :param name: The operation name. - :type name: str - :param display_name: The operation display name. - :type display_name: str - :param description: The operation description. - :type description: str - :param origin: The operation origin. - :type origin: str - :param properties: The operation properties. - :type properties: any - :param is_data_action: The dataAction flag to specify the operation type. - :type is_data_action: bool + :ivar name: The operation name. + :vartype name: str + :ivar display_name: The operation display name. + :vartype display_name: str + :ivar description: The operation description. + :vartype description: str + :ivar origin: The operation origin. + :vartype origin: str + :ivar properties: The operation properties. + :vartype properties: JSON + :ivar is_data_action: The dataAction flag to specify the operation type. + :vartype is_data_action: bool """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'origin': {'key': 'origin', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'object'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "origin": {"key": "origin", "type": "str"}, + "properties": {"key": "properties", "type": "object"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, } def __init__( @@ -204,11 +221,25 @@ def __init__( display_name: Optional[str] = None, description: Optional[str] = None, origin: Optional[str] = None, - properties: Optional[Any] = None, + properties: Optional[JSON] = None, is_data_action: Optional[bool] = None, **kwargs ): - super(ProviderOperation, self).__init__(**kwargs) + """ + :keyword name: The operation name. + :paramtype name: str + :keyword display_name: The operation display name. + :paramtype display_name: str + :keyword description: The operation description. + :paramtype description: str + :keyword origin: The operation origin. + :paramtype origin: str + :keyword properties: The operation properties. + :paramtype properties: JSON + :keyword is_data_action: The dataAction flag to specify the operation type. + :paramtype is_data_action: bool + """ + super().__init__(**kwargs) self.name = name self.display_name = display_name self.description = description @@ -217,44 +248,62 @@ def __init__( self.is_data_action = is_data_action -class ProviderOperationsMetadata(msrest.serialization.Model): +class ProviderOperationsMetadata(_serialization.Model): """Provider Operations metadata. - :param id: The provider id. - :type id: str - :param name: The provider name. - :type name: str - :param type: The provider type. - :type type: str - :param display_name: The provider display name. - :type display_name: str - :param resource_types: The provider resource types. - :type resource_types: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] - :param operations: The provider operations. - :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] + :ivar id: The provider id. + :vartype id: str + :ivar name: The provider name. + :vartype name: str + :ivar type: The provider type. + :vartype type: str + :ivar display_name: The provider display name. + :vartype display_name: str + :ivar resource_types: The provider resource types. + :vartype resource_types: + list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] + :ivar operations: The provider operations. + :vartype operations: + list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'resource_types': {'key': 'resourceTypes', 'type': '[ResourceType]'}, - 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "resource_types": {"key": "resourceTypes", "type": "[ResourceType]"}, + "operations": {"key": "operations", "type": "[ProviderOperation]"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, type: Optional[str] = None, display_name: Optional[str] = None, - resource_types: Optional[List["ResourceType"]] = None, - operations: Optional[List["ProviderOperation"]] = None, + resource_types: Optional[List["_models.ResourceType"]] = None, + operations: Optional[List["_models.ProviderOperation"]] = None, **kwargs ): - super(ProviderOperationsMetadata, self).__init__(**kwargs) + """ + :keyword id: The provider id. + :paramtype id: str + :keyword name: The provider name. + :paramtype name: str + :keyword type: The provider type. + :paramtype type: str + :keyword display_name: The provider display name. + :paramtype display_name: str + :keyword resource_types: The provider resource types. + :paramtype resource_types: + list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] + :keyword operations: The provider operations. + :paramtype operations: + list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] + """ + super().__init__(**kwargs) self.id = id self.name = name self.type = type @@ -263,48 +312,56 @@ def __init__( self.operations = operations -class ProviderOperationsMetadataListResult(msrest.serialization.Model): +class ProviderOperationsMetadataListResult(_serialization.Model): """Provider operations metadata list. - :param value: The list of providers. - :type value: + :ivar value: The list of providers. + :vartype value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ProviderOperationsMetadata]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ProviderOperationsMetadata]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["ProviderOperationsMetadata"]] = None, + value: Optional[List["_models.ProviderOperationsMetadata"]] = None, next_link: Optional[str] = None, **kwargs ): - super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) + """ + :keyword value: The list of providers. + :paramtype value: + list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ResourceType(msrest.serialization.Model): +class ResourceType(_serialization.Model): """Resource Type. - :param name: The resource type name. - :type name: str - :param display_name: The resource type display name. - :type display_name: str - :param operations: The resource type operations. - :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] + :ivar name: The resource type name. + :vartype name: str + :ivar display_name: The resource type display name. + :vartype display_name: str + :ivar operations: The resource type operations. + :vartype operations: + list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "operations": {"key": "operations", "type": "[ProviderOperation]"}, } def __init__( @@ -312,16 +369,25 @@ def __init__( *, name: Optional[str] = None, display_name: Optional[str] = None, - operations: Optional[List["ProviderOperation"]] = None, + operations: Optional[List["_models.ProviderOperation"]] = None, **kwargs ): - super(ResourceType, self).__init__(**kwargs) + """ + :keyword name: The resource type name. + :paramtype name: str + :keyword display_name: The resource type display name. + :paramtype display_name: str + :keyword operations: The resource type operations. + :paramtype operations: + list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] + """ + super().__init__(**kwargs) self.name = name self.display_name = display_name self.operations = operations -class RoleAssignment(msrest.serialization.Model): +class RoleAssignment(_serialization.Model): """Role Assignments. Variables are only populated by the server, and will be ignored when sending a request. @@ -332,30 +398,30 @@ class RoleAssignment(msrest.serialization.Model): :vartype name: str :ivar type: The role assignment type. :vartype type: str - :param scope: The role assignment scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool + :ivar scope: The role assignment scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar can_delegate: The Delegation flag for the role assignment. + :vartype can_delegate: bool """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "can_delegate": {"key": "properties.canDelegate", "type": "bool"}, } def __init__( @@ -367,7 +433,17 @@ def __init__( can_delegate: Optional[bool] = None, **kwargs ): - super(RoleAssignment, self).__init__(**kwargs) + """ + :keyword scope: The role assignment scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword can_delegate: The Delegation flag for the role assignment. + :paramtype can_delegate: bool + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -377,98 +453,102 @@ def __init__( self.can_delegate = can_delegate -class RoleAssignmentCreateParameters(msrest.serialization.Model): +class RoleAssignmentCreateParameters(_serialization.Model): """Role assignment create parameters. All required parameters must be populated in order to send to Azure. - :param role_definition_id: Required. The role definition ID used in the role assignment. - :type role_definition_id: str - :param principal_id: Required. The principal ID assigned to the role. This maps to the ID - inside the Active Directory. It can point to a user, service principal, or security group. - :type principal_id: str - :param can_delegate: The delegation flag used for creating a role assignment. - :type can_delegate: bool + :ivar role_definition_id: The role definition ID used in the role assignment. Required. + :vartype role_definition_id: str + :ivar principal_id: The principal ID assigned to the role. This maps to the ID inside the + Active Directory. It can point to a user, service principal, or security group. Required. + :vartype principal_id: str + :ivar can_delegate: The delegation flag used for creating a role assignment. + :vartype can_delegate: bool """ _validation = { - 'role_definition_id': {'required': True}, - 'principal_id': {'required': True}, + "role_definition_id": {"required": True}, + "principal_id": {"required": True}, } _attribute_map = { - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "can_delegate": {"key": "properties.canDelegate", "type": "bool"}, } - def __init__( - self, - *, - role_definition_id: str, - principal_id: str, - can_delegate: Optional[bool] = None, - **kwargs - ): - super(RoleAssignmentCreateParameters, self).__init__(**kwargs) + def __init__(self, *, role_definition_id: str, principal_id: str, can_delegate: Optional[bool] = None, **kwargs): + """ + :keyword role_definition_id: The role definition ID used in the role assignment. Required. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID assigned to the role. This maps to the ID inside the + Active Directory. It can point to a user, service principal, or security group. Required. + :paramtype principal_id: str + :keyword can_delegate: The delegation flag used for creating a role assignment. + :paramtype can_delegate: bool + """ + super().__init__(**kwargs) self.role_definition_id = role_definition_id self.principal_id = principal_id self.can_delegate = can_delegate -class RoleAssignmentFilter(msrest.serialization.Model): +class RoleAssignmentFilter(_serialization.Model): """Role Assignments filter. - :param principal_id: Returns role assignment of the specific principal. - :type principal_id: str - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool + :ivar principal_id: Returns role assignment of the specific principal. + :vartype principal_id: str + :ivar can_delegate: The Delegation flag for the role assignment. + :vartype can_delegate: bool """ _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'can_delegate': {'key': 'canDelegate', 'type': 'bool'}, + "principal_id": {"key": "principalId", "type": "str"}, + "can_delegate": {"key": "canDelegate", "type": "bool"}, } - def __init__( - self, - *, - principal_id: Optional[str] = None, - can_delegate: Optional[bool] = None, - **kwargs - ): - super(RoleAssignmentFilter, self).__init__(**kwargs) + def __init__(self, *, principal_id: Optional[str] = None, can_delegate: Optional[bool] = None, **kwargs): + """ + :keyword principal_id: Returns role assignment of the specific principal. + :paramtype principal_id: str + :keyword can_delegate: The Delegation flag for the role assignment. + :paramtype can_delegate: bool + """ + super().__init__(**kwargs) self.principal_id = principal_id self.can_delegate = can_delegate -class RoleAssignmentListResult(msrest.serialization.Model): +class RoleAssignmentListResult(_serialization.Model): """Role assignment list operation result. - :param value: Role assignment list. - :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Role assignment list. + :vartype value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["RoleAssignment"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.RoleAssignment"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleAssignmentListResult, self).__init__(**kwargs) + """ + :keyword value: Role assignment list. + :paramtype value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class RoleDefinition(msrest.serialization.Model): +class RoleDefinition(_serialization.Model): """Role definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -479,33 +559,33 @@ class RoleDefinition(msrest.serialization.Model): :vartype name: str :ivar type: The role definition type. :vartype type: str - :param role_name: The role name. - :type role_name: str - :param description: The role definition description. - :type description: str - :param role_type: The role type. - :type role_type: str - :param permissions: Role definition permissions. - :type permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] - :param assignable_scopes: Role definition assignable scopes. - :type assignable_scopes: list[str] + :ivar role_name: The role name. + :vartype role_name: str + :ivar description: The role definition description. + :vartype description: str + :ivar role_type: The role type. + :vartype role_type: str + :ivar permissions: Role definition permissions. + :vartype permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] + :ivar assignable_scopes: Role definition assignable scopes. + :vartype assignable_scopes: list[str] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'role_name': {'key': 'properties.roleName', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'role_type': {'key': 'properties.type', 'type': 'str'}, - 'permissions': {'key': 'properties.permissions', 'type': '[Permission]'}, - 'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "role_name": {"key": "properties.roleName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "role_type": {"key": "properties.type", "type": "str"}, + "permissions": {"key": "properties.permissions", "type": "[Permission]"}, + "assignable_scopes": {"key": "properties.assignableScopes", "type": "[str]"}, } def __init__( @@ -514,11 +594,23 @@ def __init__( role_name: Optional[str] = None, description: Optional[str] = None, role_type: Optional[str] = None, - permissions: Optional[List["Permission"]] = None, + permissions: Optional[List["_models.Permission"]] = None, assignable_scopes: Optional[List[str]] = None, **kwargs ): - super(RoleDefinition, self).__init__(**kwargs) + """ + :keyword role_name: The role name. + :paramtype role_name: str + :keyword description: The role definition description. + :paramtype description: str + :keyword role_type: The role type. + :paramtype role_type: str + :keyword permissions: Role definition permissions. + :paramtype permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] + :keyword assignable_scopes: Role definition assignable scopes. + :paramtype assignable_scopes: list[str] + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -529,53 +621,55 @@ def __init__( self.assignable_scopes = assignable_scopes -class RoleDefinitionFilter(msrest.serialization.Model): +class RoleDefinitionFilter(_serialization.Model): """Role Definitions filter. - :param role_name: Returns role definition with the specific name. - :type role_name: str - :param type: Returns role definition with the specific type. - :type type: str + :ivar role_name: Returns role definition with the specific name. + :vartype role_name: str + :ivar type: Returns role definition with the specific type. + :vartype type: str """ _attribute_map = { - 'role_name': {'key': 'roleName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "role_name": {"key": "roleName", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - *, - role_name: Optional[str] = None, - type: Optional[str] = None, - **kwargs - ): - super(RoleDefinitionFilter, self).__init__(**kwargs) + def __init__(self, *, role_name: Optional[str] = None, type: Optional[str] = None, **kwargs): + """ + :keyword role_name: Returns role definition with the specific name. + :paramtype role_name: str + :keyword type: Returns role definition with the specific type. + :paramtype type: str + """ + super().__init__(**kwargs) self.role_name = role_name self.type = type -class RoleDefinitionListResult(msrest.serialization.Model): +class RoleDefinitionListResult(_serialization.Model): """Role definition list operation result. - :param value: Role definition list. - :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Role definition list. + :vartype value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleDefinition]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["RoleDefinition"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.RoleDefinition"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleDefinitionListResult, self).__init__(**kwargs) + """ + :keyword value: Role definition list. + :paramtype value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/__init__.py index be3e88f5724..88276b0bfd9 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/__init__.py @@ -11,9 +11,15 @@ from ._permissions_operations import PermissionsOperations from ._role_definitions_operations import RoleDefinitionsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'ProviderOperationsMetadataOperations', - 'RoleAssignmentsOperations', - 'PermissionsOperations', - 'RoleDefinitionsOperations', + "ProviderOperationsMetadataOperations", + "RoleAssignmentsOperations", + "PermissionsOperations", + "RoleDefinitionsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_permissions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_permissions_operations.py index 5fcce526eb2..df3bd393290 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_permissions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_permissions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,183 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class PermissionsOperations(object): - """PermissionsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_list_for_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceProviderNamespace": _SERIALIZER.url( + "resource_provider_namespace", resource_provider_namespace, "str", skip_quote=True + ), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PermissionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_01_01_preview.AuthorizationManagementClient`'s + :attr:`permissions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list_for_resource_group( - self, - resource_group_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PermissionGetResult"] + @distributed_trace + def list_for_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Permission"]: """Gets all permissions the caller has for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PermissionGetResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.PermissionGetResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PermissionGetResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PermissionGetResult', pipeline_response) + deserialized = self._deserialize("PermissionGetResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -102,86 +191,96 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions'} # type: ignore + return ItemPaged(get_next, extract_data) + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions"} # type: ignore + + @distributed_trace def list_for_resource( self, - resource_group_name, # type: str - resource_provider_namespace, # type: str - parent_resource_path, # type: str - resource_type, # type: str - resource_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PermissionGetResult"] + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + **kwargs: Any + ) -> Iterable["_models.Permission"]: """Gets all permissions the caller has for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get the permissions for. + :param resource_name: The name of the resource to get the permissions for. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PermissionGetResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.PermissionGetResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PermissionGetResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PermissionGetResult', pipeline_response) + deserialized = self._deserialize("PermissionGetResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -190,17 +289,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_provider_operations_metadata_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_provider_operations_metadata_operations.py index 2331c9c0454..8b7173f1821 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_provider_operations_metadata_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_provider_operations_metadata_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,152 +6,219 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(resource_provider_namespace: str, *, expand: str = "resourceTypes", **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}" + ) + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url( + "resource_provider_namespace", resource_provider_namespace, "str", skip_quote=True + ), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class ProviderOperationsMetadataOperations(object): - """ProviderOperationsMetadataOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +def build_list_request(*, expand: str = "resourceTypes", **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/providerOperations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ProviderOperationsMetadataOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_01_01_preview.AuthorizationManagementClient`'s + :attr:`provider_operations_metadata` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def get( - self, - resource_provider_namespace, # type: str - expand="resourceTypes", # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.ProviderOperationsMetadata" + self, resource_provider_namespace: str, expand: str = "resourceTypes", **kwargs: Any + ) -> _models.ProviderOperationsMetadata: """Gets provider operations metadata for the specified resource provider. - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param expand: Specifies whether to expand the values. + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ProviderOperationsMetadata, or the result of cls(response) + :return: ProviderOperationsMetadata or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProviderOperationsMetadata"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadata] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + request = build_get_request( + resource_provider_namespace=resource_provider_namespace, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ProviderOperationsMetadata', pipeline_response) + deserialized = self._deserialize("ProviderOperationsMetadata", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}'} # type: ignore - - def list( - self, - expand="resourceTypes", # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ProviderOperationsMetadataListResult"] + + get.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}"} # type: ignore + + @distributed_trace + def list(self, expand: str = "resourceTypes", **kwargs: Any) -> Iterable["_models.ProviderOperationsMetadata"]: """Gets provider operations metadata for all resource providers. - :param expand: Specifies whether to expand the values. + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProviderOperationsMetadataListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadataListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ProviderOperationsMetadata or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProviderOperationsMetadataListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadataListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ProviderOperationsMetadataListResult', pipeline_response) + deserialized = self._deserialize("ProviderOperationsMetadataListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -159,17 +227,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/providerOperations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_role_assignments_operations.py index 8ec1f2daa99..17fbec816a1 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_role_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,118 +6,424 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceProviderNamespace": _SERIALIZER.url( + "resource_provider_namespace", resource_provider_namespace, "str", skip_quote=True + ), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_group_request( + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request(role_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleId}") + path_format_arguments = { + "roleId": _SERIALIZER.url("role_id", role_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_by_id_request(role_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleId}") + path_format_arguments = { + "roleId": _SERIALIZER.url("role_id", role_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class RoleAssignmentsOperations(object): - """RoleAssignmentsOperations operations. + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +def build_get_by_id_request(role_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleId}") + path_format_arguments = { + "roleId": _SERIALIZER.url("role_id", role_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_01_01_preview.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_resource( self, - resource_group_name, # type: str - resource_provider_namespace, # type: str - parent_resource_path, # type: str - resource_type, # type: str - resource_name, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """Gets role assignments for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get role assignments for. + :param resource_name: The name of the resource to get role assignments for. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -125,77 +432,83 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_resource_group( - self, - resource_group_name, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """Gets role assignments for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -204,90 +517,92 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) - def delete( - self, - scope, # type: str - role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleAssignment"] + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace + def delete(self, scope: str, role_assignment_name: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. - :param scope: The scope of the role assignment to delete. + :param scope: The scope of the role assignment to delete. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to delete. + :param role_assignment_name: The name of the role assignment to delete. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload def create( self, - scope, # type: str - role_assignment_name, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + scope: str, + role_assignment_name: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: """Creates a role assignment. :param scope: The scope of the role assignment to create. The scope can be any REST resource @@ -295,350 +610,490 @@ def create( '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to create. It can be any valid - GUID. + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - def get( - self, - scope, # type: str - role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace + def get(self, scope: str, role_assignment_name: str, **kwargs: Any) -> _models.RoleAssignment: """Get the specified role assignment. - :param scope: The scope of the role assignment. + :param scope: The scope of the role assignment. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to get. + :param role_assignment_name: The name of the role assignment to get. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - def delete_by_id( - self, - role_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleAssignment"] + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace + def delete_by_id(self, role_id: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. - :param role_id: The ID of the role assignment to delete. + :param role_id: The ID of the role assignment to delete. Required. :type role_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_id.metadata = {'url': '/{roleId}'} # type: ignore + delete_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @overload def create_by_id( self, - role_id, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + role_id: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_by_id( + self, role_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_by_id( + self, role_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: """Creates a role assignment by ID. - :param role_id: The ID of the role assignment to create. + :param role_id: The ID of the role assignment to create. Required. :type role_id: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_id=role_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_by_id.metadata = {'url': '/{roleId}'} # type: ignore - def get_by_id( - self, - role_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + create_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace + def get_by_id(self, role_id: str, **kwargs: Any) -> _models.RoleAssignment: """Gets a role assignment by ID. - :param role_id: The ID of the role assignment to get. + :param role_id: The ID of the role assignment to get. Required. :type role_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleId}'} # type: ignore - def list( - self, - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + get_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.RoleAssignment"]: """Gets all role assignments for the subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -647,76 +1102,81 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """Gets role assignments for a scope. - :param scope: The scope of the role assignments. + :param scope: The scope of the role assignments. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -725,17 +1185,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_role_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_role_definitions_operations.py index 00fc742eda7..68700b13c8f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_role_definitions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/operations/_role_definitions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,287 +6,490 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_delete_request(scope: str, role_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(scope: str, role_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class RoleDefinitionsOperations(object): - """RoleDefinitionsOperations operations. + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +def build_list_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(role_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleId}") + path_format_arguments = { + "roleId": _SERIALIZER.url("role_id", role_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_01_01_preview.AuthorizationManagementClient`'s + :attr:`role_definitions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def delete( - self, - scope, # type: str - role_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleDefinition"] + @distributed_trace + def delete(self, scope: str, role_definition_id: str, **kwargs: Any) -> Optional[_models.RoleDefinition]: """Deletes a role definition. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition to delete. + :param role_definition_id: The ID of the role definition to delete. Required. :type role_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleDefinition"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleDefinition]] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_delete_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore - def get( - self, - scope, # type: str - role_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleDefinition" + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace + def get(self, scope: str, role_definition_id: str, **kwargs: Any) -> _models.RoleDefinition: """Get role definition by name (GUID). - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition. + :param role_definition_id: The ID of the role definition. Required. :type role_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + request = build_get_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @overload def create_or_update( self, - scope, # type: str - role_definition_id, # type: str - role_definition, # type: "_models.RoleDefinition" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleDefinition" + scope: str, + role_definition_id: str, + role_definition: _models.RoleDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleDefinition: """Creates or updates a role definition. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str - :param role_definition_id: The ID of the role definition. + :param role_definition_id: The ID of the role definition. Required. :type role_definition_id: str - :param role_definition: The values for the role definition. + :param role_definition: The values for the role definition. Required. :type role_definition: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + scope: str, + role_definition_id: str, + role_definition: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Required. + :type role_definition: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, scope: str, role_definition_id: str, role_definition: Union[_models.RoleDefinition, IO], **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Is either a model type or a IO + type. Required. + :type role_definition: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleDefinitionId': self._serialize.url("role_definition_id", role_definition_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(role_definition, 'RoleDefinition') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(role_definition, (IO, bytes)): + _content = role_definition + else: + _json = self._serialize.body(role_definition, "RoleDefinition") + + request = build_create_or_update_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}'} # type: ignore - def list( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleDefinitionListResult"] + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace + def list(self, scope: str, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.RoleDefinition"]: """Get all role definitions that are applicable at scope and above. - :param scope: The scope of the role definition. + :param scope: The scope of the role definition. Required. :type scope: str :param filter: The filter to apply on the operation. Use atScopeAndBelow filter to search below - the given scope as well. + the given scope as well. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleDefinition or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("RoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -294,76 +498,77 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions'} # type: ignore + return ItemPaged(get_next, extract_data) - def get_by_id( - self, - role_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleDefinition" + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions"} # type: ignore + + @distributed_trace + def get_by_id(self, role_id: str, **kwargs: Any) -> _models.RoleDefinition: """Gets a role definition by ID. :param role_id: The fully qualified role definition ID. Use the format, /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for subscription level role definitions, or /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for tenant level role - definitions. + definitions. Required. :type role_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleDefinition, or the result of cls(response) + :return: RoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleDefinition', pipeline_response) + deserialized = self._deserialize("RoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleId}'} # type: ignore + + get_by_id.metadata = {"url": "/{roleId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/__init__.py index ae11ad3e4d9..9eb8d3ec28c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AuthorizationManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_authorization_management_client.py index ce546ece531..1809788a3d1 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_authorization_management_client.py @@ -6,113 +6,140 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + AccessReviewDefaultSettingsOperations, + AccessReviewInstanceDecisionsOperations, + AccessReviewInstanceMyDecisionsOperations, + AccessReviewInstanceOperations, + AccessReviewInstancesAssignedForMyApprovalOperations, + AccessReviewInstancesOperations, + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, + AccessReviewScheduleDefinitionsOperations, + Operations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import Operations -from .operations import AccessReviewScheduleDefinitionsOperations -from .operations import AccessReviewInstancesOperations -from .operations import AccessReviewInstanceOperations -from .operations import AccessReviewInstanceDecisionsOperations -from .operations import AccessReviewDefaultSettingsOperations -from .operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations -from .operations import AccessReviewInstancesAssignedForMyApprovalOperations -from .operations import AccessReviewInstanceMyDecisionsOperations -from . import models -class AuthorizationManagementClient(object): - """Access reviews service provides the workflow for running access reviews on different kind of resources. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Access reviews service provides the workflow for running access reviews on different kind of + resources. :ivar operations: Operations operations :vartype operations: azure.mgmt.authorization.v2018_05_01_preview.operations.Operations :ivar access_review_schedule_definitions: AccessReviewScheduleDefinitionsOperations operations - :vartype access_review_schedule_definitions: azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewScheduleDefinitionsOperations + :vartype access_review_schedule_definitions: + azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewScheduleDefinitionsOperations :ivar access_review_instances: AccessReviewInstancesOperations operations - :vartype access_review_instances: azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewInstancesOperations + :vartype access_review_instances: + azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewInstancesOperations :ivar access_review_instance: AccessReviewInstanceOperations operations - :vartype access_review_instance: azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewInstanceOperations + :vartype access_review_instance: + azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewInstanceOperations :ivar access_review_instance_decisions: AccessReviewInstanceDecisionsOperations operations - :vartype access_review_instance_decisions: azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewInstanceDecisionsOperations + :vartype access_review_instance_decisions: + azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewInstanceDecisionsOperations :ivar access_review_default_settings: AccessReviewDefaultSettingsOperations operations - :vartype access_review_default_settings: azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewDefaultSettingsOperations - :ivar access_review_schedule_definitions_assigned_for_my_approval: AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations - :vartype access_review_schedule_definitions_assigned_for_my_approval: azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations - :ivar access_review_instances_assigned_for_my_approval: AccessReviewInstancesAssignedForMyApprovalOperations operations - :vartype access_review_instances_assigned_for_my_approval: azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewInstancesAssignedForMyApprovalOperations + :vartype access_review_default_settings: + azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewDefaultSettingsOperations + :ivar access_review_schedule_definitions_assigned_for_my_approval: + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations + :vartype access_review_schedule_definitions_assigned_for_my_approval: + azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations + :ivar access_review_instances_assigned_for_my_approval: + AccessReviewInstancesAssignedForMyApprovalOperations operations + :vartype access_review_instances_assigned_for_my_approval: + azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewInstancesAssignedForMyApprovalOperations :ivar access_review_instance_my_decisions: AccessReviewInstanceMyDecisionsOperations operations - :vartype access_review_instance_my_decisions: azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewInstanceMyDecisionsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype access_review_instance_my_decisions: + azure.mgmt.authorization.v2018_05_01_preview.operations.AccessReviewInstanceMyDecisionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-05-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.access_review_schedule_definitions = AccessReviewScheduleDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instances = AccessReviewInstancesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance = AccessReviewInstanceOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance_decisions = AccessReviewInstanceDecisionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_default_settings = AccessReviewDefaultSettingsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.access_review_schedule_definitions_assigned_for_my_approval = AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_schedule_definitions_assigned_for_my_approval = ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) self.access_review_instances_assigned_for_my_approval = AccessReviewInstancesAssignedForMyApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance_my_decisions = AccessReviewInstanceMyDecisionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_configuration.py index 5c9bd6311f4..5ebeec3f5a8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_configuration.py @@ -6,66 +6,64 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-05-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2018-05-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-05-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_metadata.json index e992c72e1e2..73b4e50e993 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_metadata.json +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_metadata.json @@ -5,25 +5,25 @@ "name": "AuthorizationManagementClient", "filename": "_authorization_management_client", "description": "Access reviews service provides the workflow for running access reviews on different kind of resources.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, "azure_arm": true, "has_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -54,7 +54,7 @@ "required": false }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -74,7 +74,7 @@ "required": false }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -91,11 +91,10 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "operations": "Operations", diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_version.py index 48944bf3938..cac9f5d10f8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/__init__.py index ffc49d028e4..dd28625b36f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._authorization_management_client import AuthorizationManagementClient -__all__ = ['AuthorizationManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_authorization_management_client.py index 57640f36f63..7612f2b6d18 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_authorization_management_client.py @@ -6,109 +6,140 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + AccessReviewDefaultSettingsOperations, + AccessReviewInstanceDecisionsOperations, + AccessReviewInstanceMyDecisionsOperations, + AccessReviewInstanceOperations, + AccessReviewInstancesAssignedForMyApprovalOperations, + AccessReviewInstancesOperations, + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, + AccessReviewScheduleDefinitionsOperations, + Operations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import Operations -from .operations import AccessReviewScheduleDefinitionsOperations -from .operations import AccessReviewInstancesOperations -from .operations import AccessReviewInstanceOperations -from .operations import AccessReviewInstanceDecisionsOperations -from .operations import AccessReviewDefaultSettingsOperations -from .operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations -from .operations import AccessReviewInstancesAssignedForMyApprovalOperations -from .operations import AccessReviewInstanceMyDecisionsOperations -from .. import models - -class AuthorizationManagementClient(object): - """Access reviews service provides the workflow for running access reviews on different kind of resources. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Access reviews service provides the workflow for running access reviews on different kind of + resources. :ivar operations: Operations operations :vartype operations: azure.mgmt.authorization.v2018_05_01_preview.aio.operations.Operations :ivar access_review_schedule_definitions: AccessReviewScheduleDefinitionsOperations operations - :vartype access_review_schedule_definitions: azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewScheduleDefinitionsOperations + :vartype access_review_schedule_definitions: + azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewScheduleDefinitionsOperations :ivar access_review_instances: AccessReviewInstancesOperations operations - :vartype access_review_instances: azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewInstancesOperations + :vartype access_review_instances: + azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewInstancesOperations :ivar access_review_instance: AccessReviewInstanceOperations operations - :vartype access_review_instance: azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewInstanceOperations + :vartype access_review_instance: + azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewInstanceOperations :ivar access_review_instance_decisions: AccessReviewInstanceDecisionsOperations operations - :vartype access_review_instance_decisions: azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewInstanceDecisionsOperations + :vartype access_review_instance_decisions: + azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewInstanceDecisionsOperations :ivar access_review_default_settings: AccessReviewDefaultSettingsOperations operations - :vartype access_review_default_settings: azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewDefaultSettingsOperations - :ivar access_review_schedule_definitions_assigned_for_my_approval: AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations - :vartype access_review_schedule_definitions_assigned_for_my_approval: azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations - :ivar access_review_instances_assigned_for_my_approval: AccessReviewInstancesAssignedForMyApprovalOperations operations - :vartype access_review_instances_assigned_for_my_approval: azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewInstancesAssignedForMyApprovalOperations + :vartype access_review_default_settings: + azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewDefaultSettingsOperations + :ivar access_review_schedule_definitions_assigned_for_my_approval: + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations + :vartype access_review_schedule_definitions_assigned_for_my_approval: + azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations + :ivar access_review_instances_assigned_for_my_approval: + AccessReviewInstancesAssignedForMyApprovalOperations operations + :vartype access_review_instances_assigned_for_my_approval: + azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewInstancesAssignedForMyApprovalOperations :ivar access_review_instance_my_decisions: AccessReviewInstanceMyDecisionsOperations operations - :vartype access_review_instance_my_decisions: azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewInstanceMyDecisionsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype access_review_instance_my_decisions: + azure.mgmt.authorization.v2018_05_01_preview.aio.operations.AccessReviewInstanceMyDecisionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-05-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.access_review_schedule_definitions = AccessReviewScheduleDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instances = AccessReviewInstancesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance = AccessReviewInstanceOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance_decisions = AccessReviewInstanceDecisionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_default_settings = AccessReviewDefaultSettingsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.access_review_schedule_definitions_assigned_for_my_approval = AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_schedule_definitions_assigned_for_my_approval = ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) self.access_review_instances_assigned_for_my_approval = AccessReviewInstancesAssignedForMyApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance_my_decisions = AccessReviewInstanceMyDecisionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_configuration.py index a07795ddc22..f3f28118560 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,49 +19,48 @@ from azure.core.credentials_async import AsyncTokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-05-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2018-05-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-05-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/__init__.py index 9fe7178064d..2ed7cbae216 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/__init__.py @@ -12,18 +12,28 @@ from ._access_review_instance_operations import AccessReviewInstanceOperations from ._access_review_instance_decisions_operations import AccessReviewInstanceDecisionsOperations from ._access_review_default_settings_operations import AccessReviewDefaultSettingsOperations -from ._access_review_schedule_definitions_assigned_for_my_approval_operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations -from ._access_review_instances_assigned_for_my_approval_operations import AccessReviewInstancesAssignedForMyApprovalOperations +from ._access_review_schedule_definitions_assigned_for_my_approval_operations import ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, +) +from ._access_review_instances_assigned_for_my_approval_operations import ( + AccessReviewInstancesAssignedForMyApprovalOperations, +) from ._access_review_instance_my_decisions_operations import AccessReviewInstanceMyDecisionsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'Operations', - 'AccessReviewScheduleDefinitionsOperations', - 'AccessReviewInstancesOperations', - 'AccessReviewInstanceOperations', - 'AccessReviewInstanceDecisionsOperations', - 'AccessReviewDefaultSettingsOperations', - 'AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations', - 'AccessReviewInstancesAssignedForMyApprovalOperations', - 'AccessReviewInstanceMyDecisionsOperations', + "Operations", + "AccessReviewScheduleDefinitionsOperations", + "AccessReviewInstancesOperations", + "AccessReviewInstanceOperations", + "AccessReviewInstanceDecisionsOperations", + "AccessReviewDefaultSettingsOperations", + "AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations", + "AccessReviewInstancesAssignedForMyApprovalOperations", + "AccessReviewInstanceMyDecisionsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_default_settings_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_default_settings_operations.py index 13b6cb88ffe..65dc2dd6ea3 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_default_settings_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_default_settings_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,147 +6,208 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_default_settings_operations import build_get_request, build_put_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewDefaultSettingsOperations: - """AccessReviewDefaultSettingsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewDefaultSettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_default_settings` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get( - self, - **kwargs: Any - ) -> "_models.AccessReviewDefaultSettings": + @distributed_trace_async + async def get(self, **kwargs: Any) -> _models.AccessReviewDefaultSettings: """Get access review default settings for the subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDefaultSettings, or the result of cls(response) + :return: AccessReviewDefaultSettings or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDefaultSettings - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDefaultSettings"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDefaultSettings', pipeline_response) + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore + + @overload async def put( - self, - properties: "_models.AccessReviewScheduleSettings", - **kwargs: Any - ) -> "_models.AccessReviewDefaultSettings": + self, properties: _models.AccessReviewScheduleSettings, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: """Get access review default settings for the subscription. - :param properties: Access review schedule settings. - :type properties: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleSettings + :param properties: Access review schedule settings. Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleSettings + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDefaultSettings, or the result of cls(response) + :return: AccessReviewDefaultSettings or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDefaultSettings - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put( + self, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put( + self, properties: Union[_models.AccessReviewScheduleSettings, IO], **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleSettings or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDefaultSettings"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.put.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewScheduleSettings') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleSettings") + + request = build_put_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDefaultSettings', pipeline_response) + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default'} # type: ignore + + put.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_decisions_operations.py index e1a995a343d..f77bae8a357 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_decisions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_decisions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,94 +6,111 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instance_decisions_operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewInstanceDecisionsOperations: - """AccessReviewInstanceDecisionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewInstanceDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance_decisions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewDecisionListResult"]: + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewDecision"]: """Get access review instance decisions. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewDecisionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecisionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecisionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewDecisionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -101,17 +119,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py index 22ab8981dbf..74391fd06e1 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,93 +6,115 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._access_review_instance_my_decisions_operations import ( + build_get_by_id_request, + build_list_request, + build_patch_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewInstanceMyDecisionsOperations: - """AccessReviewInstanceMyDecisionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewInstanceMyDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance_my_decisions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewDecisionListResult"]: + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewDecision"]: """Get my access review instance decisions. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewDecisionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecisionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecisionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewDecisionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -100,149 +123,229 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore + + @distributed_trace_async async def get_by_id( - self, - schedule_definition_id: str, - id: str, - decision_id: str, - **kwargs: Any - ) -> "_models.AccessReviewDecision": + self, schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any + ) -> _models.AccessReviewDecision: """Get my single access review instance decision. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str - :param decision_id: The id of the decision record. + :param decision_id: The id of the decision record. Required. :type decision_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDecision, or the result of cls(response) + :return: AccessReviewDecision or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecision"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'decisionId': self._serialize.url("decision_id", decision_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDecision', pipeline_response) + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}'} # type: ignore + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore + + @overload async def patch( self, schedule_definition_id: str, id: str, decision_id: str, - properties: "_models.AccessReviewDecisionProperties", + properties: _models.AccessReviewDecisionProperties, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.AccessReviewDecision": + ) -> _models.AccessReviewDecision: """Record a decision. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str - :param decision_id: The id of the decision record. + :param decision_id: The id of the decision record. Required. :type decision_id: str - :param properties: Access review decision properties to patch. - :type properties: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecisionProperties + :param properties: Access review decision properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecisionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDecision, or the result of cls(response) + :return: AccessReviewDecision or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: Union[_models.AccessReviewDecisionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecisionProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecision"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.patch.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'decisionId': self._serialize.url("decision_id", decision_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewDecisionProperties') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewDecisionProperties") + + request = build_patch_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDecision', pipeline_response) + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - patch.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}'} # type: ignore + + patch.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_operations.py index 75c39ff8437..83d0bc9c440 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instance_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,316 +6,336 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._access_review_instance_operations import ( + build_accept_recommendations_request, + build_apply_decisions_request, + build_reset_decisions_request, + build_send_reminders_request, + build_stop_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewInstanceOperations: - """AccessReviewInstanceOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - async def stop( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any ) -> None: """An action to stop an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.stop.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - stop.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop'} # type: ignore + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop"} # type: ignore - async def reset_decisions( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any + @distributed_trace_async + async def reset_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any ) -> None: """An action to reset all decisions for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.reset_decisions.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reset_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.reset_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - reset_decisions.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions'} # type: ignore + reset_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions"} # type: ignore - async def apply_decisions( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any + @distributed_trace_async + async def apply_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any ) -> None: """An action to apply all decisions for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.apply_decisions.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_apply_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.apply_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - apply_decisions.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions'} # type: ignore + apply_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions"} # type: ignore - async def send_reminders( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any + @distributed_trace_async + async def send_reminders( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any ) -> None: """An action to send reminders for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.send_reminders.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_send_reminders_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.send_reminders.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - send_reminders.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders'} # type: ignore + send_reminders.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders"} # type: ignore - async def accept_recommendations( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any + @distributed_trace_async + async def accept_recommendations( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any ) -> None: """An action to accept recommendations for decision in an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.accept_recommendations.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_accept_recommendations_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.accept_recommendations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - accept_recommendations.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations'} # type: ignore + accept_recommendations.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py index fc9106f368c..ee4ba247b57 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,89 +6,109 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instances_assigned_for_my_approval_operations import ( + build_get_by_id_request, + build_list_request, +) -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewInstancesAssignedForMyApprovalOperations: - """AccessReviewInstancesAssignedForMyApprovalOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewInstancesAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instances_assigned_for_my_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - schedule_definition_id: str, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewInstanceListResult"]: + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, schedule_definition_id: str, **kwargs: Any) -> AsyncIterable["_models.AccessReviewInstance"]: """Get access review instances assigned for my approval. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewInstanceListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewInstanceListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -96,75 +117,76 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances'} # type: ignore - - async def get_by_id( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any - ) -> "_models.AccessReviewInstance": + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: """Get single access review instance assigned for my approval. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewInstance, or the result of cls(response) + :return: AccessReviewInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewInstance', pipeline_response) + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}'} # type: ignore + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instances_operations.py index 479d93c18f5..2db6374d42a 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instances_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_instances_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,90 +6,107 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instances_operations import build_get_by_id_request, build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewInstancesOperations: - """AccessReviewInstancesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instances` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - schedule_definition_id: str, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewInstanceListResult"]: + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, schedule_definition_id: str, **kwargs: Any) -> AsyncIterable["_models.AccessReviewInstance"]: """Get access review instances. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewInstanceListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewInstanceListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -97,76 +115,77 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances'} # type: ignore - - async def get_by_id( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any - ) -> "_models.AccessReviewInstance": + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: """Get access review instances. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewInstance, or the result of cls(response) + :return: AccessReviewInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewInstance', pipeline_response) + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}'} # type: ignore + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py index 7d876ea7ecd..05e1c3aa8be 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,102 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_schedule_definitions_assigned_for_my_approval_operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations: - """AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions_assigned_for_my_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewScheduleDefinitionListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.AccessReviewScheduleDefinition"]: """Get access review instances assigned for my approval. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewScheduleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewScheduleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -89,17 +110,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_schedule_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_schedule_definitions_operations.py index ede53b7fea6..cb6f84b1f70 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_schedule_definitions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_access_review_schedule_definitions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,86 +6,110 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._access_review_schedule_definitions_operations import ( + build_create_or_update_by_id_request, + build_delete_by_id_request, + build_get_by_id_request, + build_list_request, + build_stop_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewScheduleDefinitionsOperations: - """AccessReviewScheduleDefinitionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewScheduleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewScheduleDefinitionListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.AccessReviewScheduleDefinition"]: """Get access review schedule definitions. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewScheduleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewScheduleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -93,239 +118,307 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get_by_id( - self, - schedule_definition_id: str, - **kwargs: Any - ) -> "_models.AccessReviewScheduleDefinition": + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, **kwargs: Any) -> _models.AccessReviewScheduleDefinition: """Get single access review definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewScheduleDefinition, or the result of cls(response) + :return: AccessReviewScheduleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewScheduleDefinition', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore - async def delete_by_id( - self, - schedule_definition_id: str, - **kwargs: Any + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def delete_by_id( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any ) -> None: """Delete access review schedule definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_delete_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore + delete_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + @overload async def create_or_update_by_id( self, schedule_definition_id: str, - properties: "_models.AccessReviewScheduleDefinitionProperties", + properties: _models.AccessReviewScheduleDefinitionProperties, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.AccessReviewScheduleDefinition": + ) -> _models.AccessReviewScheduleDefinition: """Create or Update access review schedule definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param properties: Access review schedule definition properties. - :type properties: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionProperties + :param properties: Access review schedule definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewScheduleDefinition, or the result of cls(response) + :return: AccessReviewScheduleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_by_id( + self, schedule_definition_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: Union[_models.AccessReviewScheduleDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionProperties + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewScheduleDefinitionProperties') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleDefinitionProperties") + + request = build_create_or_update_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewScheduleDefinition', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore - async def stop( - self, - schedule_definition_id: str, - **kwargs: Any + create_or_update_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any ) -> None: """Stop access review definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.stop.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - stop.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop'} # type: ignore + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_operations.py index 1e2b098f9c7..246fb2ada88 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,101 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.aio.AuthorizationManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists the operations available from this provider. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -89,17 +109,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/operations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/__init__.py index 498d27291a3..b555500e3ca 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/__init__.py @@ -6,94 +6,76 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import AccessReviewDecision - from ._models_py3 import AccessReviewDecisionListResult - from ._models_py3 import AccessReviewDecisionProperties - from ._models_py3 import AccessReviewDecisionTarget - from ._models_py3 import AccessReviewDefaultSettings - from ._models_py3 import AccessReviewInstance - from ._models_py3 import AccessReviewInstanceListResult - from ._models_py3 import AccessReviewReviewer - from ._models_py3 import AccessReviewScheduleDefinition - from ._models_py3 import AccessReviewScheduleDefinitionListResult - from ._models_py3 import AccessReviewScheduleDefinitionProperties - from ._models_py3 import AccessReviewScheduleSettings - from ._models_py3 import ErrorDefinition - from ._models_py3 import ErrorDefinitionProperties - from ._models_py3 import Operation - from ._models_py3 import OperationDisplay - from ._models_py3 import OperationListResult - from ._models_py3 import ServicePrincipalDecisionTarget - from ._models_py3 import UserDecisionTarget -except (SyntaxError, ImportError): - from ._models import AccessReviewDecision # type: ignore - from ._models import AccessReviewDecisionListResult # type: ignore - from ._models import AccessReviewDecisionProperties # type: ignore - from ._models import AccessReviewDecisionTarget # type: ignore - from ._models import AccessReviewDefaultSettings # type: ignore - from ._models import AccessReviewInstance # type: ignore - from ._models import AccessReviewInstanceListResult # type: ignore - from ._models import AccessReviewReviewer # type: ignore - from ._models import AccessReviewScheduleDefinition # type: ignore - from ._models import AccessReviewScheduleDefinitionListResult # type: ignore - from ._models import AccessReviewScheduleDefinitionProperties # type: ignore - from ._models import AccessReviewScheduleSettings # type: ignore - from ._models import ErrorDefinition # type: ignore - from ._models import ErrorDefinitionProperties # type: ignore - from ._models import Operation # type: ignore - from ._models import OperationDisplay # type: ignore - from ._models import OperationListResult # type: ignore - from ._models import ServicePrincipalDecisionTarget # type: ignore - from ._models import UserDecisionTarget # type: ignore +from ._models_py3 import AccessReviewDecision +from ._models_py3 import AccessReviewDecisionListResult +from ._models_py3 import AccessReviewDecisionProperties +from ._models_py3 import AccessReviewDecisionTarget +from ._models_py3 import AccessReviewDefaultSettings +from ._models_py3 import AccessReviewInstance +from ._models_py3 import AccessReviewInstanceListResult +from ._models_py3 import AccessReviewReviewer +from ._models_py3 import AccessReviewScheduleDefinition +from ._models_py3 import AccessReviewScheduleDefinitionListResult +from ._models_py3 import AccessReviewScheduleDefinitionProperties +from ._models_py3 import AccessReviewScheduleSettings +from ._models_py3 import ErrorDefinition +from ._models_py3 import ErrorDefinitionProperties +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import ServicePrincipalDecisionTarget +from ._models_py3 import UserDecisionTarget -from ._authorization_management_client_enums import ( - AccessRecommendationType, - AccessReviewActorIdentityType, - AccessReviewApplyResult, - AccessReviewInstanceStatus, - AccessReviewRecurrencePatternType, - AccessReviewRecurrenceRangeType, - AccessReviewResult, - AccessReviewReviewerType, - AccessReviewScheduleDefinitionReviewersType, - AccessReviewScheduleDefinitionStatus, - AccessReviewScopePrincipalType, - DecisionTargetType, - DefaultDecisionType, -) +from ._authorization_management_client_enums import AccessRecommendationType +from ._authorization_management_client_enums import AccessReviewActorIdentityType +from ._authorization_management_client_enums import AccessReviewApplyResult +from ._authorization_management_client_enums import AccessReviewInstanceStatus +from ._authorization_management_client_enums import AccessReviewRecurrencePatternType +from ._authorization_management_client_enums import AccessReviewRecurrenceRangeType +from ._authorization_management_client_enums import AccessReviewResult +from ._authorization_management_client_enums import AccessReviewReviewerType +from ._authorization_management_client_enums import AccessReviewScheduleDefinitionReviewersType +from ._authorization_management_client_enums import AccessReviewScheduleDefinitionStatus +from ._authorization_management_client_enums import AccessReviewScopePrincipalType +from ._authorization_management_client_enums import DecisionTargetType +from ._authorization_management_client_enums import DefaultDecisionType +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'AccessReviewDecision', - 'AccessReviewDecisionListResult', - 'AccessReviewDecisionProperties', - 'AccessReviewDecisionTarget', - 'AccessReviewDefaultSettings', - 'AccessReviewInstance', - 'AccessReviewInstanceListResult', - 'AccessReviewReviewer', - 'AccessReviewScheduleDefinition', - 'AccessReviewScheduleDefinitionListResult', - 'AccessReviewScheduleDefinitionProperties', - 'AccessReviewScheduleSettings', - 'ErrorDefinition', - 'ErrorDefinitionProperties', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'ServicePrincipalDecisionTarget', - 'UserDecisionTarget', - 'AccessRecommendationType', - 'AccessReviewActorIdentityType', - 'AccessReviewApplyResult', - 'AccessReviewInstanceStatus', - 'AccessReviewRecurrencePatternType', - 'AccessReviewRecurrenceRangeType', - 'AccessReviewResult', - 'AccessReviewReviewerType', - 'AccessReviewScheduleDefinitionReviewersType', - 'AccessReviewScheduleDefinitionStatus', - 'AccessReviewScopePrincipalType', - 'DecisionTargetType', - 'DefaultDecisionType', + "AccessReviewDecision", + "AccessReviewDecisionListResult", + "AccessReviewDecisionProperties", + "AccessReviewDecisionTarget", + "AccessReviewDefaultSettings", + "AccessReviewInstance", + "AccessReviewInstanceListResult", + "AccessReviewReviewer", + "AccessReviewScheduleDefinition", + "AccessReviewScheduleDefinitionListResult", + "AccessReviewScheduleDefinitionProperties", + "AccessReviewScheduleSettings", + "ErrorDefinition", + "ErrorDefinitionProperties", + "Operation", + "OperationDisplay", + "OperationListResult", + "ServicePrincipalDecisionTarget", + "UserDecisionTarget", + "AccessRecommendationType", + "AccessReviewActorIdentityType", + "AccessReviewApplyResult", + "AccessReviewInstanceStatus", + "AccessReviewRecurrencePatternType", + "AccessReviewRecurrenceRangeType", + "AccessReviewResult", + "AccessReviewReviewerType", + "AccessReviewScheduleDefinitionReviewersType", + "AccessReviewScheduleDefinitionStatus", + "AccessReviewScopePrincipalType", + "DecisionTargetType", + "DefaultDecisionType", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_authorization_management_client_enums.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_authorization_management_client_enums.py index d00c500e2fa..27bfa98670e 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_authorization_management_client_enums.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_authorization_management_client_enums.py @@ -6,44 +6,27 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass - -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class AccessRecommendationType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The feature- generated recommendation shown to the reviewer. - """ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AccessRecommendationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The feature- generated recommendation shown to the reviewer.""" APPROVE = "Approve" DENY = "Deny" NO_INFO_AVAILABLE = "NoInfoAvailable" -class AccessReviewActorIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The identity type : user/servicePrincipal - """ + +class AccessReviewActorIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type : user/servicePrincipal.""" USER = "user" SERVICE_PRINCIPAL = "servicePrincipal" -class AccessReviewApplyResult(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The outcome of applying the decision. - """ + +class AccessReviewApplyResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The outcome of applying the decision.""" NEW = "New" APPLYING = "Applying" @@ -52,9 +35,9 @@ class AccessReviewApplyResult(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum APPLIED_SUCCESSFULLY_BUT_OBJECT_NOT_FOUND = "AppliedSuccessfullyButObjectNotFound" APPLY_NOT_SUPPORTED = "ApplyNotSupported" -class AccessReviewInstanceStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """This read-only field specifies the status of an access review instance. - """ + +class AccessReviewInstanceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This read-only field specifies the status of an access review instance.""" NOT_STARTED = "NotStarted" IN_PROGRESS = "InProgress" @@ -68,24 +51,25 @@ class AccessReviewInstanceStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, E AUTO_REVIEWED = "AutoReviewed" STARTING = "Starting" -class AccessReviewRecurrencePatternType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The recurrence type : weekly, monthly, etc. - """ + +class AccessReviewRecurrencePatternType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The recurrence type : weekly, monthly, etc.""" WEEKLY = "weekly" ABSOLUTE_MONTHLY = "absoluteMonthly" -class AccessReviewRecurrenceRangeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The recurrence range type. The possible values are: endDate, noEnd, numbered. - """ + +class AccessReviewRecurrenceRangeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The recurrence range type. The possible values are: endDate, noEnd, numbered.""" END_DATE = "endDate" NO_END = "noEnd" NUMBERED = "numbered" -class AccessReviewResult(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class AccessReviewResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The decision on the approval step. This value is initially set to NotReviewed. Approvers can - take action of Approve/Deny + take action of Approve/Deny. """ APPROVE = "Approve" @@ -94,14 +78,15 @@ class AccessReviewResult(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DONT_KNOW = "DontKnow" NOT_NOTIFIED = "NotNotified" -class AccessReviewReviewerType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The identity type : user/servicePrincipal - """ + +class AccessReviewReviewerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type : user/servicePrincipal.""" USER = "user" SERVICE_PRINCIPAL = "servicePrincipal" -class AccessReviewScheduleDefinitionReviewersType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class AccessReviewScheduleDefinitionReviewersType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """This field specifies the type of reviewers for a review. Usually for a review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be assigned and instead be chosen dynamically. For example managers review or self review. @@ -111,9 +96,9 @@ class AccessReviewScheduleDefinitionReviewersType(with_metaclass(_CaseInsensitiv SELF = "Self" MANAGERS = "Managers" -class AccessReviewScheduleDefinitionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """This read-only field specifies the status of an accessReview. - """ + +class AccessReviewScheduleDefinitionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This read-only field specifies the status of an accessReview.""" NOT_STARTED = "NotStarted" IN_PROGRESS = "InProgress" @@ -127,23 +112,23 @@ class AccessReviewScheduleDefinitionStatus(with_metaclass(_CaseInsensitiveEnumMe AUTO_REVIEWED = "AutoReviewed" STARTING = "Starting" -class AccessReviewScopePrincipalType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The identity type user/servicePrincipal to review - """ + +class AccessReviewScopePrincipalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type user/servicePrincipal to review.""" USER = "user" SERVICE_PRINCIPAL = "servicePrincipal" -class DecisionTargetType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of decision target : User/ServicePrincipal - """ + +class DecisionTargetType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of decision target : User/ServicePrincipal.""" USER = "user" SERVICE_PRINCIPAL = "servicePrincipal" -class DefaultDecisionType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """This specifies the behavior for the autoReview feature when an access review completes. - """ + +class DefaultDecisionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This specifies the behavior for the autoReview feature when an access review completes.""" APPROVE = "Approve" DENY = "Deny" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_models.py deleted file mode 100644 index a722a5bff82..00000000000 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_models.py +++ /dev/null @@ -1,1204 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class AccessReviewDecision(msrest.serialization.Model): - """Access Review. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The access review decision id. - :vartype id: str - :ivar name: The access review decision name. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - :ivar recommendation: The feature- generated recommendation shown to the reviewer. Possible - values include: "Approve", "Deny", "NoInfoAvailable". - :vartype recommendation: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessRecommendationType - :param decision: The decision on the approval step. This value is initially set to NotReviewed. - Approvers can take action of Approve/Deny. Possible values include: "Approve", "Deny", - "NotReviewed", "DontKnow", "NotNotified". - :type decision: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str - :ivar reviewed_date_time: Date Time when a decision was taken. - :vartype reviewed_date_time: ~datetime.datetime - :ivar apply_result: The outcome of applying the decision. Possible values include: "New", - "Applying", "AppliedSuccessfully", "AppliedWithUnknownFailure", - "AppliedSuccessfullyButObjectNotFound", "ApplyNotSupported". - :vartype apply_result: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewApplyResult - :ivar applied_date_time: The date and time when the review decision was applied. - :vartype applied_date_time: ~datetime.datetime - :ivar principal_id_properties_applied_by_principal_id: The identity id. - :vartype principal_id_properties_applied_by_principal_id: str - :ivar principal_type_properties_applied_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". - :vartype principal_type_properties_applied_by_principal_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name_properties_applied_by_principal_name: The identity display name. - :vartype principal_name_properties_applied_by_principal_name: str - :ivar user_principal_name_properties_applied_by_user_principal_name: The user principal name(if - valid). - :vartype user_principal_name_properties_applied_by_user_principal_name: str - :ivar principal_id_properties_reviewed_by_principal_id: The identity id. - :vartype principal_id_properties_reviewed_by_principal_id: str - :ivar principal_type_properties_reviewed_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". - :vartype principal_type_properties_reviewed_by_principal_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name_properties_reviewed_by_principal_name: The identity display name. - :vartype principal_name_properties_reviewed_by_principal_name: str - :ivar user_principal_name_properties_reviewed_by_user_principal_name: The user principal - name(if valid). - :vartype user_principal_name_properties_reviewed_by_user_principal_name: str - :param type_properties_target_type: The type of decision target : - User/ServicePrincipal.Constant filled by server. Possible values include: "user", - "servicePrincipal". - :type type_properties_target_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'recommendation': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'apply_result': {'readonly': True}, - 'applied_date_time': {'readonly': True}, - 'principal_id_properties_applied_by_principal_id': {'readonly': True}, - 'principal_type_properties_applied_by_principal_type': {'readonly': True}, - 'principal_name_properties_applied_by_principal_name': {'readonly': True}, - 'user_principal_name_properties_applied_by_user_principal_name': {'readonly': True}, - 'principal_id_properties_reviewed_by_principal_id': {'readonly': True}, - 'principal_type_properties_reviewed_by_principal_type': {'readonly': True}, - 'principal_name_properties_reviewed_by_principal_name': {'readonly': True}, - 'user_principal_name_properties_reviewed_by_user_principal_name': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'recommendation': {'key': 'properties.recommendation', 'type': 'str'}, - 'decision': {'key': 'properties.decision', 'type': 'str'}, - 'justification': {'key': 'properties.justification', 'type': 'str'}, - 'reviewed_date_time': {'key': 'properties.reviewedDateTime', 'type': 'iso-8601'}, - 'apply_result': {'key': 'properties.applyResult', 'type': 'str'}, - 'applied_date_time': {'key': 'properties.appliedDateTime', 'type': 'iso-8601'}, - 'principal_id_properties_applied_by_principal_id': {'key': 'properties.appliedBy.principalId', 'type': 'str'}, - 'principal_type_properties_applied_by_principal_type': {'key': 'properties.appliedBy.principalType', 'type': 'str'}, - 'principal_name_properties_applied_by_principal_name': {'key': 'properties.appliedBy.principalName', 'type': 'str'}, - 'user_principal_name_properties_applied_by_user_principal_name': {'key': 'properties.appliedBy.userPrincipalName', 'type': 'str'}, - 'principal_id_properties_reviewed_by_principal_id': {'key': 'properties.reviewedBy.principalId', 'type': 'str'}, - 'principal_type_properties_reviewed_by_principal_type': {'key': 'properties.reviewedBy.principalType', 'type': 'str'}, - 'principal_name_properties_reviewed_by_principal_name': {'key': 'properties.reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name_properties_reviewed_by_user_principal_name': {'key': 'properties.reviewedBy.userPrincipalName', 'type': 'str'}, - 'type_properties_target_type': {'key': 'properties.target.type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDecision, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.recommendation = None - self.decision = kwargs.get('decision', None) - self.justification = kwargs.get('justification', None) - self.reviewed_date_time = None - self.apply_result = None - self.applied_date_time = None - self.principal_id_properties_applied_by_principal_id = None - self.principal_type_properties_applied_by_principal_type = None - self.principal_name_properties_applied_by_principal_name = None - self.user_principal_name_properties_applied_by_user_principal_name = None - self.principal_id_properties_reviewed_by_principal_id = None - self.principal_type_properties_reviewed_by_principal_type = None - self.principal_name_properties_reviewed_by_principal_name = None - self.user_principal_name_properties_reviewed_by_user_principal_name = None - self.type_properties_target_type = None # type: Optional[str] - - -class AccessReviewDecisionListResult(msrest.serialization.Model): - """List of access review decisions. - - :param value: Access Review Decision list. - :type value: list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewDecision]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class AccessReviewDecisionProperties(msrest.serialization.Model): - """Approval Step. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar recommendation: The feature- generated recommendation shown to the reviewer. Possible - values include: "Approve", "Deny", "NoInfoAvailable". - :vartype recommendation: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessRecommendationType - :param decision: The decision on the approval step. This value is initially set to NotReviewed. - Approvers can take action of Approve/Deny. Possible values include: "Approve", "Deny", - "NotReviewed", "DontKnow", "NotNotified". - :type decision: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str - :ivar reviewed_date_time: Date Time when a decision was taken. - :vartype reviewed_date_time: ~datetime.datetime - :ivar apply_result: The outcome of applying the decision. Possible values include: "New", - "Applying", "AppliedSuccessfully", "AppliedWithUnknownFailure", - "AppliedSuccessfullyButObjectNotFound", "ApplyNotSupported". - :vartype apply_result: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewApplyResult - :ivar applied_date_time: The date and time when the review decision was applied. - :vartype applied_date_time: ~datetime.datetime - :ivar principal_id_applied_by_principal_id: The identity id. - :vartype principal_id_applied_by_principal_id: str - :ivar principal_type_applied_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". - :vartype principal_type_applied_by_principal_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name_applied_by_principal_name: The identity display name. - :vartype principal_name_applied_by_principal_name: str - :ivar user_principal_name_applied_by_user_principal_name: The user principal name(if valid). - :vartype user_principal_name_applied_by_user_principal_name: str - :ivar principal_id_reviewed_by_principal_id: The identity id. - :vartype principal_id_reviewed_by_principal_id: str - :ivar principal_type_reviewed_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". - :vartype principal_type_reviewed_by_principal_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name_reviewed_by_principal_name: The identity display name. - :vartype principal_name_reviewed_by_principal_name: str - :ivar user_principal_name_reviewed_by_user_principal_name: The user principal name(if valid). - :vartype user_principal_name_reviewed_by_user_principal_name: str - :param type: The type of decision target : User/ServicePrincipal.Constant filled by server. - Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType - """ - - _validation = { - 'recommendation': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'apply_result': {'readonly': True}, - 'applied_date_time': {'readonly': True}, - 'principal_id_applied_by_principal_id': {'readonly': True}, - 'principal_type_applied_by_principal_type': {'readonly': True}, - 'principal_name_applied_by_principal_name': {'readonly': True}, - 'user_principal_name_applied_by_user_principal_name': {'readonly': True}, - 'principal_id_reviewed_by_principal_id': {'readonly': True}, - 'principal_type_reviewed_by_principal_type': {'readonly': True}, - 'principal_name_reviewed_by_principal_name': {'readonly': True}, - 'user_principal_name_reviewed_by_user_principal_name': {'readonly': True}, - } - - _attribute_map = { - 'recommendation': {'key': 'recommendation', 'type': 'str'}, - 'decision': {'key': 'decision', 'type': 'str'}, - 'justification': {'key': 'justification', 'type': 'str'}, - 'reviewed_date_time': {'key': 'reviewedDateTime', 'type': 'iso-8601'}, - 'apply_result': {'key': 'applyResult', 'type': 'str'}, - 'applied_date_time': {'key': 'appliedDateTime', 'type': 'iso-8601'}, - 'principal_id_applied_by_principal_id': {'key': 'appliedBy.principalId', 'type': 'str'}, - 'principal_type_applied_by_principal_type': {'key': 'appliedBy.principalType', 'type': 'str'}, - 'principal_name_applied_by_principal_name': {'key': 'appliedBy.principalName', 'type': 'str'}, - 'user_principal_name_applied_by_user_principal_name': {'key': 'appliedBy.userPrincipalName', 'type': 'str'}, - 'principal_id_reviewed_by_principal_id': {'key': 'reviewedBy.principalId', 'type': 'str'}, - 'principal_type_reviewed_by_principal_type': {'key': 'reviewedBy.principalType', 'type': 'str'}, - 'principal_name_reviewed_by_principal_name': {'key': 'reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name_reviewed_by_user_principal_name': {'key': 'reviewedBy.userPrincipalName', 'type': 'str'}, - 'type': {'key': 'target.type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionProperties, self).__init__(**kwargs) - self.recommendation = None - self.decision = kwargs.get('decision', None) - self.justification = kwargs.get('justification', None) - self.reviewed_date_time = None - self.apply_result = None - self.applied_date_time = None - self.principal_id_applied_by_principal_id = None - self.principal_type_applied_by_principal_type = None - self.principal_name_applied_by_principal_name = None - self.user_principal_name_applied_by_user_principal_name = None - self.principal_id_reviewed_by_principal_id = None - self.principal_type_reviewed_by_principal_type = None - self.principal_name_reviewed_by_principal_name = None - self.user_principal_name_reviewed_by_user_principal_name = None - self.type = None # type: Optional[str] - - -class AccessReviewDecisionTarget(msrest.serialization.Model): - """Target of the decision. - - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: ServicePrincipalDecisionTarget, UserDecisionTarget. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType - """ - - _validation = { - 'type': {'required': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - } - - _subtype_map = { - 'type': {'servicePrincipal': 'ServicePrincipalDecisionTarget', 'user': 'UserDecisionTarget'} - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionTarget, self).__init__(**kwargs) - self.type = None # type: Optional[str] - - -class AccessReviewDefaultSettings(msrest.serialization.Model): - """Access Review Default Settings. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The access review default settings id. This is only going to be default. - :vartype id: str - :ivar name: The access review default settings name. This is always going to be Access Review - Default Settings. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the - review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to - reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a - justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to - pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to - automatically change the target object access resource, is enabled. If not enabled, a user - must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_properties_recurrence_range_type: The recurrence range type. The possible values - are: endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_properties_recurrence_range_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date - in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. - Possible values include: "weekly", "absoluteMonthly". - :type type_properties_recurrence_pattern_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'mail_notifications_enabled': {'key': 'properties.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'properties.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'properties.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'properties.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'properties.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'properties.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'properties.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'properties.instanceDurationInDays', 'type': 'int'}, - 'type_properties_recurrence_range_type': {'key': 'properties.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'properties.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'properties.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_properties_recurrence_pattern_type': {'key': 'properties.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'properties.recurrence.pattern.interval', 'type': 'int'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDefaultSettings, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.mail_notifications_enabled = kwargs.get('mail_notifications_enabled', None) - self.reminder_notifications_enabled = kwargs.get('reminder_notifications_enabled', None) - self.default_decision_enabled = kwargs.get('default_decision_enabled', None) - self.justification_required_on_approval = kwargs.get('justification_required_on_approval', None) - self.default_decision = kwargs.get('default_decision', None) - self.auto_apply_decisions_enabled = kwargs.get('auto_apply_decisions_enabled', None) - self.recommendations_enabled = kwargs.get('recommendations_enabled', None) - self.instance_duration_in_days = kwargs.get('instance_duration_in_days', None) - self.type_properties_recurrence_range_type = kwargs.get('type_properties_recurrence_range_type', None) - self.number_of_occurrences = kwargs.get('number_of_occurrences', None) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.type_properties_recurrence_pattern_type = kwargs.get('type_properties_recurrence_pattern_type', None) - self.interval = kwargs.get('interval', None) - - -class AccessReviewInstance(msrest.serialization.Model): - """Access Review Instance. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The access review instance id. - :vartype id: str - :ivar name: The access review instance name. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - :ivar status: This read-only field specifies the status of an access review instance. Possible - values include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". - :vartype status: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstanceStatus - :param start_date_time: The DateTime when the review instance is scheduled to be start. - :type start_date_time: ~datetime.datetime - :param end_date_time: The DateTime when the review instance is scheduled to end. - :type end_date_time: ~datetime.datetime - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'status': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewInstance, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.status = None - self.start_date_time = kwargs.get('start_date_time', None) - self.end_date_time = kwargs.get('end_date_time', None) - - -class AccessReviewInstanceListResult(msrest.serialization.Model): - """List of Access Review Instances. - - :param value: Access Review Instance list. - :type value: list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewInstance]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewInstanceListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class AccessReviewReviewer(msrest.serialization.Model): - """Descriptor for what needs to be reviewed. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param principal_id: The id of the reviewer(user/servicePrincipal). - :type principal_id: str - :ivar principal_type: The identity type : user/servicePrincipal. Possible values include: - "user", "servicePrincipal". - :vartype principal_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewReviewerType - """ - - _validation = { - 'principal_type': {'readonly': True}, - } - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'principal_type': {'key': 'principalType', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewReviewer, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - self.principal_type = None - - -class AccessReviewScheduleDefinition(msrest.serialization.Model): - """Access Review Schedule Definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The access review schedule definition id. - :vartype id: str - :ivar name: The access review schedule definition unique id. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - :param display_name: The display name for the schedule definition. - :type display_name: str - :ivar status: This read-only field specifies the status of an accessReview. Possible values - include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". - :vartype status: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionStatus - :param description_for_admins: The description provided by the access review creator and - visible to admins. - :type description_for_admins: str - :param description_for_reviewers: The description provided by the access review creator to be - shown to reviewers. - :type description_for_reviewers: str - :param reviewers: This is the collection of reviewers. - :type reviewers: - list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewReviewer] - :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a - review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be - assigned and instead be chosen dynamically. For example managers review or self review. - Possible values include: "Assigned", "Self", "Managers". - :vartype reviewers_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionReviewersType - :param instances: This is the collection of instances returned when one does an expand on it. - :type instances: - list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] - :ivar resource_id: ResourceId in which this review is getting created. - :vartype resource_id: str - :ivar role_definition_id: This is used to indicate the role being reviewed. - :vartype role_definition_id: str - :ivar principal_type_properties_scope_principal_type: The identity type user/servicePrincipal - to review. Possible values include: "user", "servicePrincipal". - :vartype principal_type_properties_scope_principal_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScopePrincipalType - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the - review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to - reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a - justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to - pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to - automatically change the target object access resource, is enabled. If not enabled, a user - must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_properties_settings_recurrence_range_type: The recurrence range type. The possible - values are: endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_properties_settings_recurrence_range_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date - in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, - etc. Possible values include: "weekly", "absoluteMonthly". - :type type_properties_settings_recurrence_pattern_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int - :ivar principal_id: The identity id. - :vartype principal_id: str - :ivar principal_type_properties_created_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". - :vartype principal_type_properties_created_by_principal_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name: The identity display name. - :vartype principal_name: str - :ivar user_principal_name: The user principal name(if valid). - :vartype user_principal_name: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'status': {'readonly': True}, - 'reviewers_type': {'readonly': True}, - 'resource_id': {'readonly': True}, - 'role_definition_id': {'readonly': True}, - 'principal_type_properties_scope_principal_type': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type_properties_created_by_principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'description_for_admins': {'key': 'properties.descriptionForAdmins', 'type': 'str'}, - 'description_for_reviewers': {'key': 'properties.descriptionForReviewers', 'type': 'str'}, - 'reviewers': {'key': 'properties.reviewers', 'type': '[AccessReviewReviewer]'}, - 'reviewers_type': {'key': 'properties.reviewersType', 'type': 'str'}, - 'instances': {'key': 'properties.instances', 'type': '[AccessReviewInstance]'}, - 'resource_id': {'key': 'properties.scope.resourceId', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.scope.roleDefinitionId', 'type': 'str'}, - 'principal_type_properties_scope_principal_type': {'key': 'properties.scope.principalType', 'type': 'str'}, - 'mail_notifications_enabled': {'key': 'properties.settings.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'properties.settings.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'properties.settings.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'properties.settings.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'properties.settings.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'properties.settings.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'properties.settings.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'properties.settings.instanceDurationInDays', 'type': 'int'}, - 'type_properties_settings_recurrence_range_type': {'key': 'properties.settings.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'properties.settings.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'properties.settings.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.settings.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_properties_settings_recurrence_pattern_type': {'key': 'properties.settings.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'properties.settings.recurrence.pattern.interval', 'type': 'int'}, - 'principal_id': {'key': 'properties.createdBy.principalId', 'type': 'str'}, - 'principal_type_properties_created_by_principal_type': {'key': 'properties.createdBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'properties.createdBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'properties.createdBy.userPrincipalName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewScheduleDefinition, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.display_name = kwargs.get('display_name', None) - self.status = None - self.description_for_admins = kwargs.get('description_for_admins', None) - self.description_for_reviewers = kwargs.get('description_for_reviewers', None) - self.reviewers = kwargs.get('reviewers', None) - self.reviewers_type = None - self.instances = kwargs.get('instances', None) - self.resource_id = None - self.role_definition_id = None - self.principal_type_properties_scope_principal_type = None - self.mail_notifications_enabled = kwargs.get('mail_notifications_enabled', None) - self.reminder_notifications_enabled = kwargs.get('reminder_notifications_enabled', None) - self.default_decision_enabled = kwargs.get('default_decision_enabled', None) - self.justification_required_on_approval = kwargs.get('justification_required_on_approval', None) - self.default_decision = kwargs.get('default_decision', None) - self.auto_apply_decisions_enabled = kwargs.get('auto_apply_decisions_enabled', None) - self.recommendations_enabled = kwargs.get('recommendations_enabled', None) - self.instance_duration_in_days = kwargs.get('instance_duration_in_days', None) - self.type_properties_settings_recurrence_range_type = kwargs.get('type_properties_settings_recurrence_range_type', None) - self.number_of_occurrences = kwargs.get('number_of_occurrences', None) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.type_properties_settings_recurrence_pattern_type = kwargs.get('type_properties_settings_recurrence_pattern_type', None) - self.interval = kwargs.get('interval', None) - self.principal_id = None - self.principal_type_properties_created_by_principal_type = None - self.principal_name = None - self.user_principal_name = None - - -class AccessReviewScheduleDefinitionListResult(msrest.serialization.Model): - """List of Access Review Schedule Definitions. - - :param value: Access Review Schedule Definition list. - :type value: - list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewScheduleDefinition]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewScheduleDefinitionListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class AccessReviewScheduleDefinitionProperties(msrest.serialization.Model): - """Access Review. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param display_name: The display name for the schedule definition. - :type display_name: str - :ivar status: This read-only field specifies the status of an accessReview. Possible values - include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". - :vartype status: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionStatus - :param description_for_admins: The description provided by the access review creator and - visible to admins. - :type description_for_admins: str - :param description_for_reviewers: The description provided by the access review creator to be - shown to reviewers. - :type description_for_reviewers: str - :param reviewers: This is the collection of reviewers. - :type reviewers: - list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewReviewer] - :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a - review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be - assigned and instead be chosen dynamically. For example managers review or self review. - Possible values include: "Assigned", "Self", "Managers". - :vartype reviewers_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionReviewersType - :param instances: This is the collection of instances returned when one does an expand on it. - :type instances: - list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] - :ivar resource_id: ResourceId in which this review is getting created. - :vartype resource_id: str - :ivar role_definition_id: This is used to indicate the role being reviewed. - :vartype role_definition_id: str - :ivar principal_type_scope_principal_type: The identity type user/servicePrincipal to review. - Possible values include: "user", "servicePrincipal". - :vartype principal_type_scope_principal_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScopePrincipalType - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the - review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to - reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a - justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to - pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to - automatically change the target object access resource, is enabled. If not enabled, a user - must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_settings_recurrence_range_type: The recurrence range type. The possible values are: - endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_settings_recurrence_range_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date - in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. - Possible values include: "weekly", "absoluteMonthly". - :type type_settings_recurrence_pattern_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int - :ivar principal_id: The identity id. - :vartype principal_id: str - :ivar principal_type_created_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". - :vartype principal_type_created_by_principal_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name: The identity display name. - :vartype principal_name: str - :ivar user_principal_name: The user principal name(if valid). - :vartype user_principal_name: str - """ - - _validation = { - 'status': {'readonly': True}, - 'reviewers_type': {'readonly': True}, - 'resource_id': {'readonly': True}, - 'role_definition_id': {'readonly': True}, - 'principal_type_scope_principal_type': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type_created_by_principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, - } - - _attribute_map = { - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'description_for_admins': {'key': 'descriptionForAdmins', 'type': 'str'}, - 'description_for_reviewers': {'key': 'descriptionForReviewers', 'type': 'str'}, - 'reviewers': {'key': 'reviewers', 'type': '[AccessReviewReviewer]'}, - 'reviewers_type': {'key': 'reviewersType', 'type': 'str'}, - 'instances': {'key': 'instances', 'type': '[AccessReviewInstance]'}, - 'resource_id': {'key': 'scope.resourceId', 'type': 'str'}, - 'role_definition_id': {'key': 'scope.roleDefinitionId', 'type': 'str'}, - 'principal_type_scope_principal_type': {'key': 'scope.principalType', 'type': 'str'}, - 'mail_notifications_enabled': {'key': 'settings.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'settings.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'settings.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'settings.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'settings.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'settings.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'settings.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'settings.instanceDurationInDays', 'type': 'int'}, - 'type_settings_recurrence_range_type': {'key': 'settings.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'settings.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'settings.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'settings.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_settings_recurrence_pattern_type': {'key': 'settings.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'settings.recurrence.pattern.interval', 'type': 'int'}, - 'principal_id': {'key': 'createdBy.principalId', 'type': 'str'}, - 'principal_type_created_by_principal_type': {'key': 'createdBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'createdBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'createdBy.userPrincipalName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewScheduleDefinitionProperties, self).__init__(**kwargs) - self.display_name = kwargs.get('display_name', None) - self.status = None - self.description_for_admins = kwargs.get('description_for_admins', None) - self.description_for_reviewers = kwargs.get('description_for_reviewers', None) - self.reviewers = kwargs.get('reviewers', None) - self.reviewers_type = None - self.instances = kwargs.get('instances', None) - self.resource_id = None - self.role_definition_id = None - self.principal_type_scope_principal_type = None - self.mail_notifications_enabled = kwargs.get('mail_notifications_enabled', None) - self.reminder_notifications_enabled = kwargs.get('reminder_notifications_enabled', None) - self.default_decision_enabled = kwargs.get('default_decision_enabled', None) - self.justification_required_on_approval = kwargs.get('justification_required_on_approval', None) - self.default_decision = kwargs.get('default_decision', None) - self.auto_apply_decisions_enabled = kwargs.get('auto_apply_decisions_enabled', None) - self.recommendations_enabled = kwargs.get('recommendations_enabled', None) - self.instance_duration_in_days = kwargs.get('instance_duration_in_days', None) - self.type_settings_recurrence_range_type = kwargs.get('type_settings_recurrence_range_type', None) - self.number_of_occurrences = kwargs.get('number_of_occurrences', None) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.type_settings_recurrence_pattern_type = kwargs.get('type_settings_recurrence_pattern_type', None) - self.interval = kwargs.get('interval', None) - self.principal_id = None - self.principal_type_created_by_principal_type = None - self.principal_name = None - self.user_principal_name = None - - -class AccessReviewScheduleSettings(msrest.serialization.Model): - """Settings of an Access Review. - - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the - review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to - reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a - justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to - pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to - automatically change the target object access resource, is enabled. If not enabled, a user - must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_recurrence_range_type: The recurrence range type. The possible values are: endDate, - noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_recurrence_range_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date - in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Possible - values include: "weekly", "absoluteMonthly". - :type type_recurrence_pattern_type: str or - ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int - """ - - _attribute_map = { - 'mail_notifications_enabled': {'key': 'mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'instanceDurationInDays', 'type': 'int'}, - 'type_recurrence_range_type': {'key': 'recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_recurrence_pattern_type': {'key': 'recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'recurrence.pattern.interval', 'type': 'int'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewScheduleSettings, self).__init__(**kwargs) - self.mail_notifications_enabled = kwargs.get('mail_notifications_enabled', None) - self.reminder_notifications_enabled = kwargs.get('reminder_notifications_enabled', None) - self.default_decision_enabled = kwargs.get('default_decision_enabled', None) - self.justification_required_on_approval = kwargs.get('justification_required_on_approval', None) - self.default_decision = kwargs.get('default_decision', None) - self.auto_apply_decisions_enabled = kwargs.get('auto_apply_decisions_enabled', None) - self.recommendations_enabled = kwargs.get('recommendations_enabled', None) - self.instance_duration_in_days = kwargs.get('instance_duration_in_days', None) - self.type_recurrence_range_type = kwargs.get('type_recurrence_range_type', None) - self.number_of_occurrences = kwargs.get('number_of_occurrences', None) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.type_recurrence_pattern_type = kwargs.get('type_recurrence_pattern_type', None) - self.interval = kwargs.get('interval', None) - - -class ErrorDefinition(msrest.serialization.Model): - """Error description and code explaining why an operation failed. - - :param error: Error of the list gateway status. - :type error: ~azure.mgmt.authorization.v2018_05_01_preview.models.ErrorDefinitionProperties - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinitionProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDefinition, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ErrorDefinitionProperties(msrest.serialization.Model): - """Error description and code explaining why an operation failed. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar message: Description of the error. - :vartype message: str - :param code: Error code of list gateway. - :type code: str - """ - - _validation = { - 'message': {'readonly': True}, - } - - _attribute_map = { - 'message': {'key': 'message', 'type': 'str'}, - 'code': {'key': 'code', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDefinitionProperties, self).__init__(**kwargs) - self.message = None - self.code = kwargs.get('code', None) - - -class Operation(msrest.serialization.Model): - """The definition of a Microsoft.Authorization operation. - - :param name: Name of the operation. - :type name: str - :param is_data_action: Indicates whether the operation is a data action. - :type is_data_action: bool - :param display: Display of the operation. - :type display: ~azure.mgmt.authorization.v2018_05_01_preview.models.OperationDisplay - :param origin: Origin of the operation. - :type origin: str - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'origin': {'key': 'origin', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Operation, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.is_data_action = kwargs.get('is_data_action', None) - self.display = kwargs.get('display', None) - self.origin = kwargs.get('origin', None) - - -class OperationDisplay(msrest.serialization.Model): - """The display information for a Microsoft.Authorization operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provider: The resource provider name: Microsoft.Authorization. - :vartype provider: str - :ivar resource: The resource on which the operation is performed. - :vartype resource: str - :ivar operation: The operation that users can perform. - :vartype operation: str - :ivar description: The description for the operation. - :vartype description: str - """ - - _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, - } - - _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None - self.description = None - - -class OperationListResult(msrest.serialization.Model): - """The result of a request to list Microsoft.Authorization operations. - - :param value: The collection value. - :type value: list[~azure.mgmt.authorization.v2018_05_01_preview.models.Operation] - :param next_link: The URI that can be used to request the next set of paged results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class ServicePrincipalDecisionTarget(AccessReviewDecisionTarget): - """Service Principal Decision Target. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType - :ivar principal_id: The id of service principal whose access is reviewed. - :vartype principal_id: str - :ivar principal_name: The display name of the service principal whose access was reviewed. - :vartype principal_name: str - :ivar app_id: The appId for the service principal entity being reviewed. - :vartype app_id: str - """ - - _validation = { - 'type': {'required': True}, - 'principal_id': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'app_id': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'principal_name': {'key': 'principalName', 'type': 'str'}, - 'app_id': {'key': 'appId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ServicePrincipalDecisionTarget, self).__init__(**kwargs) - self.type = 'servicePrincipal' # type: str - self.principal_id = None - self.principal_name = None - self.app_id = None - - -class UserDecisionTarget(AccessReviewDecisionTarget): - """User Decision Target. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType - :ivar principal_id: The id of user whose access was reviewed. - :vartype principal_id: str - :ivar principal_name: The display name of the user whose access was reviewed. - :vartype principal_name: str - :ivar user_principal_name: The user principal name of the user whose access was reviewed. - :vartype user_principal_name: str - """ - - _validation = { - 'type': {'required': True}, - 'principal_id': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'principal_name': {'key': 'principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'userPrincipalName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(UserDecisionTarget, self).__init__(**kwargs) - self.type = 'user' # type: str - self.principal_id = None - self.principal_name = None - self.user_principal_name = None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_models_py3.py index e833c4d6e9e..35479109a8a 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_models_py3.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,15 +8,16 @@ # -------------------------------------------------------------------------- import datetime -from typing import List, Optional, Union +from typing import List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization -from ._authorization_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class AccessReviewDecision(msrest.serialization.Model): +class AccessReviewDecision(_serialization.Model): # pylint: disable=too-many-instance-attributes """Access Review. Variables are only populated by the server, and will be ignored when sending a request. @@ -26,21 +28,22 @@ class AccessReviewDecision(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :ivar recommendation: The feature- generated recommendation shown to the reviewer. Possible - values include: "Approve", "Deny", "NoInfoAvailable". + :ivar recommendation: The feature- generated recommendation shown to the reviewer. Known values + are: "Approve", "Deny", and "NoInfoAvailable". :vartype recommendation: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessRecommendationType - :param decision: The decision on the approval step. This value is initially set to NotReviewed. - Approvers can take action of Approve/Deny. Possible values include: "Approve", "Deny", - "NotReviewed", "DontKnow", "NotNotified". - :type decision: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str + :ivar decision: The decision on the approval step. This value is initially set to NotReviewed. + Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", "NotReviewed", + "DontKnow", and "NotNotified". + :vartype decision: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewResult + :ivar justification: Justification provided by approvers for their action. + :vartype justification: str :ivar reviewed_date_time: Date Time when a decision was taken. :vartype reviewed_date_time: ~datetime.datetime - :ivar apply_result: The outcome of applying the decision. Possible values include: "New", - "Applying", "AppliedSuccessfully", "AppliedWithUnknownFailure", - "AppliedSuccessfullyButObjectNotFound", "ApplyNotSupported". + :ivar apply_result: The outcome of applying the decision. Known values are: "New", "Applying", + "AppliedSuccessfully", "AppliedWithUnknownFailure", "AppliedSuccessfullyButObjectNotFound", and + "ApplyNotSupported". :vartype apply_result: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewApplyResult :ivar applied_date_time: The date and time when the review decision was applied. @@ -48,7 +51,7 @@ class AccessReviewDecision(msrest.serialization.Model): :ivar principal_id_properties_applied_by_principal_id: The identity id. :vartype principal_id_properties_applied_by_principal_id: str :ivar principal_type_properties_applied_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". + user/servicePrincipal. Known values are: "user" and "servicePrincipal". :vartype principal_type_properties_applied_by_principal_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType :ivar principal_name_properties_applied_by_principal_name: The identity display name. @@ -59,7 +62,7 @@ class AccessReviewDecision(msrest.serialization.Model): :ivar principal_id_properties_reviewed_by_principal_id: The identity id. :vartype principal_id_properties_reviewed_by_principal_id: str :ivar principal_type_properties_reviewed_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". + user/servicePrincipal. Known values are: "user" and "servicePrincipal". :vartype principal_type_properties_reviewed_by_principal_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType :ivar principal_name_properties_reviewed_by_principal_name: The identity display name. @@ -67,60 +70,86 @@ class AccessReviewDecision(msrest.serialization.Model): :ivar user_principal_name_properties_reviewed_by_user_principal_name: The user principal name(if valid). :vartype user_principal_name_properties_reviewed_by_user_principal_name: str - :param type_properties_target_type: The type of decision target : - User/ServicePrincipal.Constant filled by server. Possible values include: "user", - "servicePrincipal". - :type type_properties_target_type: str or + :ivar type_properties_target_type: The type of decision target : User/ServicePrincipal. Known + values are: "user" and "servicePrincipal". + :vartype type_properties_target_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'recommendation': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'apply_result': {'readonly': True}, - 'applied_date_time': {'readonly': True}, - 'principal_id_properties_applied_by_principal_id': {'readonly': True}, - 'principal_type_properties_applied_by_principal_type': {'readonly': True}, - 'principal_name_properties_applied_by_principal_name': {'readonly': True}, - 'user_principal_name_properties_applied_by_user_principal_name': {'readonly': True}, - 'principal_id_properties_reviewed_by_principal_id': {'readonly': True}, - 'principal_type_properties_reviewed_by_principal_type': {'readonly': True}, - 'principal_name_properties_reviewed_by_principal_name': {'readonly': True}, - 'user_principal_name_properties_reviewed_by_user_principal_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "recommendation": {"readonly": True}, + "reviewed_date_time": {"readonly": True}, + "apply_result": {"readonly": True}, + "applied_date_time": {"readonly": True}, + "principal_id_properties_applied_by_principal_id": {"readonly": True}, + "principal_type_properties_applied_by_principal_type": {"readonly": True}, + "principal_name_properties_applied_by_principal_name": {"readonly": True}, + "user_principal_name_properties_applied_by_user_principal_name": {"readonly": True}, + "principal_id_properties_reviewed_by_principal_id": {"readonly": True}, + "principal_type_properties_reviewed_by_principal_type": {"readonly": True}, + "principal_name_properties_reviewed_by_principal_name": {"readonly": True}, + "user_principal_name_properties_reviewed_by_user_principal_name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'recommendation': {'key': 'properties.recommendation', 'type': 'str'}, - 'decision': {'key': 'properties.decision', 'type': 'str'}, - 'justification': {'key': 'properties.justification', 'type': 'str'}, - 'reviewed_date_time': {'key': 'properties.reviewedDateTime', 'type': 'iso-8601'}, - 'apply_result': {'key': 'properties.applyResult', 'type': 'str'}, - 'applied_date_time': {'key': 'properties.appliedDateTime', 'type': 'iso-8601'}, - 'principal_id_properties_applied_by_principal_id': {'key': 'properties.appliedBy.principalId', 'type': 'str'}, - 'principal_type_properties_applied_by_principal_type': {'key': 'properties.appliedBy.principalType', 'type': 'str'}, - 'principal_name_properties_applied_by_principal_name': {'key': 'properties.appliedBy.principalName', 'type': 'str'}, - 'user_principal_name_properties_applied_by_user_principal_name': {'key': 'properties.appliedBy.userPrincipalName', 'type': 'str'}, - 'principal_id_properties_reviewed_by_principal_id': {'key': 'properties.reviewedBy.principalId', 'type': 'str'}, - 'principal_type_properties_reviewed_by_principal_type': {'key': 'properties.reviewedBy.principalType', 'type': 'str'}, - 'principal_name_properties_reviewed_by_principal_name': {'key': 'properties.reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name_properties_reviewed_by_user_principal_name': {'key': 'properties.reviewedBy.userPrincipalName', 'type': 'str'}, - 'type_properties_target_type': {'key': 'properties.target.type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "recommendation": {"key": "properties.recommendation", "type": "str"}, + "decision": {"key": "properties.decision", "type": "str"}, + "justification": {"key": "properties.justification", "type": "str"}, + "reviewed_date_time": {"key": "properties.reviewedDateTime", "type": "iso-8601"}, + "apply_result": {"key": "properties.applyResult", "type": "str"}, + "applied_date_time": {"key": "properties.appliedDateTime", "type": "iso-8601"}, + "principal_id_properties_applied_by_principal_id": {"key": "properties.appliedBy.principalId", "type": "str"}, + "principal_type_properties_applied_by_principal_type": { + "key": "properties.appliedBy.principalType", + "type": "str", + }, + "principal_name_properties_applied_by_principal_name": { + "key": "properties.appliedBy.principalName", + "type": "str", + }, + "user_principal_name_properties_applied_by_user_principal_name": { + "key": "properties.appliedBy.userPrincipalName", + "type": "str", + }, + "principal_id_properties_reviewed_by_principal_id": {"key": "properties.reviewedBy.principalId", "type": "str"}, + "principal_type_properties_reviewed_by_principal_type": { + "key": "properties.reviewedBy.principalType", + "type": "str", + }, + "principal_name_properties_reviewed_by_principal_name": { + "key": "properties.reviewedBy.principalName", + "type": "str", + }, + "user_principal_name_properties_reviewed_by_user_principal_name": { + "key": "properties.reviewedBy.userPrincipalName", + "type": "str", + }, + "type_properties_target_type": {"key": "properties.target.type", "type": "str"}, } def __init__( self, *, - decision: Optional[Union[str, "AccessReviewResult"]] = None, + decision: Optional[Union[str, "_models.AccessReviewResult"]] = None, justification: Optional[str] = None, **kwargs ): - super(AccessReviewDecision, self).__init__(**kwargs) + """ + :keyword decision: The decision on the approval step. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + "NotReviewed", "DontKnow", and "NotNotified". + :paramtype decision: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewResult + :keyword justification: Justification provided by approvers for their action. + :paramtype justification: str + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -141,52 +170,56 @@ def __init__( self.type_properties_target_type = None # type: Optional[str] -class AccessReviewDecisionListResult(msrest.serialization.Model): +class AccessReviewDecisionListResult(_serialization.Model): """List of access review decisions. - :param value: Access Review Decision list. - :type value: list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Access Review Decision list. + :vartype value: list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewDecision]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[AccessReviewDecision]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["AccessReviewDecision"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.AccessReviewDecision"]] = None, next_link: Optional[str] = None, **kwargs ): - super(AccessReviewDecisionListResult, self).__init__(**kwargs) + """ + :keyword value: Access Review Decision list. + :paramtype value: + list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class AccessReviewDecisionProperties(msrest.serialization.Model): +class AccessReviewDecisionProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes """Approval Step. Variables are only populated by the server, and will be ignored when sending a request. - :ivar recommendation: The feature- generated recommendation shown to the reviewer. Possible - values include: "Approve", "Deny", "NoInfoAvailable". + :ivar recommendation: The feature- generated recommendation shown to the reviewer. Known values + are: "Approve", "Deny", and "NoInfoAvailable". :vartype recommendation: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessRecommendationType - :param decision: The decision on the approval step. This value is initially set to NotReviewed. - Approvers can take action of Approve/Deny. Possible values include: "Approve", "Deny", - "NotReviewed", "DontKnow", "NotNotified". - :type decision: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str + :ivar decision: The decision on the approval step. This value is initially set to NotReviewed. + Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", "NotReviewed", + "DontKnow", and "NotNotified". + :vartype decision: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewResult + :ivar justification: Justification provided by approvers for their action. + :vartype justification: str :ivar reviewed_date_time: Date Time when a decision was taken. :vartype reviewed_date_time: ~datetime.datetime - :ivar apply_result: The outcome of applying the decision. Possible values include: "New", - "Applying", "AppliedSuccessfully", "AppliedWithUnknownFailure", - "AppliedSuccessfullyButObjectNotFound", "ApplyNotSupported". + :ivar apply_result: The outcome of applying the decision. Known values are: "New", "Applying", + "AppliedSuccessfully", "AppliedWithUnknownFailure", "AppliedSuccessfullyButObjectNotFound", and + "ApplyNotSupported". :vartype apply_result: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewApplyResult :ivar applied_date_time: The date and time when the review decision was applied. @@ -194,7 +227,7 @@ class AccessReviewDecisionProperties(msrest.serialization.Model): :ivar principal_id_applied_by_principal_id: The identity id. :vartype principal_id_applied_by_principal_id: str :ivar principal_type_applied_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". + Known values are: "user" and "servicePrincipal". :vartype principal_type_applied_by_principal_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType :ivar principal_name_applied_by_principal_name: The identity display name. @@ -204,59 +237,68 @@ class AccessReviewDecisionProperties(msrest.serialization.Model): :ivar principal_id_reviewed_by_principal_id: The identity id. :vartype principal_id_reviewed_by_principal_id: str :ivar principal_type_reviewed_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". + Known values are: "user" and "servicePrincipal". :vartype principal_type_reviewed_by_principal_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType :ivar principal_name_reviewed_by_principal_name: The identity display name. :vartype principal_name_reviewed_by_principal_name: str :ivar user_principal_name_reviewed_by_user_principal_name: The user principal name(if valid). :vartype user_principal_name_reviewed_by_user_principal_name: str - :param type: The type of decision target : User/ServicePrincipal.Constant filled by server. - Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType + :ivar type: The type of decision target : User/ServicePrincipal. Known values are: "user" and + "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType """ _validation = { - 'recommendation': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'apply_result': {'readonly': True}, - 'applied_date_time': {'readonly': True}, - 'principal_id_applied_by_principal_id': {'readonly': True}, - 'principal_type_applied_by_principal_type': {'readonly': True}, - 'principal_name_applied_by_principal_name': {'readonly': True}, - 'user_principal_name_applied_by_user_principal_name': {'readonly': True}, - 'principal_id_reviewed_by_principal_id': {'readonly': True}, - 'principal_type_reviewed_by_principal_type': {'readonly': True}, - 'principal_name_reviewed_by_principal_name': {'readonly': True}, - 'user_principal_name_reviewed_by_user_principal_name': {'readonly': True}, + "recommendation": {"readonly": True}, + "reviewed_date_time": {"readonly": True}, + "apply_result": {"readonly": True}, + "applied_date_time": {"readonly": True}, + "principal_id_applied_by_principal_id": {"readonly": True}, + "principal_type_applied_by_principal_type": {"readonly": True}, + "principal_name_applied_by_principal_name": {"readonly": True}, + "user_principal_name_applied_by_user_principal_name": {"readonly": True}, + "principal_id_reviewed_by_principal_id": {"readonly": True}, + "principal_type_reviewed_by_principal_type": {"readonly": True}, + "principal_name_reviewed_by_principal_name": {"readonly": True}, + "user_principal_name_reviewed_by_user_principal_name": {"readonly": True}, } _attribute_map = { - 'recommendation': {'key': 'recommendation', 'type': 'str'}, - 'decision': {'key': 'decision', 'type': 'str'}, - 'justification': {'key': 'justification', 'type': 'str'}, - 'reviewed_date_time': {'key': 'reviewedDateTime', 'type': 'iso-8601'}, - 'apply_result': {'key': 'applyResult', 'type': 'str'}, - 'applied_date_time': {'key': 'appliedDateTime', 'type': 'iso-8601'}, - 'principal_id_applied_by_principal_id': {'key': 'appliedBy.principalId', 'type': 'str'}, - 'principal_type_applied_by_principal_type': {'key': 'appliedBy.principalType', 'type': 'str'}, - 'principal_name_applied_by_principal_name': {'key': 'appliedBy.principalName', 'type': 'str'}, - 'user_principal_name_applied_by_user_principal_name': {'key': 'appliedBy.userPrincipalName', 'type': 'str'}, - 'principal_id_reviewed_by_principal_id': {'key': 'reviewedBy.principalId', 'type': 'str'}, - 'principal_type_reviewed_by_principal_type': {'key': 'reviewedBy.principalType', 'type': 'str'}, - 'principal_name_reviewed_by_principal_name': {'key': 'reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name_reviewed_by_user_principal_name': {'key': 'reviewedBy.userPrincipalName', 'type': 'str'}, - 'type': {'key': 'target.type', 'type': 'str'}, + "recommendation": {"key": "recommendation", "type": "str"}, + "decision": {"key": "decision", "type": "str"}, + "justification": {"key": "justification", "type": "str"}, + "reviewed_date_time": {"key": "reviewedDateTime", "type": "iso-8601"}, + "apply_result": {"key": "applyResult", "type": "str"}, + "applied_date_time": {"key": "appliedDateTime", "type": "iso-8601"}, + "principal_id_applied_by_principal_id": {"key": "appliedBy.principalId", "type": "str"}, + "principal_type_applied_by_principal_type": {"key": "appliedBy.principalType", "type": "str"}, + "principal_name_applied_by_principal_name": {"key": "appliedBy.principalName", "type": "str"}, + "user_principal_name_applied_by_user_principal_name": {"key": "appliedBy.userPrincipalName", "type": "str"}, + "principal_id_reviewed_by_principal_id": {"key": "reviewedBy.principalId", "type": "str"}, + "principal_type_reviewed_by_principal_type": {"key": "reviewedBy.principalType", "type": "str"}, + "principal_name_reviewed_by_principal_name": {"key": "reviewedBy.principalName", "type": "str"}, + "user_principal_name_reviewed_by_user_principal_name": {"key": "reviewedBy.userPrincipalName", "type": "str"}, + "type": {"key": "target.type", "type": "str"}, } def __init__( self, *, - decision: Optional[Union[str, "AccessReviewResult"]] = None, + decision: Optional[Union[str, "_models.AccessReviewResult"]] = None, justification: Optional[str] = None, **kwargs ): - super(AccessReviewDecisionProperties, self).__init__(**kwargs) + """ + :keyword decision: The decision on the approval step. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + "NotReviewed", "DontKnow", and "NotNotified". + :paramtype decision: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewResult + :keyword justification: Justification provided by approvers for their action. + :paramtype justification: str + """ + super().__init__(**kwargs) self.recommendation = None self.decision = decision self.justification = justification @@ -274,40 +316,36 @@ def __init__( self.type = None # type: Optional[str] -class AccessReviewDecisionTarget(msrest.serialization.Model): +class AccessReviewDecisionTarget(_serialization.Model): """Target of the decision. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: ServicePrincipalDecisionTarget, UserDecisionTarget. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + ServicePrincipalDecisionTarget, UserDecisionTarget All required parameters must be populated in order to send to Azure. - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType """ _validation = { - 'type': {'required': True}, + "type": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, } - _subtype_map = { - 'type': {'servicePrincipal': 'ServicePrincipalDecisionTarget', 'user': 'UserDecisionTarget'} - } + _subtype_map = {"type": {"servicePrincipal": "ServicePrincipalDecisionTarget", "user": "UserDecisionTarget"}} - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionTarget, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None # type: Optional[str] -class AccessReviewDefaultSettings(msrest.serialization.Model): +class AccessReviewDefaultSettings(_serialization.Model): # pylint: disable=too-many-instance-attributes """Access Review Default Settings. Variables are only populated by the server, and will be ignored when sending a request. @@ -319,76 +357,76 @@ class AccessReviewDefaultSettings(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to automatically change the target object access resource, is enabled. If not enabled, a user must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_properties_recurrence_range_type: The recurrence range type. The possible values - are: endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_properties_recurrence_range_type: str or + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_properties_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_properties_recurrence_range_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. - Possible values include: "weekly", "absoluteMonthly". - :type type_properties_recurrence_pattern_type: str or + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :vartype type_properties_recurrence_pattern_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'mail_notifications_enabled': {'key': 'properties.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'properties.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'properties.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'properties.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'properties.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'properties.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'properties.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'properties.instanceDurationInDays', 'type': 'int'}, - 'type_properties_recurrence_range_type': {'key': 'properties.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'properties.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'properties.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_properties_recurrence_pattern_type': {'key': 'properties.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'properties.recurrence.pattern.interval', 'type': 'int'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "mail_notifications_enabled": {"key": "properties.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "properties.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "properties.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "properties.justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "properties.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "properties.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "properties.recommendationsEnabled", "type": "bool"}, + "instance_duration_in_days": {"key": "properties.instanceDurationInDays", "type": "int"}, + "type_properties_recurrence_range_type": {"key": "properties.recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "properties.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "properties.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.recurrence.range.endDate", "type": "iso-8601"}, + "type_properties_recurrence_pattern_type": {"key": "properties.recurrence.pattern.type", "type": "str"}, + "interval": {"key": "properties.recurrence.pattern.interval", "type": "int"}, } def __init__( @@ -398,19 +436,68 @@ def __init__( reminder_notifications_enabled: Optional[bool] = None, default_decision_enabled: Optional[bool] = None, justification_required_on_approval: Optional[bool] = None, - default_decision: Optional[Union[str, "DefaultDecisionType"]] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, auto_apply_decisions_enabled: Optional[bool] = None, recommendations_enabled: Optional[bool] = None, instance_duration_in_days: Optional[int] = None, - type_properties_recurrence_range_type: Optional[Union[str, "AccessReviewRecurrenceRangeType"]] = None, + type_properties_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, number_of_occurrences: Optional[int] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, - type_properties_recurrence_pattern_type: Optional[Union[str, "AccessReviewRecurrencePatternType"]] = None, + type_properties_recurrence_pattern_type: Optional[ + Union[str, "_models.AccessReviewRecurrencePatternType"] + ] = None, interval: Optional[int] = None, **kwargs ): - super(AccessReviewDefaultSettings, self).__init__(**kwargs) + """ + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_properties_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_properties_recurrence_range_type: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :paramtype type_properties_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -430,7 +517,7 @@ def __init__( self.interval = interval -class AccessReviewInstance(msrest.serialization.Model): +class AccessReviewInstance(_serialization.Model): """Access Review Instance. Variables are only populated by the server, and will be ignored when sending a request. @@ -441,31 +528,31 @@ class AccessReviewInstance(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :ivar status: This read-only field specifies the status of an access review instance. Possible - values include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". + :ivar status: This read-only field specifies the status of an access review instance. Known + values are: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", + "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". :vartype status: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstanceStatus - :param start_date_time: The DateTime when the review instance is scheduled to be start. - :type start_date_time: ~datetime.datetime - :param end_date_time: The DateTime when the review instance is scheduled to end. - :type end_date_time: ~datetime.datetime + :ivar start_date_time: The DateTime when the review instance is scheduled to be start. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: The DateTime when the review instance is scheduled to end. + :vartype end_date_time: ~datetime.datetime """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'status': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "status": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, } def __init__( @@ -475,7 +562,13 @@ def __init__( end_date_time: Optional[datetime.datetime] = None, **kwargs ): - super(AccessReviewInstance, self).__init__(**kwargs) + """ + :keyword start_date_time: The DateTime when the review instance is scheduled to be start. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: The DateTime when the review instance is scheduled to end. + :paramtype end_date_time: ~datetime.datetime + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -484,66 +577,68 @@ def __init__( self.end_date_time = end_date_time -class AccessReviewInstanceListResult(msrest.serialization.Model): +class AccessReviewInstanceListResult(_serialization.Model): """List of Access Review Instances. - :param value: Access Review Instance list. - :type value: list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Access Review Instance list. + :vartype value: list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewInstance]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[AccessReviewInstance]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["AccessReviewInstance"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.AccessReviewInstance"]] = None, next_link: Optional[str] = None, **kwargs ): - super(AccessReviewInstanceListResult, self).__init__(**kwargs) + """ + :keyword value: Access Review Instance list. + :paramtype value: + list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class AccessReviewReviewer(msrest.serialization.Model): +class AccessReviewReviewer(_serialization.Model): """Descriptor for what needs to be reviewed. Variables are only populated by the server, and will be ignored when sending a request. - :param principal_id: The id of the reviewer(user/servicePrincipal). - :type principal_id: str - :ivar principal_type: The identity type : user/servicePrincipal. Possible values include: - "user", "servicePrincipal". + :ivar principal_id: The id of the reviewer(user/servicePrincipal). + :vartype principal_id: str + :ivar principal_type: The identity type : user/servicePrincipal. Known values are: "user" and + "servicePrincipal". :vartype principal_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewReviewerType """ _validation = { - 'principal_type': {'readonly': True}, + "principal_type": {"readonly": True}, } _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'principal_type': {'key': 'principalType', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "principal_type": {"key": "principalType", "type": "str"}, } - def __init__( - self, - *, - principal_id: Optional[str] = None, - **kwargs - ): - super(AccessReviewReviewer, self).__init__(**kwargs) + def __init__(self, *, principal_id: Optional[str] = None, **kwargs): + """ + :keyword principal_id: The id of the reviewer(user/servicePrincipal). + :paramtype principal_id: str + """ + super().__init__(**kwargs) self.principal_id = principal_id self.principal_type = None -class AccessReviewScheduleDefinition(msrest.serialization.Model): +class AccessReviewScheduleDefinition(_serialization.Model): # pylint: disable=too-many-instance-attributes """Access Review Schedule Definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -554,87 +649,87 @@ class AccessReviewScheduleDefinition(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :param display_name: The display name for the schedule definition. - :type display_name: str - :ivar status: This read-only field specifies the status of an accessReview. Possible values - include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". + :ivar display_name: The display name for the schedule definition. + :vartype display_name: str + :ivar status: This read-only field specifies the status of an accessReview. Known values are: + "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", "Completing", + "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". :vartype status: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionStatus - :param description_for_admins: The description provided by the access review creator and - visible to admins. - :type description_for_admins: str - :param description_for_reviewers: The description provided by the access review creator to be + :ivar description_for_admins: The description provided by the access review creator and visible + to admins. + :vartype description_for_admins: str + :ivar description_for_reviewers: The description provided by the access review creator to be shown to reviewers. - :type description_for_reviewers: str - :param reviewers: This is the collection of reviewers. - :type reviewers: + :vartype description_for_reviewers: str + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewReviewer] :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be - assigned and instead be chosen dynamically. For example managers review or self review. - Possible values include: "Assigned", "Self", "Managers". + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". :vartype reviewers_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionReviewersType - :param instances: This is the collection of instances returned when one does an expand on it. - :type instances: + :ivar instances: This is the collection of instances returned when one does an expand on it. + :vartype instances: list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] :ivar resource_id: ResourceId in which this review is getting created. :vartype resource_id: str :ivar role_definition_id: This is used to indicate the role being reviewed. :vartype role_definition_id: str :ivar principal_type_properties_scope_principal_type: The identity type user/servicePrincipal - to review. Possible values include: "user", "servicePrincipal". + to review. Known values are: "user" and "servicePrincipal". :vartype principal_type_properties_scope_principal_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScopePrincipalType - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to automatically change the target object access resource, is enabled. If not enabled, a user must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_properties_settings_recurrence_range_type: The recurrence range type. The possible - values are: endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_properties_settings_recurrence_range_type: str or + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_properties_settings_recurrence_range_type: The recurrence range type. The possible + values are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_properties_settings_recurrence_range_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, - etc. Possible values include: "weekly", "absoluteMonthly". - :type type_properties_settings_recurrence_pattern_type: str or + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, + etc. Known values are: "weekly" and "absoluteMonthly". + :vartype type_properties_settings_recurrence_pattern_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int :ivar principal_id: The identity id. :vartype principal_id: str :ivar principal_type_properties_created_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". + user/servicePrincipal. Known values are: "user" and "servicePrincipal". :vartype principal_type_properties_created_by_principal_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType :ivar principal_name: The identity display name. @@ -644,79 +739,157 @@ class AccessReviewScheduleDefinition(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'status': {'readonly': True}, - 'reviewers_type': {'readonly': True}, - 'resource_id': {'readonly': True}, - 'role_definition_id': {'readonly': True}, - 'principal_type_properties_scope_principal_type': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type_properties_created_by_principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + "resource_id": {"readonly": True}, + "role_definition_id": {"readonly": True}, + "principal_type_properties_scope_principal_type": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type_properties_created_by_principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'description_for_admins': {'key': 'properties.descriptionForAdmins', 'type': 'str'}, - 'description_for_reviewers': {'key': 'properties.descriptionForReviewers', 'type': 'str'}, - 'reviewers': {'key': 'properties.reviewers', 'type': '[AccessReviewReviewer]'}, - 'reviewers_type': {'key': 'properties.reviewersType', 'type': 'str'}, - 'instances': {'key': 'properties.instances', 'type': '[AccessReviewInstance]'}, - 'resource_id': {'key': 'properties.scope.resourceId', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.scope.roleDefinitionId', 'type': 'str'}, - 'principal_type_properties_scope_principal_type': {'key': 'properties.scope.principalType', 'type': 'str'}, - 'mail_notifications_enabled': {'key': 'properties.settings.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'properties.settings.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'properties.settings.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'properties.settings.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'properties.settings.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'properties.settings.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'properties.settings.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'properties.settings.instanceDurationInDays', 'type': 'int'}, - 'type_properties_settings_recurrence_range_type': {'key': 'properties.settings.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'properties.settings.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'properties.settings.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.settings.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_properties_settings_recurrence_pattern_type': {'key': 'properties.settings.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'properties.settings.recurrence.pattern.interval', 'type': 'int'}, - 'principal_id': {'key': 'properties.createdBy.principalId', 'type': 'str'}, - 'principal_type_properties_created_by_principal_type': {'key': 'properties.createdBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'properties.createdBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'properties.createdBy.userPrincipalName', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "description_for_admins": {"key": "properties.descriptionForAdmins", "type": "str"}, + "description_for_reviewers": {"key": "properties.descriptionForReviewers", "type": "str"}, + "reviewers": {"key": "properties.reviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "properties.reviewersType", "type": "str"}, + "instances": {"key": "properties.instances", "type": "[AccessReviewInstance]"}, + "resource_id": {"key": "properties.scope.resourceId", "type": "str"}, + "role_definition_id": {"key": "properties.scope.roleDefinitionId", "type": "str"}, + "principal_type_properties_scope_principal_type": {"key": "properties.scope.principalType", "type": "str"}, + "mail_notifications_enabled": {"key": "properties.settings.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "properties.settings.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "properties.settings.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": { + "key": "properties.settings.justificationRequiredOnApproval", + "type": "bool", + }, + "default_decision": {"key": "properties.settings.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "properties.settings.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "properties.settings.recommendationsEnabled", "type": "bool"}, + "instance_duration_in_days": {"key": "properties.settings.instanceDurationInDays", "type": "int"}, + "type_properties_settings_recurrence_range_type": { + "key": "properties.settings.recurrence.range.type", + "type": "str", + }, + "number_of_occurrences": {"key": "properties.settings.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "properties.settings.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.settings.recurrence.range.endDate", "type": "iso-8601"}, + "type_properties_settings_recurrence_pattern_type": { + "key": "properties.settings.recurrence.pattern.type", + "type": "str", + }, + "interval": {"key": "properties.settings.recurrence.pattern.interval", "type": "int"}, + "principal_id": {"key": "properties.createdBy.principalId", "type": "str"}, + "principal_type_properties_created_by_principal_type": { + "key": "properties.createdBy.principalType", + "type": "str", + }, + "principal_name": {"key": "properties.createdBy.principalName", "type": "str"}, + "user_principal_name": {"key": "properties.createdBy.userPrincipalName", "type": "str"}, } - def __init__( + def __init__( # pylint: disable=too-many-locals self, *, display_name: Optional[str] = None, description_for_admins: Optional[str] = None, description_for_reviewers: Optional[str] = None, - reviewers: Optional[List["AccessReviewReviewer"]] = None, - instances: Optional[List["AccessReviewInstance"]] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + instances: Optional[List["_models.AccessReviewInstance"]] = None, mail_notifications_enabled: Optional[bool] = None, reminder_notifications_enabled: Optional[bool] = None, default_decision_enabled: Optional[bool] = None, justification_required_on_approval: Optional[bool] = None, - default_decision: Optional[Union[str, "DefaultDecisionType"]] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, auto_apply_decisions_enabled: Optional[bool] = None, recommendations_enabled: Optional[bool] = None, instance_duration_in_days: Optional[int] = None, - type_properties_settings_recurrence_range_type: Optional[Union[str, "AccessReviewRecurrenceRangeType"]] = None, + type_properties_settings_recurrence_range_type: Optional[ + Union[str, "_models.AccessReviewRecurrenceRangeType"] + ] = None, number_of_occurrences: Optional[int] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, - type_properties_settings_recurrence_pattern_type: Optional[Union[str, "AccessReviewRecurrencePatternType"]] = None, + type_properties_settings_recurrence_pattern_type: Optional[ + Union[str, "_models.AccessReviewRecurrencePatternType"] + ] = None, interval: Optional[int] = None, **kwargs ): - super(AccessReviewScheduleDefinition, self).__init__(**kwargs) + """ + :keyword display_name: The display name for the schedule definition. + :paramtype display_name: str + :keyword description_for_admins: The description provided by the access review creator and + visible to admins. + :paramtype description_for_admins: str + :keyword description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :paramtype description_for_reviewers: str + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewReviewer] + :keyword instances: This is the collection of instances returned when one does an expand on it. + :paramtype instances: + list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_properties_settings_recurrence_range_type: The recurrence range type. The + possible values are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and + "numbered". + :paramtype type_properties_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, + monthly, etc. Known values are: "weekly" and "absoluteMonthly". + :paramtype type_properties_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -750,119 +923,126 @@ def __init__( self.user_principal_name = None -class AccessReviewScheduleDefinitionListResult(msrest.serialization.Model): +class AccessReviewScheduleDefinitionListResult(_serialization.Model): """List of Access Review Schedule Definitions. - :param value: Access Review Schedule Definition list. - :type value: + :ivar value: Access Review Schedule Definition list. + :vartype value: list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewScheduleDefinition]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[AccessReviewScheduleDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["AccessReviewScheduleDefinition"]] = None, + value: Optional[List["_models.AccessReviewScheduleDefinition"]] = None, next_link: Optional[str] = None, **kwargs ): - super(AccessReviewScheduleDefinitionListResult, self).__init__(**kwargs) + """ + :keyword value: Access Review Schedule Definition list. + :paramtype value: + list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class AccessReviewScheduleDefinitionProperties(msrest.serialization.Model): +class AccessReviewScheduleDefinitionProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes """Access Review. Variables are only populated by the server, and will be ignored when sending a request. - :param display_name: The display name for the schedule definition. - :type display_name: str - :ivar status: This read-only field specifies the status of an accessReview. Possible values - include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". + :ivar display_name: The display name for the schedule definition. + :vartype display_name: str + :ivar status: This read-only field specifies the status of an accessReview. Known values are: + "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", "Completing", + "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". :vartype status: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionStatus - :param description_for_admins: The description provided by the access review creator and - visible to admins. - :type description_for_admins: str - :param description_for_reviewers: The description provided by the access review creator to be + :ivar description_for_admins: The description provided by the access review creator and visible + to admins. + :vartype description_for_admins: str + :ivar description_for_reviewers: The description provided by the access review creator to be shown to reviewers. - :type description_for_reviewers: str - :param reviewers: This is the collection of reviewers. - :type reviewers: + :vartype description_for_reviewers: str + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewReviewer] :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be - assigned and instead be chosen dynamically. For example managers review or self review. - Possible values include: "Assigned", "Self", "Managers". + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". :vartype reviewers_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionReviewersType - :param instances: This is the collection of instances returned when one does an expand on it. - :type instances: + :ivar instances: This is the collection of instances returned when one does an expand on it. + :vartype instances: list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] :ivar resource_id: ResourceId in which this review is getting created. :vartype resource_id: str :ivar role_definition_id: This is used to indicate the role being reviewed. :vartype role_definition_id: str :ivar principal_type_scope_principal_type: The identity type user/servicePrincipal to review. - Possible values include: "user", "servicePrincipal". + Known values are: "user" and "servicePrincipal". :vartype principal_type_scope_principal_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScopePrincipalType - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to automatically change the target object access resource, is enabled. If not enabled, a user must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_settings_recurrence_range_type: The recurrence range type. The possible values are: - endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_settings_recurrence_range_type: str or + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_settings_recurrence_range_type: The recurrence range type. The possible values are: + endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_settings_recurrence_range_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. - Possible values include: "weekly", "absoluteMonthly". - :type type_settings_recurrence_pattern_type: str or + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known + values are: "weekly" and "absoluteMonthly". + :vartype type_settings_recurrence_pattern_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int :ivar principal_id: The identity id. :vartype principal_id: str :ivar principal_type_created_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". + Known values are: "user" and "servicePrincipal". :vartype principal_type_created_by_principal_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewActorIdentityType :ivar principal_name: The identity display name. @@ -872,73 +1052,134 @@ class AccessReviewScheduleDefinitionProperties(msrest.serialization.Model): """ _validation = { - 'status': {'readonly': True}, - 'reviewers_type': {'readonly': True}, - 'resource_id': {'readonly': True}, - 'role_definition_id': {'readonly': True}, - 'principal_type_scope_principal_type': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type_created_by_principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + "resource_id": {"readonly": True}, + "role_definition_id": {"readonly": True}, + "principal_type_scope_principal_type": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type_created_by_principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, } _attribute_map = { - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'description_for_admins': {'key': 'descriptionForAdmins', 'type': 'str'}, - 'description_for_reviewers': {'key': 'descriptionForReviewers', 'type': 'str'}, - 'reviewers': {'key': 'reviewers', 'type': '[AccessReviewReviewer]'}, - 'reviewers_type': {'key': 'reviewersType', 'type': 'str'}, - 'instances': {'key': 'instances', 'type': '[AccessReviewInstance]'}, - 'resource_id': {'key': 'scope.resourceId', 'type': 'str'}, - 'role_definition_id': {'key': 'scope.roleDefinitionId', 'type': 'str'}, - 'principal_type_scope_principal_type': {'key': 'scope.principalType', 'type': 'str'}, - 'mail_notifications_enabled': {'key': 'settings.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'settings.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'settings.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'settings.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'settings.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'settings.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'settings.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'settings.instanceDurationInDays', 'type': 'int'}, - 'type_settings_recurrence_range_type': {'key': 'settings.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'settings.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'settings.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'settings.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_settings_recurrence_pattern_type': {'key': 'settings.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'settings.recurrence.pattern.interval', 'type': 'int'}, - 'principal_id': {'key': 'createdBy.principalId', 'type': 'str'}, - 'principal_type_created_by_principal_type': {'key': 'createdBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'createdBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'createdBy.userPrincipalName', 'type': 'str'}, + "display_name": {"key": "displayName", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "description_for_admins": {"key": "descriptionForAdmins", "type": "str"}, + "description_for_reviewers": {"key": "descriptionForReviewers", "type": "str"}, + "reviewers": {"key": "reviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "reviewersType", "type": "str"}, + "instances": {"key": "instances", "type": "[AccessReviewInstance]"}, + "resource_id": {"key": "scope.resourceId", "type": "str"}, + "role_definition_id": {"key": "scope.roleDefinitionId", "type": "str"}, + "principal_type_scope_principal_type": {"key": "scope.principalType", "type": "str"}, + "mail_notifications_enabled": {"key": "settings.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "settings.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "settings.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "settings.justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "settings.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "settings.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "settings.recommendationsEnabled", "type": "bool"}, + "instance_duration_in_days": {"key": "settings.instanceDurationInDays", "type": "int"}, + "type_settings_recurrence_range_type": {"key": "settings.recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "settings.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "settings.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "settings.recurrence.range.endDate", "type": "iso-8601"}, + "type_settings_recurrence_pattern_type": {"key": "settings.recurrence.pattern.type", "type": "str"}, + "interval": {"key": "settings.recurrence.pattern.interval", "type": "int"}, + "principal_id": {"key": "createdBy.principalId", "type": "str"}, + "principal_type_created_by_principal_type": {"key": "createdBy.principalType", "type": "str"}, + "principal_name": {"key": "createdBy.principalName", "type": "str"}, + "user_principal_name": {"key": "createdBy.userPrincipalName", "type": "str"}, } - def __init__( + def __init__( # pylint: disable=too-many-locals self, *, display_name: Optional[str] = None, description_for_admins: Optional[str] = None, description_for_reviewers: Optional[str] = None, - reviewers: Optional[List["AccessReviewReviewer"]] = None, - instances: Optional[List["AccessReviewInstance"]] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + instances: Optional[List["_models.AccessReviewInstance"]] = None, mail_notifications_enabled: Optional[bool] = None, reminder_notifications_enabled: Optional[bool] = None, default_decision_enabled: Optional[bool] = None, justification_required_on_approval: Optional[bool] = None, - default_decision: Optional[Union[str, "DefaultDecisionType"]] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, auto_apply_decisions_enabled: Optional[bool] = None, recommendations_enabled: Optional[bool] = None, instance_duration_in_days: Optional[int] = None, - type_settings_recurrence_range_type: Optional[Union[str, "AccessReviewRecurrenceRangeType"]] = None, + type_settings_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, number_of_occurrences: Optional[int] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, - type_settings_recurrence_pattern_type: Optional[Union[str, "AccessReviewRecurrencePatternType"]] = None, + type_settings_recurrence_pattern_type: Optional[Union[str, "_models.AccessReviewRecurrencePatternType"]] = None, interval: Optional[int] = None, **kwargs ): - super(AccessReviewScheduleDefinitionProperties, self).__init__(**kwargs) + """ + :keyword display_name: The display name for the schedule definition. + :paramtype display_name: str + :keyword description_for_admins: The description provided by the access review creator and + visible to admins. + :paramtype description_for_admins: str + :keyword description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :paramtype description_for_reviewers: str + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewReviewer] + :keyword instances: This is the collection of instances returned when one does an expand on it. + :paramtype instances: + list[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_settings_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :paramtype type_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) self.display_name = display_name self.status = None self.description_for_admins = description_for_admins @@ -969,70 +1210,70 @@ def __init__( self.user_principal_name = None -class AccessReviewScheduleSettings(msrest.serialization.Model): +class AccessReviewScheduleSettings(_serialization.Model): # pylint: disable=too-many-instance-attributes """Settings of an Access Review. - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to automatically change the target object access resource, is enabled. If not enabled, a user must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_recurrence_range_type: The recurrence range type. The possible values are: endDate, - noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_recurrence_range_type: str or + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_recurrence_range_type: The recurrence range type. The possible values are: endDate, + noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_recurrence_range_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Possible - values include: "weekly", "absoluteMonthly". - :type type_recurrence_pattern_type: str or + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known values + are: "weekly" and "absoluteMonthly". + :vartype type_recurrence_pattern_type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int """ _attribute_map = { - 'mail_notifications_enabled': {'key': 'mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'instanceDurationInDays', 'type': 'int'}, - 'type_recurrence_range_type': {'key': 'recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_recurrence_pattern_type': {'key': 'recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'recurrence.pattern.interval', 'type': 'int'}, + "mail_notifications_enabled": {"key": "mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "recommendationsEnabled", "type": "bool"}, + "instance_duration_in_days": {"key": "instanceDurationInDays", "type": "int"}, + "type_recurrence_range_type": {"key": "recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "recurrence.range.endDate", "type": "iso-8601"}, + "type_recurrence_pattern_type": {"key": "recurrence.pattern.type", "type": "str"}, + "interval": {"key": "recurrence.pattern.interval", "type": "int"}, } def __init__( @@ -1042,19 +1283,66 @@ def __init__( reminder_notifications_enabled: Optional[bool] = None, default_decision_enabled: Optional[bool] = None, justification_required_on_approval: Optional[bool] = None, - default_decision: Optional[Union[str, "DefaultDecisionType"]] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, auto_apply_decisions_enabled: Optional[bool] = None, recommendations_enabled: Optional[bool] = None, instance_duration_in_days: Optional[int] = None, - type_recurrence_range_type: Optional[Union[str, "AccessReviewRecurrenceRangeType"]] = None, + type_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, number_of_occurrences: Optional[int] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, - type_recurrence_pattern_type: Optional[Union[str, "AccessReviewRecurrencePatternType"]] = None, + type_recurrence_pattern_type: Optional[Union[str, "_models.AccessReviewRecurrencePatternType"]] = None, interval: Optional[int] = None, **kwargs ): - super(AccessReviewScheduleSettings, self).__init__(**kwargs) + """ + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_recurrence_range_type: The recurrence range type. The possible values are: + endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_recurrence_range_type: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known values + are: "weekly" and "absoluteMonthly". + :paramtype type_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) self.mail_notifications_enabled = mail_notifications_enabled self.reminder_notifications_enabled = reminder_notifications_enabled self.default_decision_enabled = default_decision_enabled @@ -1071,76 +1359,75 @@ def __init__( self.interval = interval -class ErrorDefinition(msrest.serialization.Model): +class ErrorDefinition(_serialization.Model): """Error description and code explaining why an operation failed. - :param error: Error of the list gateway status. - :type error: ~azure.mgmt.authorization.v2018_05_01_preview.models.ErrorDefinitionProperties + :ivar error: Error of the list gateway status. + :vartype error: ~azure.mgmt.authorization.v2018_05_01_preview.models.ErrorDefinitionProperties """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinitionProperties'}, + "error": {"key": "error", "type": "ErrorDefinitionProperties"}, } - def __init__( - self, - *, - error: Optional["ErrorDefinitionProperties"] = None, - **kwargs - ): - super(ErrorDefinition, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDefinitionProperties"] = None, **kwargs): + """ + :keyword error: Error of the list gateway status. + :paramtype error: + ~azure.mgmt.authorization.v2018_05_01_preview.models.ErrorDefinitionProperties + """ + super().__init__(**kwargs) self.error = error -class ErrorDefinitionProperties(msrest.serialization.Model): +class ErrorDefinitionProperties(_serialization.Model): """Error description and code explaining why an operation failed. Variables are only populated by the server, and will be ignored when sending a request. :ivar message: Description of the error. :vartype message: str - :param code: Error code of list gateway. - :type code: str + :ivar code: Error code of list gateway. + :vartype code: str """ _validation = { - 'message': {'readonly': True}, + "message": {"readonly": True}, } _attribute_map = { - 'message': {'key': 'message', 'type': 'str'}, - 'code': {'key': 'code', 'type': 'str'}, + "message": {"key": "message", "type": "str"}, + "code": {"key": "code", "type": "str"}, } - def __init__( - self, - *, - code: Optional[str] = None, - **kwargs - ): - super(ErrorDefinitionProperties, self).__init__(**kwargs) + def __init__(self, *, code: Optional[str] = None, **kwargs): + """ + :keyword code: Error code of list gateway. + :paramtype code: str + """ + super().__init__(**kwargs) self.message = None self.code = code -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """The definition of a Microsoft.Authorization operation. - :param name: Name of the operation. - :type name: str - :param is_data_action: Indicates whether the operation is a data action. - :type is_data_action: bool - :param display: Display of the operation. - :type display: ~azure.mgmt.authorization.v2018_05_01_preview.models.OperationDisplay - :param origin: Origin of the operation. - :type origin: str + :ivar name: Name of the operation. + :vartype name: str + :ivar is_data_action: Indicates whether the operation is a data action. + :vartype is_data_action: bool + :ivar display: Display of the operation. + :vartype display: ~azure.mgmt.authorization.v2018_05_01_preview.models.OperationDisplay + :ivar origin: Origin of the operation. + :vartype origin: str """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'origin': {'key': 'origin', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, } def __init__( @@ -1148,18 +1435,28 @@ def __init__( *, name: Optional[str] = None, is_data_action: Optional[bool] = None, - display: Optional["OperationDisplay"] = None, + display: Optional["_models.OperationDisplay"] = None, origin: Optional[str] = None, **kwargs ): - super(Operation, self).__init__(**kwargs) + """ + :keyword name: Name of the operation. + :paramtype name: str + :keyword is_data_action: Indicates whether the operation is a data action. + :paramtype is_data_action: bool + :keyword display: Display of the operation. + :paramtype display: ~azure.mgmt.authorization.v2018_05_01_preview.models.OperationDisplay + :keyword origin: Origin of the operation. + :paramtype origin: str + """ + super().__init__(**kwargs) self.name = name self.is_data_action = is_data_action self.display = display self.origin = origin -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """The display information for a Microsoft.Authorization operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -1175,52 +1472,50 @@ class OperationDisplay(msrest.serialization.Model): """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """The result of a request to list Microsoft.Authorization operations. - :param value: The collection value. - :type value: list[~azure.mgmt.authorization.v2018_05_01_preview.models.Operation] - :param next_link: The URI that can be used to request the next set of paged results. - :type next_link: str + :ivar value: The collection value. + :vartype value: list[~azure.mgmt.authorization.v2018_05_01_preview.models.Operation] + :ivar next_link: The URI that can be used to request the next set of paged results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["Operation"]] = None, - next_link: Optional[str] = None, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs): + """ + :keyword value: The collection value. + :paramtype value: list[~azure.mgmt.authorization.v2018_05_01_preview.models.Operation] + :keyword next_link: The URI that can be used to request the next set of paged results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link @@ -1232,9 +1527,9 @@ class ServicePrincipalDecisionTarget(AccessReviewDecisionTarget): All required parameters must be populated in order to send to Azure. - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType :ivar principal_id: The id of service principal whose access is reviewed. :vartype principal_id: str :ivar principal_name: The display name of the service principal whose access was reviewed. @@ -1244,25 +1539,23 @@ class ServicePrincipalDecisionTarget(AccessReviewDecisionTarget): """ _validation = { - 'type': {'required': True}, - 'principal_id': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'app_id': {'readonly': True}, + "type": {"required": True}, + "principal_id": {"readonly": True}, + "principal_name": {"readonly": True}, + "app_id": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'principal_name': {'key': 'principalName', 'type': 'str'}, - 'app_id': {'key': 'appId', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "principal_id": {"key": "principalId", "type": "str"}, + "principal_name": {"key": "principalName", "type": "str"}, + "app_id": {"key": "appId", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(ServicePrincipalDecisionTarget, self).__init__(**kwargs) - self.type = 'servicePrincipal' # type: str + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = "servicePrincipal" # type: str self.principal_id = None self.principal_name = None self.app_id = None @@ -1275,9 +1568,9 @@ class UserDecisionTarget(AccessReviewDecisionTarget): All required parameters must be populated in order to send to Azure. - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2018_05_01_preview.models.DecisionTargetType :ivar principal_id: The id of user whose access was reviewed. :vartype principal_id: str :ivar principal_name: The display name of the user whose access was reviewed. @@ -1287,25 +1580,23 @@ class UserDecisionTarget(AccessReviewDecisionTarget): """ _validation = { - 'type': {'required': True}, - 'principal_id': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, + "type": {"required": True}, + "principal_id": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'principal_name': {'key': 'principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'userPrincipalName', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "principal_id": {"key": "principalId", "type": "str"}, + "principal_name": {"key": "principalName", "type": "str"}, + "user_principal_name": {"key": "userPrincipalName", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(UserDecisionTarget, self).__init__(**kwargs) - self.type = 'user' # type: str + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = "user" # type: str self.principal_id = None self.principal_name = None self.user_principal_name = None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/__init__.py index 9fe7178064d..2ed7cbae216 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/__init__.py @@ -12,18 +12,28 @@ from ._access_review_instance_operations import AccessReviewInstanceOperations from ._access_review_instance_decisions_operations import AccessReviewInstanceDecisionsOperations from ._access_review_default_settings_operations import AccessReviewDefaultSettingsOperations -from ._access_review_schedule_definitions_assigned_for_my_approval_operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations -from ._access_review_instances_assigned_for_my_approval_operations import AccessReviewInstancesAssignedForMyApprovalOperations +from ._access_review_schedule_definitions_assigned_for_my_approval_operations import ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, +) +from ._access_review_instances_assigned_for_my_approval_operations import ( + AccessReviewInstancesAssignedForMyApprovalOperations, +) from ._access_review_instance_my_decisions_operations import AccessReviewInstanceMyDecisionsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'Operations', - 'AccessReviewScheduleDefinitionsOperations', - 'AccessReviewInstancesOperations', - 'AccessReviewInstanceOperations', - 'AccessReviewInstanceDecisionsOperations', - 'AccessReviewDefaultSettingsOperations', - 'AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations', - 'AccessReviewInstancesAssignedForMyApprovalOperations', - 'AccessReviewInstanceMyDecisionsOperations', + "Operations", + "AccessReviewScheduleDefinitionsOperations", + "AccessReviewInstancesOperations", + "AccessReviewInstanceOperations", + "AccessReviewInstanceDecisionsOperations", + "AccessReviewDefaultSettingsOperations", + "AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations", + "AccessReviewInstancesAssignedForMyApprovalOperations", + "AccessReviewInstanceMyDecisionsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_default_settings_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_default_settings_operations.py index 3825a6e7381..5868fcfc85e 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_default_settings_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_default_settings_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,153 +6,268 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class AccessReviewDefaultSettingsOperations(object): - """AccessReviewDefaultSettingsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_get_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_put_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewDefaultSettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_default_settings` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def get( - self, - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewDefaultSettings" + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, **kwargs: Any) -> _models.AccessReviewDefaultSettings: """Get access review default settings for the subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDefaultSettings, or the result of cls(response) + :return: AccessReviewDefaultSettings or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDefaultSettings - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDefaultSettings"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDefaultSettings', pipeline_response) + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore + + @overload def put( - self, - properties, # type: "_models.AccessReviewScheduleSettings" - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewDefaultSettings" + self, properties: _models.AccessReviewScheduleSettings, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: """Get access review default settings for the subscription. - :param properties: Access review schedule settings. - :type properties: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleSettings + :param properties: Access review schedule settings. Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleSettings + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDefaultSettings, or the result of cls(response) + :return: AccessReviewDefaultSettings or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDefaultSettings - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put( + self, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put( + self, properties: Union[_models.AccessReviewScheduleSettings, IO], **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleSettings or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDefaultSettings"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.put.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewScheduleSettings') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleSettings") + + request = build_put_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDefaultSettings', pipeline_response) + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default'} # type: ignore + + put.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_decisions_operations.py index 554fcef70f1..fbc8aede25e 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_decisions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_decisions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,99 +6,141 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } -class AccessReviewInstanceDecisionsOperations(object): - """AccessReviewInstanceDecisionsOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance_decisions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewDecisionListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, schedule_definition_id: str, id: str, **kwargs: Any) -> Iterable["_models.AccessReviewDecision"]: """Get access review instance decisions. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewDecisionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecisionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecisionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewDecisionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -106,17 +149,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_my_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_my_decisions_operations.py index 9f704824933..4f74b93be30 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_my_decisions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_my_decisions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,98 +6,200 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "decisionId": _SERIALIZER.url("decision_id", decision_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class AccessReviewInstanceMyDecisionsOperations(object): - """AccessReviewInstanceMyDecisionsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_patch_request(schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "decisionId": _SERIALIZER.url("decision_id", decision_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceMyDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance_my_decisions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewDecisionListResult"] + @distributed_trace + def list(self, schedule_definition_id: str, id: str, **kwargs: Any) -> Iterable["_models.AccessReviewDecision"]: """Get my access review instance decisions. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewDecisionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecisionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecisionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewDecisionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -105,151 +208,229 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore + @distributed_trace def get_by_id( - self, - schedule_definition_id, # type: str - id, # type: str - decision_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewDecision" + self, schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any + ) -> _models.AccessReviewDecision: """Get my single access review instance decision. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str - :param decision_id: The id of the decision record. + :param decision_id: The id of the decision record. Required. :type decision_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDecision, or the result of cls(response) + :return: AccessReviewDecision or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecision"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'decisionId': self._serialize.url("decision_id", decision_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDecision', pipeline_response) + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}'} # type: ignore + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore + + @overload + def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: _models.AccessReviewDecisionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecisionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload def patch( self, - schedule_definition_id, # type: str - id, # type: str - decision_id, # type: str - properties, # type: "_models.AccessReviewDecisionProperties" - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewDecision" + schedule_definition_id: str, + id: str, + decision_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: """Record a decision. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str - :param decision_id: The id of the decision record. + :param decision_id: The id of the decision record. Required. :type decision_id: str - :param properties: Access review decision properties to patch. - :type properties: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecisionProperties + :param properties: Access review decision properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDecision, or the result of cls(response) + :return: AccessReviewDecision or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: Union[_models.AccessReviewDecisionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecisionProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecision"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.patch.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'decisionId': self._serialize.url("decision_id", decision_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewDecisionProperties') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewDecisionProperties") + + request = build_patch_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDecision', pipeline_response) + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - patch.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}'} # type: ignore + + patch.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_operations.py index c9630800f4b..52cb1d9fc28 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instance_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,325 +6,483 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_stop_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reset_decisions_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_apply_decisions_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_send_reminders_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } -class AccessReviewInstanceOperations(object): - """AccessReviewInstanceOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_accept_recommendations_request(schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def stop( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: """An action to stop an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.stop.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - stop.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop'} # type: ignore + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop"} # type: ignore - def reset_decisions( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + @distributed_trace + def reset_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: """An action to reset all decisions for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.reset_decisions.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reset_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.reset_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - reset_decisions.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions'} # type: ignore + reset_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions"} # type: ignore - def apply_decisions( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + @distributed_trace + def apply_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: """An action to apply all decisions for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.apply_decisions.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_apply_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.apply_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - apply_decisions.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions'} # type: ignore + apply_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions"} # type: ignore - def send_reminders( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + @distributed_trace + def send_reminders( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: """An action to send reminders for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.send_reminders.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_send_reminders_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.send_reminders.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - send_reminders.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders'} # type: ignore + send_reminders.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders"} # type: ignore - def accept_recommendations( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + @distributed_trace + def accept_recommendations( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: """An action to accept recommendations for decision in an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.accept_recommendations.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_accept_recommendations_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.accept_recommendations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - accept_recommendations.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations'} # type: ignore + accept_recommendations.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py index 84f0ecf936a..836331f4cca 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,94 +6,163 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(schedule_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class AccessReviewInstancesAssignedForMyApprovalOperations(object): - """AccessReviewInstancesAssignedForMyApprovalOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_get_by_id_request(schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstancesAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instances_assigned_for_my_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - schedule_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewInstanceListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, schedule_definition_id: str, **kwargs: Any) -> Iterable["_models.AccessReviewInstance"]: """Get access review instances assigned for my approval. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewInstanceListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewInstanceListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -101,76 +171,76 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances'} # type: ignore - - def get_by_id( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewInstance" + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: """Get single access review instance assigned for my approval. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewInstance, or the result of cls(response) + :return: AccessReviewInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewInstance', pipeline_response) + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}'} # type: ignore + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instances_operations.py index d59e1807791..a54a6c24d73 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instances_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_instances_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,166 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class AccessReviewInstancesOperations(object): - """AccessReviewInstancesOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class AccessReviewInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instances` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - schedule_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewInstanceListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, schedule_definition_id: str, **kwargs: Any) -> Iterable["_models.AccessReviewInstance"]: """Get access review instances. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewInstanceListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewInstanceListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -102,77 +174,77 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances'} # type: ignore - - def get_by_id( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewInstance" + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: """Get access review instances. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewInstance, or the result of cls(response) + :return: AccessReviewInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewInstance', pipeline_response) + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}'} # type: ignore + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py index 9c137da7b56..494e70f11dc 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") -class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations(object): - """AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations. + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions_assigned_for_my_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewScheduleDefinitionListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.AccessReviewScheduleDefinition"]: """Get access review instances assigned for my approval. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewScheduleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewScheduleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,17 +132,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_schedule_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_schedule_definitions_operations.py index c66ac2cf646..cba32538058 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_schedule_definitions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_access_review_schedule_definitions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,91 +6,250 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + _url = _format_url_section(_url, **path_format_arguments) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -class AccessReviewScheduleDefinitionsOperations(object): - """AccessReviewScheduleDefinitionsOperations operations. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + +def build_create_or_update_by_id_request( + schedule_definition_id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_stop_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewScheduleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewScheduleDefinitionListResult"] + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.AccessReviewScheduleDefinition"]: """Get access review schedule definitions. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewScheduleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewScheduleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -98,243 +258,307 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions'} # type: ignore + return ItemPaged(get_next, extract_data) - def get_by_id( - self, - schedule_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewScheduleDefinition" + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, **kwargs: Any) -> _models.AccessReviewScheduleDefinition: """Get single access review definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewScheduleDefinition, or the result of cls(response) + :return: AccessReviewScheduleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewScheduleDefinition', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore - def delete_by_id( - self, - schedule_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace + def delete_by_id( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: """Delete access review schedule definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_delete_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore + delete_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @overload + def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: _models.AccessReviewScheduleDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_by_id( + self, schedule_definition_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace def create_or_update_by_id( self, - schedule_definition_id, # type: str - properties, # type: "_models.AccessReviewScheduleDefinitionProperties" - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewScheduleDefinition" + schedule_definition_id: str, + properties: Union[_models.AccessReviewScheduleDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: """Create or Update access review schedule definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param properties: Access review schedule definition properties. - :type properties: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionProperties + :param properties: Access review schedule definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinitionProperties + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewScheduleDefinition, or the result of cls(response) + :return: AccessReviewScheduleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_05_01_preview.models.AccessReviewScheduleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewScheduleDefinitionProperties') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleDefinitionProperties") + + request = build_create_or_update_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewScheduleDefinition', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore - def stop( - self, - schedule_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + create_or_update_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace + def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: """Stop access review definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" - - # Construct URL - url = self.stop.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - stop.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop'} # type: ignore + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_operations.py index 82a69202c8f..213e2d50373 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,123 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") -class Operations(object): - """Operations operations. + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/operations") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_05_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_05_01_preview.AuthorizationManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.OperationListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists the operations available from this provider. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_05_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-05-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-05-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,17 +131,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/operations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_05_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/__init__.py index ae11ad3e4d9..9eb8d3ec28c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AuthorizationManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_authorization_management_client.py index fe329ce394c..25571d732e1 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_authorization_management_client.py @@ -6,73 +6,83 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import DenyAssignmentsOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import DenyAssignmentsOperations -from . import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to get deny assignments. A deny assignment describes the set of actions on resources that are denied for Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to get deny + assignments. A deny assignment describes the set of actions on resources that are denied for + Azure Active Directory users. :ivar deny_assignments: DenyAssignmentsOperations operations - :vartype deny_assignments: azure.mgmt.authorization.v2018_07_01_preview.operations.DenyAssignmentsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype deny_assignments: + azure.mgmt.authorization.v2018_07_01_preview.operations.DenyAssignmentsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-07-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.deny_assignments = DenyAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_configuration.py index 12ef59d35da..ba36ff26b3f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_configuration.py @@ -6,66 +6,64 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-07-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2018-07-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-07-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_metadata.json index 0666c785851..b3aba243681 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_metadata.json +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_metadata.json @@ -5,25 +5,25 @@ "name": "AuthorizationManagementClient", "filename": "_authorization_management_client", "description": "Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to get deny assignments. A deny assignment describes the set of actions on resources that are denied for Azure Active Directory users.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, "azure_arm": true, "has_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -54,7 +54,7 @@ "required": false }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -74,7 +74,7 @@ "required": false }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -91,11 +91,10 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "deny_assignments": "DenyAssignmentsOperations" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_version.py index 48944bf3938..cac9f5d10f8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/__init__.py index ffc49d028e4..dd28625b36f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._authorization_management_client import AuthorizationManagementClient -__all__ = ['AuthorizationManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_authorization_management_client.py index d2bb50dc9de..9431541b6d6 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_authorization_management_client.py @@ -6,69 +6,83 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import DenyAssignmentsOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import DenyAssignmentsOperations -from .. import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to get deny assignments. A deny assignment describes the set of actions on resources that are denied for Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to get deny + assignments. A deny assignment describes the set of actions on resources that are denied for + Azure Active Directory users. :ivar deny_assignments: DenyAssignmentsOperations operations - :vartype deny_assignments: azure.mgmt.authorization.v2018_07_01_preview.aio.operations.DenyAssignmentsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype deny_assignments: + azure.mgmt.authorization.v2018_07_01_preview.aio.operations.DenyAssignmentsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-07-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.deny_assignments = DenyAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_configuration.py index f2b03196299..62379748998 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,49 +19,48 @@ from azure.core.credentials_async import AsyncTokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-07-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2018-07-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-07-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/__init__.py index 7b0c7bab2bc..590e6d32085 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/__init__.py @@ -8,6 +8,12 @@ from ._deny_assignments_operations import DenyAssignmentsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'DenyAssignmentsOperations', + "DenyAssignmentsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/_deny_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/_deny_assignments_operations.py index d18c4796ca4..f0627b5b6ee 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/_deny_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/_deny_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,42 +6,61 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._deny_assignments_operations import ( + build_get_by_id_request, + build_get_request, + build_list_for_resource_group_request, + build_list_for_resource_request, + build_list_for_scope_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DenyAssignmentsOperations: - """DenyAssignmentsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class DenyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_07_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`deny_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_resource( self, resource_group_name: str, @@ -50,18 +70,19 @@ def list_for_resource( resource_name: str, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.DenyAssignmentListResult"]: + ) -> AsyncIterable["_models.DenyAssignment"]: """Gets deny assignments for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get deny assignments for. + :param resource_name: The name of the resource to get deny assignments for. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny @@ -72,53 +93,60 @@ def list_for_resource( returns not only those deny assignments that contain the specified principal is the Principals list but also those deny assignments that contain the specified principal is the ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny - assignment name and description properties are returned. + assignment name and description properties are returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DenyAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('DenyAssignmentListResult', pipeline_response) + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -127,30 +155,30 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/denyAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + + @distributed_trace def list_for_resource_group( - self, - resource_group_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.DenyAssignmentListResult"]: + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.DenyAssignment"]: """Gets deny assignments for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny @@ -161,49 +189,56 @@ def list_for_resource_group( returns not only those deny assignments that contain the specified principal is the Principals list but also those deny assignments that contain the specified principal is the ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny - assignment name and description properties are returned. + assignment name and description properties are returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DenyAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('DenyAssignmentListResult', pipeline_response) + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -212,26 +247,24 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/denyAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - def list( - self, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.DenyAssignmentListResult"]: + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.DenyAssignment"]: """Gets all deny assignments for the subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny @@ -243,48 +276,55 @@ def list( returns not only those deny assignments that contain the specified principal is the Principals list but also those deny assignments that contain the specified principal is the ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny - assignment name and description properties are returned. + assignment name and description properties are returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DenyAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('DenyAssignmentListResult', pipeline_response) + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -293,146 +333,146 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/denyAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get( - self, - scope: str, - deny_assignment_id: str, - **kwargs: Any - ) -> "_models.DenyAssignment": + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, deny_assignment_id: str, **kwargs: Any) -> _models.DenyAssignment: """Get the specified deny assignment. - :param scope: The scope of the deny assignment. + :param scope: The scope of the deny assignment. Required. :type scope: str - :param deny_assignment_id: The ID of the deny assignment to get. + :param deny_assignment_id: The ID of the deny assignment to get. Required. :type deny_assignment_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DenyAssignment, or the result of cls(response) + :return: DenyAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'denyAssignmentId': self._serialize.url("deny_assignment_id", deny_assignment_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignment] + + request = build_get_request( + scope=scope, + deny_assignment_id=deny_assignment_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DenyAssignment', pipeline_response) + deserialized = self._deserialize("DenyAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId}'} # type: ignore - async def get_by_id( - self, - deny_assignment_id: str, - **kwargs: Any - ) -> "_models.DenyAssignment": + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId}"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, deny_assignment_id: str, **kwargs: Any) -> _models.DenyAssignment: """Gets a deny assignment by ID. :param deny_assignment_id: The fully qualified deny assignment ID. For example, use the format, /subscriptions/{guid}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} for subscription level deny assignments, or /providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} for tenant level deny - assignments. + assignments. Required. :type deny_assignment_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DenyAssignment, or the result of cls(response) + :return: DenyAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'denyAssignmentId': self._serialize.url("deny_assignment_id", deny_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignment] + + request = build_get_by_id_request( + deny_assignment_id=deny_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DenyAssignment', pipeline_response) + deserialized = self._deserialize("DenyAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{denyAssignmentId}'} # type: ignore + get_by_id.metadata = {"url": "/{denyAssignmentId}"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.DenyAssignmentListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.DenyAssignment"]: """Gets deny assignments for a scope. - :param scope: The scope of the deny assignments. + :param scope: The scope of the deny assignments. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny @@ -443,48 +483,55 @@ def list_for_scope( returns not only those deny assignments that contain the specified principal is the Principals list but also those deny assignments that contain the specified principal is the ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny - assignment name and description properties are returned. + assignment name and description properties are returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DenyAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('DenyAssignmentListResult', pipeline_response) + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -493,17 +540,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/denyAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/__init__.py index 61272d33ee6..f7ab42f8b40 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/__init__.py @@ -6,32 +6,27 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import DenyAssignment - from ._models_py3 import DenyAssignmentFilter - from ._models_py3 import DenyAssignmentListResult - from ._models_py3 import DenyAssignmentPermission - from ._models_py3 import ErrorAdditionalInfo - from ._models_py3 import ErrorDetail - from ._models_py3 import ErrorResponse - from ._models_py3 import Principal -except (SyntaxError, ImportError): - from ._models import DenyAssignment # type: ignore - from ._models import DenyAssignmentFilter # type: ignore - from ._models import DenyAssignmentListResult # type: ignore - from ._models import DenyAssignmentPermission # type: ignore - from ._models import ErrorAdditionalInfo # type: ignore - from ._models import ErrorDetail # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import Principal # type: ignore +from ._models_py3 import DenyAssignment +from ._models_py3 import DenyAssignmentFilter +from ._models_py3 import DenyAssignmentListResult +from ._models_py3 import DenyAssignmentPermission +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import Principal +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'DenyAssignment', - 'DenyAssignmentFilter', - 'DenyAssignmentListResult', - 'DenyAssignmentPermission', - 'ErrorAdditionalInfo', - 'ErrorDetail', - 'ErrorResponse', - 'Principal', + "DenyAssignment", + "DenyAssignmentFilter", + "DenyAssignmentListResult", + "DenyAssignmentPermission", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "Principal", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_models.py deleted file mode 100644 index d3b3f670111..00000000000 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_models.py +++ /dev/null @@ -1,290 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class DenyAssignment(msrest.serialization.Model): - """Deny Assignment. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The deny assignment ID. - :vartype id: str - :ivar name: The deny assignment name. - :vartype name: str - :ivar type: The deny assignment type. - :vartype type: str - :param deny_assignment_name: The display name of the deny assignment. - :type deny_assignment_name: str - :param description: The description of the deny assignment. - :type description: str - :param permissions: An array of permissions that are denied by the deny assignment. - :type permissions: - list[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignmentPermission] - :param scope: The deny assignment scope. - :type scope: str - :param do_not_apply_to_child_scopes: Determines if the deny assignment applies to child scopes. - Default value is false. - :type do_not_apply_to_child_scopes: bool - :param principals: Array of principals to which the deny assignment applies. - :type principals: list[~azure.mgmt.authorization.v2018_07_01_preview.models.Principal] - :param exclude_principals: Array of principals to which the deny assignment does not apply. - :type exclude_principals: list[~azure.mgmt.authorization.v2018_07_01_preview.models.Principal] - :param is_system_protected: Specifies whether this deny assignment was created by Azure and - cannot be edited or deleted. - :type is_system_protected: bool - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'deny_assignment_name': {'key': 'properties.denyAssignmentName', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'permissions': {'key': 'properties.permissions', 'type': '[DenyAssignmentPermission]'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'do_not_apply_to_child_scopes': {'key': 'properties.doNotApplyToChildScopes', 'type': 'bool'}, - 'principals': {'key': 'properties.principals', 'type': '[Principal]'}, - 'exclude_principals': {'key': 'properties.excludePrincipals', 'type': '[Principal]'}, - 'is_system_protected': {'key': 'properties.isSystemProtected', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(DenyAssignment, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.deny_assignment_name = kwargs.get('deny_assignment_name', None) - self.description = kwargs.get('description', None) - self.permissions = kwargs.get('permissions', None) - self.scope = kwargs.get('scope', None) - self.do_not_apply_to_child_scopes = kwargs.get('do_not_apply_to_child_scopes', None) - self.principals = kwargs.get('principals', None) - self.exclude_principals = kwargs.get('exclude_principals', None) - self.is_system_protected = kwargs.get('is_system_protected', None) - - -class DenyAssignmentFilter(msrest.serialization.Model): - """Deny Assignments filter. - - :param deny_assignment_name: Return deny assignment with specified name. - :type deny_assignment_name: str - :param principal_id: Return all deny assignments where the specified principal is listed in the - principals list of deny assignments. - :type principal_id: str - :param gdpr_export_principal_id: Return all deny assignments where the specified principal is - listed either in the principals list or exclude principals list of deny assignments. - :type gdpr_export_principal_id: str - """ - - _attribute_map = { - 'deny_assignment_name': {'key': 'denyAssignmentName', 'type': 'str'}, - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'gdpr_export_principal_id': {'key': 'gdprExportPrincipalId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(DenyAssignmentFilter, self).__init__(**kwargs) - self.deny_assignment_name = kwargs.get('deny_assignment_name', None) - self.principal_id = kwargs.get('principal_id', None) - self.gdpr_export_principal_id = kwargs.get('gdpr_export_principal_id', None) - - -class DenyAssignmentListResult(msrest.serialization.Model): - """Deny assignment list operation result. - - :param value: Deny assignment list. - :type value: list[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[DenyAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(DenyAssignmentListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class DenyAssignmentPermission(msrest.serialization.Model): - """Deny assignment permissions. - - :param actions: Actions to which the deny assignment does not grant access. - :type actions: list[str] - :param not_actions: Actions to exclude from that the deny assignment does not grant access. - :type not_actions: list[str] - :param data_actions: Data actions to which the deny assignment does not grant access. - :type data_actions: list[str] - :param not_data_actions: Data actions to exclude from that the deny assignment does not grant - access. - :type not_data_actions: list[str] - """ - - _attribute_map = { - 'actions': {'key': 'actions', 'type': '[str]'}, - 'not_actions': {'key': 'notActions', 'type': '[str]'}, - 'data_actions': {'key': 'dataActions', 'type': '[str]'}, - 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(DenyAssignmentPermission, self).__init__(**kwargs) - self.actions = kwargs.get('actions', None) - self.not_actions = kwargs.get('not_actions', None) - self.data_actions = kwargs.get('data_actions', None) - self.not_data_actions = kwargs.get('not_data_actions', None) - - -class ErrorAdditionalInfo(msrest.serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(msrest.serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.authorization.v2018_07_01_preview.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.mgmt.authorization.v2018_07_01_preview.models.ErrorAdditionalInfo] - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(msrest.serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2018_07_01_preview.models.ErrorDetail - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class Principal(msrest.serialization.Model): - """The name of the entity last modified it. - - :param id: The id of the principal made changes. - :type id: str - :param display_name: The name of the principal made changes. - :type display_name: str - :param type: Type of principal such as user , group etc. - :type type: str - :param email: Email of principal. - :type email: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Principal, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.display_name = kwargs.get('display_name', None) - self.type = kwargs.get('type', None) - self.email = kwargs.get('email', None) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_models_py3.py index 50386332c7c..7cdcc357e35 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_models_py3.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -6,13 +7,16 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import List, Optional +from typing import List, Optional, TYPE_CHECKING -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class DenyAssignment(msrest.serialization.Model): + +class DenyAssignment(_serialization.Model): # pylint: disable=too-many-instance-attributes """Deny Assignment. Variables are only populated by the server, and will be ignored when sending a request. @@ -23,45 +27,46 @@ class DenyAssignment(msrest.serialization.Model): :vartype name: str :ivar type: The deny assignment type. :vartype type: str - :param deny_assignment_name: The display name of the deny assignment. - :type deny_assignment_name: str - :param description: The description of the deny assignment. - :type description: str - :param permissions: An array of permissions that are denied by the deny assignment. - :type permissions: + :ivar deny_assignment_name: The display name of the deny assignment. + :vartype deny_assignment_name: str + :ivar description: The description of the deny assignment. + :vartype description: str + :ivar permissions: An array of permissions that are denied by the deny assignment. + :vartype permissions: list[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignmentPermission] - :param scope: The deny assignment scope. - :type scope: str - :param do_not_apply_to_child_scopes: Determines if the deny assignment applies to child scopes. + :ivar scope: The deny assignment scope. + :vartype scope: str + :ivar do_not_apply_to_child_scopes: Determines if the deny assignment applies to child scopes. Default value is false. - :type do_not_apply_to_child_scopes: bool - :param principals: Array of principals to which the deny assignment applies. - :type principals: list[~azure.mgmt.authorization.v2018_07_01_preview.models.Principal] - :param exclude_principals: Array of principals to which the deny assignment does not apply. - :type exclude_principals: list[~azure.mgmt.authorization.v2018_07_01_preview.models.Principal] - :param is_system_protected: Specifies whether this deny assignment was created by Azure and + :vartype do_not_apply_to_child_scopes: bool + :ivar principals: Array of principals to which the deny assignment applies. + :vartype principals: list[~azure.mgmt.authorization.v2018_07_01_preview.models.Principal] + :ivar exclude_principals: Array of principals to which the deny assignment does not apply. + :vartype exclude_principals: + list[~azure.mgmt.authorization.v2018_07_01_preview.models.Principal] + :ivar is_system_protected: Specifies whether this deny assignment was created by Azure and cannot be edited or deleted. - :type is_system_protected: bool + :vartype is_system_protected: bool """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'deny_assignment_name': {'key': 'properties.denyAssignmentName', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'permissions': {'key': 'properties.permissions', 'type': '[DenyAssignmentPermission]'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'do_not_apply_to_child_scopes': {'key': 'properties.doNotApplyToChildScopes', 'type': 'bool'}, - 'principals': {'key': 'properties.principals', 'type': '[Principal]'}, - 'exclude_principals': {'key': 'properties.excludePrincipals', 'type': '[Principal]'}, - 'is_system_protected': {'key': 'properties.isSystemProtected', 'type': 'bool'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "deny_assignment_name": {"key": "properties.denyAssignmentName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "permissions": {"key": "properties.permissions", "type": "[DenyAssignmentPermission]"}, + "scope": {"key": "properties.scope", "type": "str"}, + "do_not_apply_to_child_scopes": {"key": "properties.doNotApplyToChildScopes", "type": "bool"}, + "principals": {"key": "properties.principals", "type": "[Principal]"}, + "exclude_principals": {"key": "properties.excludePrincipals", "type": "[Principal]"}, + "is_system_protected": {"key": "properties.isSystemProtected", "type": "bool"}, } def __init__( @@ -69,15 +74,37 @@ def __init__( *, deny_assignment_name: Optional[str] = None, description: Optional[str] = None, - permissions: Optional[List["DenyAssignmentPermission"]] = None, + permissions: Optional[List["_models.DenyAssignmentPermission"]] = None, scope: Optional[str] = None, do_not_apply_to_child_scopes: Optional[bool] = None, - principals: Optional[List["Principal"]] = None, - exclude_principals: Optional[List["Principal"]] = None, + principals: Optional[List["_models.Principal"]] = None, + exclude_principals: Optional[List["_models.Principal"]] = None, is_system_protected: Optional[bool] = None, **kwargs ): - super(DenyAssignment, self).__init__(**kwargs) + """ + :keyword deny_assignment_name: The display name of the deny assignment. + :paramtype deny_assignment_name: str + :keyword description: The description of the deny assignment. + :paramtype description: str + :keyword permissions: An array of permissions that are denied by the deny assignment. + :paramtype permissions: + list[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignmentPermission] + :keyword scope: The deny assignment scope. + :paramtype scope: str + :keyword do_not_apply_to_child_scopes: Determines if the deny assignment applies to child + scopes. Default value is false. + :paramtype do_not_apply_to_child_scopes: bool + :keyword principals: Array of principals to which the deny assignment applies. + :paramtype principals: list[~azure.mgmt.authorization.v2018_07_01_preview.models.Principal] + :keyword exclude_principals: Array of principals to which the deny assignment does not apply. + :paramtype exclude_principals: + list[~azure.mgmt.authorization.v2018_07_01_preview.models.Principal] + :keyword is_system_protected: Specifies whether this deny assignment was created by Azure and + cannot be edited or deleted. + :paramtype is_system_protected: bool + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -91,23 +118,23 @@ def __init__( self.is_system_protected = is_system_protected -class DenyAssignmentFilter(msrest.serialization.Model): +class DenyAssignmentFilter(_serialization.Model): """Deny Assignments filter. - :param deny_assignment_name: Return deny assignment with specified name. - :type deny_assignment_name: str - :param principal_id: Return all deny assignments where the specified principal is listed in the + :ivar deny_assignment_name: Return deny assignment with specified name. + :vartype deny_assignment_name: str + :ivar principal_id: Return all deny assignments where the specified principal is listed in the principals list of deny assignments. - :type principal_id: str - :param gdpr_export_principal_id: Return all deny assignments where the specified principal is + :vartype principal_id: str + :ivar gdpr_export_principal_id: Return all deny assignments where the specified principal is listed either in the principals list or exclude principals list of deny assignments. - :type gdpr_export_principal_id: str + :vartype gdpr_export_principal_id: str """ _attribute_map = { - 'deny_assignment_name': {'key': 'denyAssignmentName', 'type': 'str'}, - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'gdpr_export_principal_id': {'key': 'gdprExportPrincipalId', 'type': 'str'}, + "deny_assignment_name": {"key": "denyAssignmentName", "type": "str"}, + "principal_id": {"key": "principalId", "type": "str"}, + "gdpr_export_principal_id": {"key": "gdprExportPrincipalId", "type": "str"}, } def __init__( @@ -118,57 +145,69 @@ def __init__( gdpr_export_principal_id: Optional[str] = None, **kwargs ): - super(DenyAssignmentFilter, self).__init__(**kwargs) + """ + :keyword deny_assignment_name: Return deny assignment with specified name. + :paramtype deny_assignment_name: str + :keyword principal_id: Return all deny assignments where the specified principal is listed in + the principals list of deny assignments. + :paramtype principal_id: str + :keyword gdpr_export_principal_id: Return all deny assignments where the specified principal is + listed either in the principals list or exclude principals list of deny assignments. + :paramtype gdpr_export_principal_id: str + """ + super().__init__(**kwargs) self.deny_assignment_name = deny_assignment_name self.principal_id = principal_id self.gdpr_export_principal_id = gdpr_export_principal_id -class DenyAssignmentListResult(msrest.serialization.Model): +class DenyAssignmentListResult(_serialization.Model): """Deny assignment list operation result. - :param value: Deny assignment list. - :type value: list[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Deny assignment list. + :vartype value: list[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[DenyAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[DenyAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["DenyAssignment"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.DenyAssignment"]] = None, next_link: Optional[str] = None, **kwargs ): - super(DenyAssignmentListResult, self).__init__(**kwargs) + """ + :keyword value: Deny assignment list. + :paramtype value: list[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class DenyAssignmentPermission(msrest.serialization.Model): +class DenyAssignmentPermission(_serialization.Model): """Deny assignment permissions. - :param actions: Actions to which the deny assignment does not grant access. - :type actions: list[str] - :param not_actions: Actions to exclude from that the deny assignment does not grant access. - :type not_actions: list[str] - :param data_actions: Data actions to which the deny assignment does not grant access. - :type data_actions: list[str] - :param not_data_actions: Data actions to exclude from that the deny assignment does not grant + :ivar actions: Actions to which the deny assignment does not grant access. + :vartype actions: list[str] + :ivar not_actions: Actions to exclude from that the deny assignment does not grant access. + :vartype not_actions: list[str] + :ivar data_actions: Data actions to which the deny assignment does not grant access. + :vartype data_actions: list[str] + :ivar not_data_actions: Data actions to exclude from that the deny assignment does not grant access. - :type not_data_actions: list[str] + :vartype not_data_actions: list[str] """ _attribute_map = { - 'actions': {'key': 'actions', 'type': '[str]'}, - 'not_actions': {'key': 'notActions', 'type': '[str]'}, - 'data_actions': {'key': 'dataActions', 'type': '[str]'}, - 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, + "actions": {"key": "actions", "type": "[str]"}, + "not_actions": {"key": "notActions", "type": "[str]"}, + "data_actions": {"key": "dataActions", "type": "[str]"}, + "not_data_actions": {"key": "notDataActions", "type": "[str]"}, } def __init__( @@ -180,14 +219,25 @@ def __init__( not_data_actions: Optional[List[str]] = None, **kwargs ): - super(DenyAssignmentPermission, self).__init__(**kwargs) + """ + :keyword actions: Actions to which the deny assignment does not grant access. + :paramtype actions: list[str] + :keyword not_actions: Actions to exclude from that the deny assignment does not grant access. + :paramtype not_actions: list[str] + :keyword data_actions: Data actions to which the deny assignment does not grant access. + :paramtype data_actions: list[str] + :keyword not_data_actions: Data actions to exclude from that the deny assignment does not grant + access. + :paramtype not_data_actions: list[str] + """ + super().__init__(**kwargs) self.actions = actions self.not_actions = not_actions self.data_actions = data_actions self.not_data_actions = not_data_actions -class ErrorAdditionalInfo(msrest.serialization.Model): +class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. @@ -195,29 +245,27 @@ class ErrorAdditionalInfo(msrest.serialization.Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: any + :vartype info: JSON """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None -class ErrorDetail(msrest.serialization.Model): +class ErrorDetail(_serialization.Model): """The error detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -236,26 +284,24 @@ class ErrorDetail(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -263,57 +309,66 @@ def __init__( self.additional_info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2018_07_01_preview.models.ErrorDetail + :ivar error: The error object. + :vartype error: ~azure.mgmt.authorization.v2018_07_01_preview.models.ErrorDetail """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, + "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__( - self, - *, - error: Optional["ErrorDetail"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.authorization.v2018_07_01_preview.models.ErrorDetail + """ + super().__init__(**kwargs) self.error = error -class Principal(msrest.serialization.Model): +class Principal(_serialization.Model): """The name of the entity last modified it. - :param id: The id of the principal made changes. - :type id: str - :param display_name: The name of the principal made changes. - :type display_name: str - :param type: Type of principal such as user , group etc. - :type type: str - :param email: Email of principal. - :type email: str + :ivar id: The id of the principal made changes. + :vartype id: str + :ivar display_name: The name of the principal made changes. + :vartype display_name: str + :ivar type: Type of principal such as user , group etc. + :vartype type: str + :ivar email: Email of principal. + :vartype email: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "email": {"key": "email", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin display_name: Optional[str] = None, type: Optional[str] = None, email: Optional[str] = None, **kwargs ): - super(Principal, self).__init__(**kwargs) + """ + :keyword id: The id of the principal made changes. + :paramtype id: str + :keyword display_name: The name of the principal made changes. + :paramtype display_name: str + :keyword type: Type of principal such as user , group etc. + :paramtype type: str + :keyword email: Email of principal. + :paramtype email: str + """ + super().__init__(**kwargs) self.id = id self.display_name = display_name self.type = type diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/__init__.py index 7b0c7bab2bc..590e6d32085 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/__init__.py @@ -8,6 +8,12 @@ from ._deny_assignments_operations import DenyAssignmentsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'DenyAssignmentsOperations', + "DenyAssignmentsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/_deny_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/_deny_assignments_operations.py index 1c22aa2904b..0f13a8bdb89 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/_deny_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/_deny_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,68 +6,263 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/denyAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceProviderNamespace": _SERIALIZER.url( + "resource_provider_namespace", resource_provider_namespace, "str", skip_quote=True + ), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_group_request( + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/denyAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/denyAssignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, deny_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "denyAssignmentId": _SERIALIZER.url("deny_assignment_id", deny_assignment_id, "str"), + } -class DenyAssignmentsOperations(object): - """DenyAssignmentsOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_07_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(deny_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{denyAssignmentId}") + path_format_arguments = { + "denyAssignmentId": _SERIALIZER.url("deny_assignment_id", deny_assignment_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/denyAssignments") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DenyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_07_01_preview.AuthorizationManagementClient`'s + :attr:`deny_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_resource( self, - resource_group_name, # type: str - resource_provider_namespace, # type: str - parent_resource_path, # type: str - resource_type, # type: str - resource_name, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.DenyAssignmentListResult"] + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.DenyAssignment"]: """Gets deny assignments for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get deny assignments for. + :param resource_name: The name of the resource to get deny assignments for. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny @@ -77,53 +273,60 @@ def list_for_resource( returns not only those deny assignments that contain the specified principal is the Principals list but also those deny assignments that contain the specified principal is the ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny - assignment name and description properties are returned. + assignment name and description properties are returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DenyAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('DenyAssignmentListResult', pipeline_response) + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -132,31 +335,30 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/denyAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + @distributed_trace def list_for_resource_group( - self, - resource_group_name, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.DenyAssignmentListResult"] + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.DenyAssignment"]: """Gets deny assignments for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny @@ -167,49 +369,56 @@ def list_for_resource_group( returns not only those deny assignments that contain the specified principal is the Principals list but also those deny assignments that contain the specified principal is the ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny - assignment name and description properties are returned. + assignment name and description properties are returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DenyAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('DenyAssignmentListResult', pipeline_response) + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -218,27 +427,24 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/denyAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) - def list( - self, - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.DenyAssignmentListResult"] + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.DenyAssignment"]: """Gets all deny assignments for the subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny @@ -250,48 +456,55 @@ def list( returns not only those deny assignments that contain the specified principal is the Principals list but also those deny assignments that contain the specified principal is the ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny - assignment name and description properties are returned. + assignment name and description properties are returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DenyAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('DenyAssignmentListResult', pipeline_response) + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -300,149 +513,146 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/denyAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) - def get( - self, - scope, # type: str - deny_assignment_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.DenyAssignment" + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + + @distributed_trace + def get(self, scope: str, deny_assignment_id: str, **kwargs: Any) -> _models.DenyAssignment: """Get the specified deny assignment. - :param scope: The scope of the deny assignment. + :param scope: The scope of the deny assignment. Required. :type scope: str - :param deny_assignment_id: The ID of the deny assignment to get. + :param deny_assignment_id: The ID of the deny assignment to get. Required. :type deny_assignment_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DenyAssignment, or the result of cls(response) + :return: DenyAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'denyAssignmentId': self._serialize.url("deny_assignment_id", deny_assignment_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignment] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + deny_assignment_id=deny_assignment_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DenyAssignment', pipeline_response) + deserialized = self._deserialize("DenyAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId}'} # type: ignore - def get_by_id( - self, - deny_assignment_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.DenyAssignment" + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId}"} # type: ignore + + @distributed_trace + def get_by_id(self, deny_assignment_id: str, **kwargs: Any) -> _models.DenyAssignment: """Gets a deny assignment by ID. :param deny_assignment_id: The fully qualified deny assignment ID. For example, use the format, /subscriptions/{guid}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} for subscription level deny assignments, or /providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} for tenant level deny - assignments. + assignments. Required. :type deny_assignment_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DenyAssignment, or the result of cls(response) + :return: DenyAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'denyAssignmentId': self._serialize.url("deny_assignment_id", deny_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignment] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_by_id_request( + deny_assignment_id=deny_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DenyAssignment', pipeline_response) + deserialized = self._deserialize("DenyAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{denyAssignmentId}'} # type: ignore + get_by_id.metadata = {"url": "/{denyAssignmentId}"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.DenyAssignmentListResult"] + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.DenyAssignment"]: """Gets deny assignments for a scope. - :param scope: The scope of the deny assignments. + :param scope: The scope of the deny assignments. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny @@ -453,48 +663,55 @@ def list_for_scope( returns not only those deny assignments that contain the specified principal is the Principals list but also those deny assignments that contain the specified principal is the ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny - assignment name and description properties are returned. + assignment name and description properties are returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DenyAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_07_01_preview.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DenyAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('DenyAssignmentListResult', pipeline_response) + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -503,17 +720,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/denyAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_07_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/__init__.py index ae11ad3e4d9..9eb8d3ec28c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AuthorizationManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_authorization_management_client.py index 44241ef6b92..2b5fe0b7c6c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_authorization_management_client.py @@ -6,73 +6,82 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import RoleAssignmentsOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import RoleAssignmentsOperations -from . import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + assignments. A role assignment grants access to Azure Active Directory users. :ivar role_assignments: RoleAssignmentsOperations operations - :vartype role_assignments: azure.mgmt.authorization.v2018_09_01_preview.operations.RoleAssignmentsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype role_assignments: + azure.mgmt.authorization.v2018_09_01_preview.operations.RoleAssignmentsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-09-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.role_assignments = RoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_configuration.py index 4733e535b56..511ac76fb69 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_configuration.py @@ -6,66 +6,64 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-09-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2018-09-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-09-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_metadata.json index bdd80a44a1a..90923eb42d7 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_metadata.json +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_metadata.json @@ -5,25 +5,25 @@ "name": "AuthorizationManagementClient", "filename": "_authorization_management_client", "description": "Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, "azure_arm": true, "has_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -54,7 +54,7 @@ "required": false }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -74,7 +74,7 @@ "required": false }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -91,11 +91,10 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "role_assignments": "RoleAssignmentsOperations" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_version.py index 48944bf3938..cac9f5d10f8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/__init__.py index ffc49d028e4..dd28625b36f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._authorization_management_client import AuthorizationManagementClient -__all__ = ['AuthorizationManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_authorization_management_client.py index 72b80ff6ea1..a80803a2efe 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_authorization_management_client.py @@ -6,69 +6,82 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import RoleAssignmentsOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import RoleAssignmentsOperations -from .. import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + assignments. A role assignment grants access to Azure Active Directory users. :ivar role_assignments: RoleAssignmentsOperations operations - :vartype role_assignments: azure.mgmt.authorization.v2018_09_01_preview.aio.operations.RoleAssignmentsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype role_assignments: + azure.mgmt.authorization.v2018_09_01_preview.aio.operations.RoleAssignmentsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2018-09-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.role_assignments = RoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_configuration.py index 73519a2fc10..caf1b9fdc96 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,49 +19,48 @@ from azure.core.credentials_async import AsyncTokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2018-09-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2018-09-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2018-09-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/__init__.py index b9e31fd2db9..3b7b5d5c272 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/__init__.py @@ -8,6 +8,12 @@ from ._role_assignments_operations import RoleAssignmentsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RoleAssignmentsOperations', + "RoleAssignmentsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/_role_assignments_operations.py index 0d07516a09a..c8e52cba4b8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/_role_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/aio/operations/_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,42 +6,65 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_assignments_operations import ( + build_create_by_id_request, + build_create_request, + build_delete_by_id_request, + build_delete_request, + build_get_by_id_request, + build_get_request, + build_list_for_resource_group_request, + build_list_for_resource_request, + build_list_for_scope_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentsOperations: - """RoleAssignmentsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_09_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_09_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_resource( self, resource_group_name: str, @@ -50,68 +74,76 @@ def list_for_resource( resource_name: str, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + ) -> AsyncIterable["_models.RoleAssignment"]: """Gets role assignments for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get role assignments for. + :param resource_name: The name of the resource to get role assignments for. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -120,76 +152,83 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace def list_for_resource_group( - self, - resource_group_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """Gets role assignments for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -198,88 +237,92 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def delete( - self, - scope: str, - role_assignment_name: str, - **kwargs: Any - ) -> Optional["_models.RoleAssignment"]: + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace_async + async def delete(self, scope: str, role_assignment_name: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. - :param scope: The scope of the role assignment to delete. + :param scope: The scope of the role assignment to delete. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to delete. + :param role_assignment_name: The name of the role assignment to delete. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload async def create( self, scope: str, role_assignment_name: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignment": + ) -> _models.RoleAssignment: """Creates a role assignment. :param scope: The scope of the role assignment to create. The scope can be any REST resource @@ -287,345 +330,490 @@ async def create( '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to create. It can be any valid - GUID. + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - async def get( - self, - scope: str, - role_assignment_name: str, - **kwargs: Any - ) -> "_models.RoleAssignment": + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, role_assignment_name: str, **kwargs: Any) -> _models.RoleAssignment: """Get the specified role assignment. - :param scope: The scope of the role assignment. + :param scope: The scope of the role assignment. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to get. + :param role_assignment_name: The name of the role assignment to get. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - async def delete_by_id( - self, - role_id: str, - **kwargs: Any - ) -> Optional["_models.RoleAssignment"]: + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace_async + async def delete_by_id(self, role_id: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. - :param role_id: The ID of the role assignment to delete. + :param role_id: The ID of the role assignment to delete. Required. :type role_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_id.metadata = {'url': '/{roleId}'} # type: ignore + delete_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @overload async def create_by_id( self, role_id: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignment": + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, role_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, role_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: """Creates a role assignment by ID. - :param role_id: The ID of the role assignment to create. + :param role_id: The ID of the role assignment to create. Required. :type role_id: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_id=role_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_by_id.metadata = {'url': '/{roleId}'} # type: ignore - async def get_by_id( - self, - role_id: str, - **kwargs: Any - ) -> "_models.RoleAssignment": + create_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, role_id: str, **kwargs: Any) -> _models.RoleAssignment: """Gets a role assignment by ID. - :param role_id: The ID of the role assignment to get. + :param role_id: The ID of the role assignment to get. Required. :type role_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleId}'} # type: ignore - def list( - self, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + get_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.RoleAssignment"]: """Gets all role assignments for the subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -634,75 +822,81 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """Gets role assignments for a scope. - :param scope: The scope of the role assignments. + :param scope: The scope of the role assignments. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -711,17 +905,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/__init__.py index 83bed740131..c44ad4c485a 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/__init__.py @@ -6,34 +6,28 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ErrorAdditionalInfo - from ._models_py3 import ErrorDetail - from ._models_py3 import ErrorResponse - from ._models_py3 import RoleAssignment - from ._models_py3 import RoleAssignmentCreateParameters - from ._models_py3 import RoleAssignmentFilter - from ._models_py3 import RoleAssignmentListResult -except (SyntaxError, ImportError): - from ._models import ErrorAdditionalInfo # type: ignore - from ._models import ErrorDetail # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import RoleAssignment # type: ignore - from ._models import RoleAssignmentCreateParameters # type: ignore - from ._models import RoleAssignmentFilter # type: ignore - from ._models import RoleAssignmentListResult # type: ignore +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import RoleAssignment +from ._models_py3 import RoleAssignmentCreateParameters +from ._models_py3 import RoleAssignmentFilter +from ._models_py3 import RoleAssignmentListResult -from ._authorization_management_client_enums import ( - PrincipalType, -) +from ._authorization_management_client_enums import PrincipalType +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ErrorAdditionalInfo', - 'ErrorDetail', - 'ErrorResponse', - 'RoleAssignment', - 'RoleAssignmentCreateParameters', - 'RoleAssignmentFilter', - 'RoleAssignmentListResult', - 'PrincipalType', + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "RoleAssignment", + "RoleAssignmentCreateParameters", + "RoleAssignmentFilter", + "RoleAssignmentListResult", + "PrincipalType", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_authorization_management_client_enums.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_authorization_management_client_enums.py index c60129f05bc..4519b342017 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_authorization_management_client_enums.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_authorization_management_client_enums.py @@ -6,29 +6,12 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class PrincipalType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The principal type of the assigned principal ID. - """ +class PrincipalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The principal type of the assigned principal ID.""" USER = "User" GROUP = "Group" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_models.py deleted file mode 100644 index e7eec846993..00000000000 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_models.py +++ /dev/null @@ -1,247 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class ErrorAdditionalInfo(msrest.serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(msrest.serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.authorization.v2018_09_01_preview.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.mgmt.authorization.v2018_09_01_preview.models.ErrorAdditionalInfo] - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(msrest.serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2018_09_01_preview.models.ErrorDetail - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class RoleAssignment(msrest.serialization.Model): - """Role Assignments. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role assignment ID. - :vartype id: str - :ivar name: The role assignment name. - :vartype name: str - :ivar type: The role assignment type. - :vartype type: str - :param scope: The role assignment scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup". - :type principal_type: str or ~azure.mgmt.authorization.v2018_09_01_preview.models.PrincipalType - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignment, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = kwargs.get('scope', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.principal_id = kwargs.get('principal_id', None) - self.principal_type = kwargs.get('principal_type', None) - self.can_delegate = kwargs.get('can_delegate', None) - - -class RoleAssignmentCreateParameters(msrest.serialization.Model): - """Role assignment create parameters. - - All required parameters must be populated in order to send to Azure. - - :param role_definition_id: Required. The role definition ID used in the role assignment. - :type role_definition_id: str - :param principal_id: Required. The principal ID assigned to the role. This maps to the ID - inside the Active Directory. It can point to a user, service principal, or security group. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup". - :type principal_type: str or ~azure.mgmt.authorization.v2018_09_01_preview.models.PrincipalType - :param can_delegate: The delegation flag used for creating a role assignment. - :type can_delegate: bool - """ - - _validation = { - 'role_definition_id': {'required': True}, - 'principal_id': {'required': True}, - } - - _attribute_map = { - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentCreateParameters, self).__init__(**kwargs) - self.role_definition_id = kwargs['role_definition_id'] - self.principal_id = kwargs['principal_id'] - self.principal_type = kwargs.get('principal_type', None) - self.can_delegate = kwargs.get('can_delegate', None) - - -class RoleAssignmentFilter(msrest.serialization.Model): - """Role Assignments filter. - - :param principal_id: Returns role assignment of the specific principal. - :type principal_id: str - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool - """ - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'can_delegate': {'key': 'canDelegate', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentFilter, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - self.can_delegate = kwargs.get('can_delegate', None) - - -class RoleAssignmentListResult(msrest.serialization.Model): - """Role assignment list operation result. - - :param value: Role assignment list. - :type value: list[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_models_py3.py index a6dbf45a8ab..78dc3345e48 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_models_py3.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -6,15 +7,16 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import List, Optional, Union +from typing import List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization -from ._authorization_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class ErrorAdditionalInfo(msrest.serialization.Model): +class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. @@ -22,29 +24,27 @@ class ErrorAdditionalInfo(msrest.serialization.Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: any + :vartype info: JSON """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None -class ErrorDetail(msrest.serialization.Model): +class ErrorDetail(_serialization.Model): """The error detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -63,26 +63,24 @@ class ErrorDetail(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -90,28 +88,27 @@ def __init__( self.additional_info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2018_09_01_preview.models.ErrorDetail + :ivar error: The error object. + :vartype error: ~azure.mgmt.authorization.v2018_09_01_preview.models.ErrorDetail """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, + "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__( - self, - *, - error: Optional["ErrorDetail"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.authorization.v2018_09_01_preview.models.ErrorDetail + """ + super().__init__(**kwargs) self.error = error -class RoleAssignment(msrest.serialization.Model): +class RoleAssignment(_serialization.Model): """Role Assignments. Variables are only populated by the server, and will be ignored when sending a request. @@ -122,34 +119,35 @@ class RoleAssignment(msrest.serialization.Model): :vartype name: str :ivar type: The role assignment type. :vartype type: str - :param scope: The role assignment scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup". - :type principal_type: str or ~azure.mgmt.authorization.v2018_09_01_preview.models.PrincipalType - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool + :ivar scope: The role assignment scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", and "ForeignGroup". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2018_09_01_preview.models.PrincipalType + :ivar can_delegate: The Delegation flag for the role assignment. + :vartype can_delegate: bool """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "can_delegate": {"key": "properties.canDelegate", "type": "bool"}, } def __init__( @@ -158,11 +156,25 @@ def __init__( scope: Optional[str] = None, role_definition_id: Optional[str] = None, principal_id: Optional[str] = None, - principal_type: Optional[Union[str, "PrincipalType"]] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, can_delegate: Optional[bool] = None, **kwargs ): - super(RoleAssignment, self).__init__(**kwargs) + """ + :keyword scope: The role assignment scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", and "ForeignGroup". + :paramtype principal_type: str or + ~azure.mgmt.authorization.v2018_09_01_preview.models.PrincipalType + :keyword can_delegate: The Delegation flag for the role assignment. + :paramtype can_delegate: bool + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -173,33 +185,34 @@ def __init__( self.can_delegate = can_delegate -class RoleAssignmentCreateParameters(msrest.serialization.Model): +class RoleAssignmentCreateParameters(_serialization.Model): """Role assignment create parameters. All required parameters must be populated in order to send to Azure. - :param role_definition_id: Required. The role definition ID used in the role assignment. - :type role_definition_id: str - :param principal_id: Required. The principal ID assigned to the role. This maps to the ID - inside the Active Directory. It can point to a user, service principal, or security group. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup". - :type principal_type: str or ~azure.mgmt.authorization.v2018_09_01_preview.models.PrincipalType - :param can_delegate: The delegation flag used for creating a role assignment. - :type can_delegate: bool + :ivar role_definition_id: The role definition ID used in the role assignment. Required. + :vartype role_definition_id: str + :ivar principal_id: The principal ID assigned to the role. This maps to the ID inside the + Active Directory. It can point to a user, service principal, or security group. Required. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", and "ForeignGroup". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2018_09_01_preview.models.PrincipalType + :ivar can_delegate: The delegation flag used for creating a role assignment. + :vartype can_delegate: bool """ _validation = { - 'role_definition_id': {'required': True}, - 'principal_id': {'required': True}, + "role_definition_id": {"required": True}, + "principal_id": {"required": True}, } _attribute_map = { - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "can_delegate": {"key": "properties.canDelegate", "type": "bool"}, } def __init__( @@ -207,64 +220,79 @@ def __init__( *, role_definition_id: str, principal_id: str, - principal_type: Optional[Union[str, "PrincipalType"]] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, can_delegate: Optional[bool] = None, **kwargs ): - super(RoleAssignmentCreateParameters, self).__init__(**kwargs) + """ + :keyword role_definition_id: The role definition ID used in the role assignment. Required. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID assigned to the role. This maps to the ID inside the + Active Directory. It can point to a user, service principal, or security group. Required. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", and "ForeignGroup". + :paramtype principal_type: str or + ~azure.mgmt.authorization.v2018_09_01_preview.models.PrincipalType + :keyword can_delegate: The delegation flag used for creating a role assignment. + :paramtype can_delegate: bool + """ + super().__init__(**kwargs) self.role_definition_id = role_definition_id self.principal_id = principal_id self.principal_type = principal_type self.can_delegate = can_delegate -class RoleAssignmentFilter(msrest.serialization.Model): +class RoleAssignmentFilter(_serialization.Model): """Role Assignments filter. - :param principal_id: Returns role assignment of the specific principal. - :type principal_id: str - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool + :ivar principal_id: Returns role assignment of the specific principal. + :vartype principal_id: str + :ivar can_delegate: The Delegation flag for the role assignment. + :vartype can_delegate: bool """ _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'can_delegate': {'key': 'canDelegate', 'type': 'bool'}, + "principal_id": {"key": "principalId", "type": "str"}, + "can_delegate": {"key": "canDelegate", "type": "bool"}, } - def __init__( - self, - *, - principal_id: Optional[str] = None, - can_delegate: Optional[bool] = None, - **kwargs - ): - super(RoleAssignmentFilter, self).__init__(**kwargs) + def __init__(self, *, principal_id: Optional[str] = None, can_delegate: Optional[bool] = None, **kwargs): + """ + :keyword principal_id: Returns role assignment of the specific principal. + :paramtype principal_id: str + :keyword can_delegate: The Delegation flag for the role assignment. + :paramtype can_delegate: bool + """ + super().__init__(**kwargs) self.principal_id = principal_id self.can_delegate = can_delegate -class RoleAssignmentListResult(msrest.serialization.Model): +class RoleAssignmentListResult(_serialization.Model): """Role assignment list operation result. - :param value: Role assignment list. - :type value: list[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Role assignment list. + :vartype value: list[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["RoleAssignment"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.RoleAssignment"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleAssignmentListResult, self).__init__(**kwargs) + """ + :keyword value: Role assignment list. + :paramtype value: list[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/__init__.py index b9e31fd2db9..3b7b5d5c272 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/__init__.py @@ -8,6 +8,12 @@ from ._role_assignments_operations import RoleAssignmentsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RoleAssignmentsOperations', + "RoleAssignmentsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/_role_assignments_operations.py index 5c0f8f71739..21dc63ea170 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/_role_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_09_01_preview/operations/_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,118 +6,424 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceProviderNamespace": _SERIALIZER.url( + "resource_provider_namespace", resource_provider_namespace, "str", skip_quote=True + ), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_group_request( + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request(role_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleId}") + path_format_arguments = { + "roleId": _SERIALIZER.url("role_id", role_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_by_id_request(role_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleId}") + path_format_arguments = { + "roleId": _SERIALIZER.url("role_id", role_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class RoleAssignmentsOperations(object): - """RoleAssignmentsOperations operations. + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2018_09_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +def build_get_by_id_request(role_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleId}") + path_format_arguments = { + "roleId": _SERIALIZER.url("role_id", role_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2018_09_01_preview.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_resource( self, - resource_group_name, # type: str - resource_provider_namespace, # type: str - parent_resource_path, # type: str - resource_type, # type: str - resource_name, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """Gets role assignments for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get role assignments for. + :param resource_name: The name of the resource to get role assignments for. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -125,77 +432,83 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_resource_group( - self, - resource_group_name, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """Gets role assignments for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -204,90 +517,92 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) - def delete( - self, - scope, # type: str - role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleAssignment"] + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace + def delete(self, scope: str, role_assignment_name: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. - :param scope: The scope of the role assignment to delete. + :param scope: The scope of the role assignment to delete. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to delete. + :param role_assignment_name: The name of the role assignment to delete. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload def create( self, - scope, # type: str - role_assignment_name, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + scope: str, + role_assignment_name: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: """Creates a role assignment. :param scope: The scope of the role assignment to create. The scope can be any REST resource @@ -295,350 +610,490 @@ def create( '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to create. It can be any valid - GUID. + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - def get( - self, - scope, # type: str - role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace + def get(self, scope: str, role_assignment_name: str, **kwargs: Any) -> _models.RoleAssignment: """Get the specified role assignment. - :param scope: The scope of the role assignment. + :param scope: The scope of the role assignment. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to get. + :param role_assignment_name: The name of the role assignment to get. Required. :type role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore - def delete_by_id( - self, - role_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleAssignment"] + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace + def delete_by_id(self, role_id: str, **kwargs: Any) -> Optional[_models.RoleAssignment]: """Deletes a role assignment. - :param role_id: The ID of the role assignment to delete. + :param role_id: The ID of the role assignment to delete. Required. :type role_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_id.metadata = {'url': '/{roleId}'} # type: ignore + delete_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @overload def create_by_id( self, - role_id, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + role_id: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_by_id( + self, role_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_by_id( + self, role_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: """Creates a role assignment by ID. - :param role_id: The ID of the role assignment to create. + :param role_id: The ID of the role assignment to create. Required. :type role_id: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_id=role_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_by_id.metadata = {'url': '/{roleId}'} # type: ignore - def get_by_id( - self, - role_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + create_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace + def get_by_id(self, role_id: str, **kwargs: Any) -> _models.RoleAssignment: """Gets a role assignment by ID. - :param role_id: The ID of the role assignment to get. + :param role_id: The ID of the role assignment to get. Required. :type role_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleId}'} # type: ignore - def list( - self, - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + get_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.RoleAssignment"]: """Gets all role assignments for the subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -647,76 +1102,81 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """Gets role assignments for a scope. - :param scope: The scope of the role assignments. + :param scope: The scope of the role assignments. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2018_09_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-09-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -725,17 +1185,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/__init__.py index ae11ad3e4d9..9eb8d3ec28c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AuthorizationManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_authorization_management_client.py index 7f4540945ce..1083218a30b 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_authorization_management_client.py @@ -6,73 +6,82 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import RoleAssignmentMetricsOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import RoleAssignmentMetricsOperations -from . import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + assignments. A role assignment grants access to Azure Active Directory users. :ivar role_assignment_metrics: RoleAssignmentMetricsOperations operations - :vartype role_assignment_metrics: azure.mgmt.authorization.v2019_08_01_preview.operations.RoleAssignmentMetricsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype role_assignment_metrics: + azure.mgmt.authorization.v2019_08_01_preview.operations.RoleAssignmentMetricsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2019-08-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.role_assignment_metrics = RoleAssignmentMetricsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_configuration.py index b98b95f68da..8724ba0d3d5 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_configuration.py @@ -6,66 +6,64 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2019-08-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2019-08-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2019-08-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_metadata.json index 9fc9a49ce49..77aac5fc650 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_metadata.json +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_metadata.json @@ -5,25 +5,25 @@ "name": "AuthorizationManagementClient", "filename": "_authorization_management_client", "description": "Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, "azure_arm": true, "has_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -54,7 +54,7 @@ "required": false }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -74,7 +74,7 @@ "required": false }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -91,11 +91,10 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "role_assignment_metrics": "RoleAssignmentMetricsOperations" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_version.py index 48944bf3938..cac9f5d10f8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/__init__.py index ffc49d028e4..dd28625b36f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._authorization_management_client import AuthorizationManagementClient -__all__ = ['AuthorizationManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_authorization_management_client.py index c8cbf3acbd4..e155a08766b 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_authorization_management_client.py @@ -6,69 +6,82 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import RoleAssignmentMetricsOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import RoleAssignmentMetricsOperations -from .. import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + assignments. A role assignment grants access to Azure Active Directory users. :ivar role_assignment_metrics: RoleAssignmentMetricsOperations operations - :vartype role_assignment_metrics: azure.mgmt.authorization.v2019_08_01_preview.aio.operations.RoleAssignmentMetricsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype role_assignment_metrics: + azure.mgmt.authorization.v2019_08_01_preview.aio.operations.RoleAssignmentMetricsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2019-08-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.role_assignment_metrics = RoleAssignmentMetricsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_configuration.py index c57152d3d99..6e7d2124318 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,49 +19,48 @@ from azure.core.credentials_async import AsyncTokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2019-08-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2019-08-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2019-08-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/__init__.py index 8244630e3d3..61c09223d66 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/__init__.py @@ -8,6 +8,12 @@ from ._role_assignment_metrics_operations import RoleAssignmentMetricsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RoleAssignmentMetricsOperations', + "RoleAssignmentMetricsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/_role_assignment_metrics_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/_role_assignment_metrics_operations.py index 62dd285c0db..84f0b609447 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/_role_assignment_metrics_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/aio/operations/_role_assignment_metrics_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,88 +6,99 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_assignment_metrics_operations import build_get_metrics_for_subscription_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentMetricsOperations: - """RoleAssignmentMetricsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentMetricsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2019_08_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2019_08_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_assignment_metrics` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get_metrics_for_subscription( - self, - **kwargs: Any - ) -> "_models.RoleAssignmentMetricsResult": + @distributed_trace_async + async def get_metrics_for_subscription(self, **kwargs: Any) -> _models.RoleAssignmentMetricsResult: """Get role assignment usage metrics for a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentMetricsResult, or the result of cls(response) + :return: RoleAssignmentMetricsResult or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2019_08_01_preview.models.RoleAssignmentMetricsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentMetricsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_metrics_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentMetricsResult] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_metrics_for_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_metrics_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentMetricsResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentMetricsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_metrics_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignmentsUsageMetrics'} # type: ignore + + get_metrics_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignmentsUsageMetrics"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/__init__.py index 300a963b2df..bc45d64bf62 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/__init__.py @@ -6,20 +6,19 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ErrorAdditionalInfo - from ._models_py3 import ErrorDetail - from ._models_py3 import ErrorResponse - from ._models_py3 import RoleAssignmentMetricsResult -except (SyntaxError, ImportError): - from ._models import ErrorAdditionalInfo # type: ignore - from ._models import ErrorDetail # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import RoleAssignmentMetricsResult # type: ignore +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import RoleAssignmentMetricsResult +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ErrorAdditionalInfo', - 'ErrorDetail', - 'ErrorResponse', - 'RoleAssignmentMetricsResult', + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "RoleAssignmentMetricsResult", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_models.py deleted file mode 100644 index 90b847f06ec..00000000000 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_models.py +++ /dev/null @@ -1,145 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class ErrorAdditionalInfo(msrest.serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(msrest.serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.authorization.v2019_08_01_preview.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.mgmt.authorization.v2019_08_01_preview.models.ErrorAdditionalInfo] - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(msrest.serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2019_08_01_preview.models.ErrorDetail - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class RoleAssignmentMetricsResult(msrest.serialization.Model): - """Role Assignment Metrics. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar subscription_id: The subscription ID. - :vartype subscription_id: str - :ivar role_assignments_limit: The role assignment limit. - :vartype role_assignments_limit: long - :ivar role_assignments_current_count: The number of current role assignments. - :vartype role_assignments_current_count: long - :ivar role_assignments_remaining_count: The number of remaining role assignments available. - :vartype role_assignments_remaining_count: long - """ - - _validation = { - 'subscription_id': {'readonly': True}, - 'role_assignments_limit': {'readonly': True}, - 'role_assignments_current_count': {'readonly': True}, - 'role_assignments_remaining_count': {'readonly': True}, - } - - _attribute_map = { - 'subscription_id': {'key': 'subscriptionId', 'type': 'str'}, - 'role_assignments_limit': {'key': 'roleAssignmentsLimit', 'type': 'long'}, - 'role_assignments_current_count': {'key': 'roleAssignmentsCurrentCount', 'type': 'long'}, - 'role_assignments_remaining_count': {'key': 'roleAssignmentsRemainingCount', 'type': 'long'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentMetricsResult, self).__init__(**kwargs) - self.subscription_id = None - self.role_assignments_limit = None - self.role_assignments_current_count = None - self.role_assignments_remaining_count = None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_models_py3.py index 286bd07d2b4..0020262403d 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_models_py3.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -6,13 +7,16 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Optional +from typing import Optional, TYPE_CHECKING -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class ErrorAdditionalInfo(msrest.serialization.Model): + +class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. @@ -20,29 +24,27 @@ class ErrorAdditionalInfo(msrest.serialization.Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: any + :vartype info: JSON """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None -class ErrorDetail(msrest.serialization.Model): +class ErrorDetail(_serialization.Model): """The error detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -61,26 +63,24 @@ class ErrorDetail(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -88,28 +88,27 @@ def __init__( self.additional_info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2019_08_01_preview.models.ErrorDetail + :ivar error: The error object. + :vartype error: ~azure.mgmt.authorization.v2019_08_01_preview.models.ErrorDetail """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, + "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__( - self, - *, - error: Optional["ErrorDetail"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.authorization.v2019_08_01_preview.models.ErrorDetail + """ + super().__init__(**kwargs) self.error = error -class RoleAssignmentMetricsResult(msrest.serialization.Model): +class RoleAssignmentMetricsResult(_serialization.Model): """Role Assignment Metrics. Variables are only populated by the server, and will be ignored when sending a request. @@ -117,32 +116,30 @@ class RoleAssignmentMetricsResult(msrest.serialization.Model): :ivar subscription_id: The subscription ID. :vartype subscription_id: str :ivar role_assignments_limit: The role assignment limit. - :vartype role_assignments_limit: long + :vartype role_assignments_limit: int :ivar role_assignments_current_count: The number of current role assignments. - :vartype role_assignments_current_count: long + :vartype role_assignments_current_count: int :ivar role_assignments_remaining_count: The number of remaining role assignments available. - :vartype role_assignments_remaining_count: long + :vartype role_assignments_remaining_count: int """ _validation = { - 'subscription_id': {'readonly': True}, - 'role_assignments_limit': {'readonly': True}, - 'role_assignments_current_count': {'readonly': True}, - 'role_assignments_remaining_count': {'readonly': True}, + "subscription_id": {"readonly": True}, + "role_assignments_limit": {"readonly": True}, + "role_assignments_current_count": {"readonly": True}, + "role_assignments_remaining_count": {"readonly": True}, } _attribute_map = { - 'subscription_id': {'key': 'subscriptionId', 'type': 'str'}, - 'role_assignments_limit': {'key': 'roleAssignmentsLimit', 'type': 'long'}, - 'role_assignments_current_count': {'key': 'roleAssignmentsCurrentCount', 'type': 'long'}, - 'role_assignments_remaining_count': {'key': 'roleAssignmentsRemainingCount', 'type': 'long'}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + "role_assignments_limit": {"key": "roleAssignmentsLimit", "type": "int"}, + "role_assignments_current_count": {"key": "roleAssignmentsCurrentCount", "type": "int"}, + "role_assignments_remaining_count": {"key": "roleAssignmentsRemainingCount", "type": "int"}, } - def __init__( - self, - **kwargs - ): - super(RoleAssignmentMetricsResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.subscription_id = None self.role_assignments_limit = None self.role_assignments_current_count = None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/__init__.py index 8244630e3d3..61c09223d66 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/__init__.py @@ -8,6 +8,12 @@ from ._role_assignment_metrics_operations import RoleAssignmentMetricsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RoleAssignmentMetricsOperations', + "RoleAssignmentMetricsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/_role_assignment_metrics_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/_role_assignment_metrics_operations.py index 454ef3be9b1..4313cc50305 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/_role_assignment_metrics_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2019_08_01_preview/operations/_role_assignment_metrics_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,93 +6,128 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_metrics_for_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignmentsUsageMetrics" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class RoleAssignmentMetricsOperations(object): - """RoleAssignmentMetricsOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2019_08_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class RoleAssignmentMetricsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2019_08_01_preview.AuthorizationManagementClient`'s + :attr:`role_assignment_metrics` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def get_metrics_for_subscription( - self, - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentMetricsResult" + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get_metrics_for_subscription(self, **kwargs: Any) -> _models.RoleAssignmentMetricsResult: """Get role assignment usage metrics for a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentMetricsResult, or the result of cls(response) + :return: RoleAssignmentMetricsResult or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2019_08_01_preview.models.RoleAssignmentMetricsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentMetricsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_metrics_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentMetricsResult] + + request = build_get_metrics_for_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_metrics_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentMetricsResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentMetricsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_metrics_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignmentsUsageMetrics'} # type: ignore + + get_metrics_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignmentsUsageMetrics"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/__init__.py index ae11ad3e4d9..9eb8d3ec28c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AuthorizationManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_authorization_management_client.py index 33609c807ff..f6324930b89 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_authorization_management_client.py @@ -6,73 +6,82 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import RoleAssignmentsOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import RoleAssignmentsOperations -from . import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + assignments. A role assignment grants access to Azure Active Directory users. :ivar role_assignments: RoleAssignmentsOperations operations - :vartype role_assignments: azure.mgmt.authorization.v2020_04_01_preview.operations.RoleAssignmentsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype role_assignments: + azure.mgmt.authorization.v2020_04_01_preview.operations.RoleAssignmentsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2020-04-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.role_assignments = RoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_configuration.py index 68f02c44c0d..a42be946092 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_configuration.py @@ -6,66 +6,64 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2020-04-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2020-04-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2020-04-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_metadata.json index 2343e9faff4..662d784476f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_metadata.json +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_metadata.json @@ -5,25 +5,25 @@ "name": "AuthorizationManagementClient", "filename": "_authorization_management_client", "description": "Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, "azure_arm": true, "has_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -54,7 +54,7 @@ "required": false }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -74,7 +74,7 @@ "required": false }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -91,11 +91,10 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "role_assignments": "RoleAssignmentsOperations" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_version.py index 48944bf3938..cac9f5d10f8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/__init__.py index ffc49d028e4..dd28625b36f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._authorization_management_client import AuthorizationManagementClient -__all__ = ['AuthorizationManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_authorization_management_client.py index e4d7629bf93..ef3ab491bda 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_authorization_management_client.py @@ -6,69 +6,82 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import RoleAssignmentsOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import RoleAssignmentsOperations -from .. import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + assignments. A role assignment grants access to Azure Active Directory users. :ivar role_assignments: RoleAssignmentsOperations operations - :vartype role_assignments: azure.mgmt.authorization.v2020_04_01_preview.aio.operations.RoleAssignmentsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype role_assignments: + azure.mgmt.authorization.v2020_04_01_preview.aio.operations.RoleAssignmentsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2020-04-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.role_assignments = RoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_configuration.py index 7ded355a032..528e17149ab 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,49 +19,48 @@ from azure.core.credentials_async import AsyncTokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2020-04-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2020-04-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2020-04-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/__init__.py index b9e31fd2db9..3b7b5d5c272 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/__init__.py @@ -8,6 +8,12 @@ from ._role_assignments_operations import RoleAssignmentsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RoleAssignmentsOperations', + "RoleAssignmentsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/_role_assignments_operations.py index 1dcb19f3628..13f6dec0ff7 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/_role_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/aio/operations/_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,42 +6,65 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_assignments_operations import ( + build_create_by_id_request, + build_create_request, + build_delete_by_id_request, + build_delete_request, + build_get_by_id_request, + build_get_request, + build_list_for_resource_group_request, + build_list_for_resource_request, + build_list_for_scope_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentsOperations: - """RoleAssignmentsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_04_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_04_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_resource( self, resource_group_name: str, @@ -51,72 +75,79 @@ def list_for_resource( filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + ) -> AsyncIterable["_models.RoleAssignment"]: """List role assignments for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get role assignments for. + :param resource_name: The name of the resource to get role assignments for. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -125,81 +156,86 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace def list_for_resource_group( - self, - resource_group_name: str, - filter: Optional[str] = None, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, resource_group_name: str, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """List role assignments for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -208,93 +244,97 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace_async async def delete( - self, - scope: str, - role_assignment_name: str, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> Optional["_models.RoleAssignment"]: + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: """Delete a role assignment. - :param scope: The scope of the role assignment to delete. + :param scope: The scope of the role assignment to delete. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to delete. + :param role_assignment_name: The name of the role assignment to delete. Required. :type role_assignment_name: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload async def create( self, scope: str, role_assignment_name: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignment": + ) -> _models.RoleAssignment: """Create a role assignment. :param scope: The scope of the role assignment to create. The scope can be any REST resource @@ -302,365 +342,508 @@ async def create( '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to create. It can be any valid - GUID. + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Create a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Create a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace_async async def get( - self, - scope: str, - role_assignment_name: str, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> "_models.RoleAssignment": + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> _models.RoleAssignment: """Get the specified role assignment. - :param scope: The scope of the role assignment. + :param scope: The scope of the role assignment. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to get. + :param role_assignment_name: The name of the role assignment to get. Required. :type role_assignment_name: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace_async async def delete_by_id( - self, - role_id: str, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> Optional["_models.RoleAssignment"]: + self, role_id: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: """Delete a role assignment. - :param role_id: The ID of the role assignment to delete. + :param role_id: The ID of the role assignment to delete. Required. :type role_id: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_by_id_request( + role_id=role_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_id.metadata = {'url': '/{roleId}'} # type: ignore + delete_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @overload async def create_by_id( self, role_id: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignment": + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, role_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: """Creates a role assignment by ID. - :param role_id: The ID of the role assignment to create. + :param role_id: The ID of the role assignment to create. Required. :type role_id: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, role_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_id=role_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_by_id.metadata = {'url': '/{roleId}'} # type: ignore - async def get_by_id( - self, - role_id: str, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> "_models.RoleAssignment": + create_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, role_id: str, tenant_id: Optional[str] = None, **kwargs: Any) -> _models.RoleAssignment: """Gets a role assignment by ID. - :param role_id: The ID of the role assignment to get. + :param role_id: The ID of the role assignment to get. Required. :type role_id: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_by_id_request( + role_id=role_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleId}'} # type: ignore + get_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace def list( - self, - filter: Optional[str] = None, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """Gets all role assignments for the subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -669,80 +852,84 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, scope: str, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """Gets role assignments for a scope. - :param scope: The scope of the role assignments. + :param scope: The scope of the role assignments. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -751,17 +938,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/__init__.py index 83bed740131..c44ad4c485a 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/__init__.py @@ -6,34 +6,28 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ErrorAdditionalInfo - from ._models_py3 import ErrorDetail - from ._models_py3 import ErrorResponse - from ._models_py3 import RoleAssignment - from ._models_py3 import RoleAssignmentCreateParameters - from ._models_py3 import RoleAssignmentFilter - from ._models_py3 import RoleAssignmentListResult -except (SyntaxError, ImportError): - from ._models import ErrorAdditionalInfo # type: ignore - from ._models import ErrorDetail # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import RoleAssignment # type: ignore - from ._models import RoleAssignmentCreateParameters # type: ignore - from ._models import RoleAssignmentFilter # type: ignore - from ._models import RoleAssignmentListResult # type: ignore +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import RoleAssignment +from ._models_py3 import RoleAssignmentCreateParameters +from ._models_py3 import RoleAssignmentFilter +from ._models_py3 import RoleAssignmentListResult -from ._authorization_management_client_enums import ( - PrincipalType, -) +from ._authorization_management_client_enums import PrincipalType +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ErrorAdditionalInfo', - 'ErrorDetail', - 'ErrorResponse', - 'RoleAssignment', - 'RoleAssignmentCreateParameters', - 'RoleAssignmentFilter', - 'RoleAssignmentListResult', - 'PrincipalType', + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "RoleAssignment", + "RoleAssignmentCreateParameters", + "RoleAssignmentFilter", + "RoleAssignmentListResult", + "PrincipalType", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_authorization_management_client_enums.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_authorization_management_client_enums.py index c60129f05bc..4519b342017 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_authorization_management_client_enums.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_authorization_management_client_enums.py @@ -6,29 +6,12 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class PrincipalType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The principal type of the assigned principal ID. - """ +class PrincipalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The principal type of the assigned principal ID.""" USER = "User" GROUP = "Group" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_models.py deleted file mode 100644 index 538c4b092fe..00000000000 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_models.py +++ /dev/null @@ -1,301 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class ErrorAdditionalInfo(msrest.serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(msrest.serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.authorization.v2020_04_01_preview.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.mgmt.authorization.v2020_04_01_preview.models.ErrorAdditionalInfo] - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(msrest.serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2020_04_01_preview.models.ErrorDetail - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class RoleAssignment(msrest.serialization.Model): - """Role Assignments. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role assignment ID. - :vartype id: str - :ivar name: The role assignment name. - :vartype name: str - :ivar type: The role assignment type. - :vartype type: str - :param scope: The role assignment scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup". - :type principal_type: str or ~azure.mgmt.authorization.v2020_04_01_preview.models.PrincipalType - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool - :param description: Description of role assignment. - :type description: str - :param condition: The conditions on the role assignment. This limits the resources it can be - assigned to. e.g.: - @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] - StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param created_on: Time it was created. - :type created_on: ~datetime.datetime - :param updated_on: Time it was updated. - :type updated_on: ~datetime.datetime - :param created_by: Id of the user who created the assignment. - :type created_by: str - :param updated_by: Id of the user who updated the assignment. - :type updated_by: str - :param delegated_managed_identity_resource_id: Id of the delegated managed identity resource. - :type delegated_managed_identity_resource_id: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'updated_on': {'key': 'properties.updatedOn', 'type': 'iso-8601'}, - 'created_by': {'key': 'properties.createdBy', 'type': 'str'}, - 'updated_by': {'key': 'properties.updatedBy', 'type': 'str'}, - 'delegated_managed_identity_resource_id': {'key': 'properties.delegatedManagedIdentityResourceId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignment, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = kwargs.get('scope', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.principal_id = kwargs.get('principal_id', None) - self.principal_type = kwargs.get('principal_type', None) - self.can_delegate = kwargs.get('can_delegate', None) - self.description = kwargs.get('description', None) - self.condition = kwargs.get('condition', None) - self.condition_version = kwargs.get('condition_version', None) - self.created_on = kwargs.get('created_on', None) - self.updated_on = kwargs.get('updated_on', None) - self.created_by = kwargs.get('created_by', None) - self.updated_by = kwargs.get('updated_by', None) - self.delegated_managed_identity_resource_id = kwargs.get('delegated_managed_identity_resource_id', None) - - -class RoleAssignmentCreateParameters(msrest.serialization.Model): - """Role assignment create parameters. - - All required parameters must be populated in order to send to Azure. - - :param role_definition_id: Required. The role definition ID used in the role assignment. - :type role_definition_id: str - :param principal_id: Required. The principal ID assigned to the role. This maps to the ID - inside the Active Directory. It can point to a user, service principal, or security group. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup". - :type principal_type: str or ~azure.mgmt.authorization.v2020_04_01_preview.models.PrincipalType - :param can_delegate: The delegation flag used for creating a role assignment. - :type can_delegate: bool - :param description: Description of role assignment. - :type description: str - :param condition: The conditions on the role assignment. This limits the resources it can be - assigned to. e.g.: - @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] - StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param delegated_managed_identity_resource_id: Id of the delegated managed identity resource. - :type delegated_managed_identity_resource_id: str - """ - - _validation = { - 'role_definition_id': {'required': True}, - 'principal_id': {'required': True}, - } - - _attribute_map = { - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'delegated_managed_identity_resource_id': {'key': 'properties.delegatedManagedIdentityResourceId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentCreateParameters, self).__init__(**kwargs) - self.role_definition_id = kwargs['role_definition_id'] - self.principal_id = kwargs['principal_id'] - self.principal_type = kwargs.get('principal_type', None) - self.can_delegate = kwargs.get('can_delegate', None) - self.description = kwargs.get('description', None) - self.condition = kwargs.get('condition', None) - self.condition_version = kwargs.get('condition_version', None) - self.delegated_managed_identity_resource_id = kwargs.get('delegated_managed_identity_resource_id', None) - - -class RoleAssignmentFilter(msrest.serialization.Model): - """Role Assignments filter. - - :param principal_id: Returns role assignment of the specific principal. - :type principal_id: str - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool - """ - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'can_delegate': {'key': 'canDelegate', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentFilter, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - self.can_delegate = kwargs.get('can_delegate', None) - - -class RoleAssignmentListResult(msrest.serialization.Model): - """Role assignment list operation result. - - :param value: Role assignment list. - :type value: list[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_models_py3.py index e16a85d3881..fd8c02d51c6 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_models_py3.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,15 +8,16 @@ # -------------------------------------------------------------------------- import datetime -from typing import List, Optional, Union +from typing import List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization -from ._authorization_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class ErrorAdditionalInfo(msrest.serialization.Model): +class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. @@ -23,29 +25,27 @@ class ErrorAdditionalInfo(msrest.serialization.Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: any + :vartype info: JSON """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None -class ErrorDetail(msrest.serialization.Model): +class ErrorDetail(_serialization.Model): """The error detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -64,26 +64,24 @@ class ErrorDetail(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -91,28 +89,27 @@ def __init__( self.additional_info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2020_04_01_preview.models.ErrorDetail + :ivar error: The error object. + :vartype error: ~azure.mgmt.authorization.v2020_04_01_preview.models.ErrorDetail """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, + "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__( - self, - *, - error: Optional["ErrorDetail"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.authorization.v2020_04_01_preview.models.ErrorDetail + """ + super().__init__(**kwargs) self.error = error -class RoleAssignment(msrest.serialization.Model): +class RoleAssignment(_serialization.Model): # pylint: disable=too-many-instance-attributes """Role Assignments. Variables are only populated by the server, and will be ignored when sending a request. @@ -123,61 +120,65 @@ class RoleAssignment(msrest.serialization.Model): :vartype name: str :ivar type: The role assignment type. :vartype type: str - :param scope: The role assignment scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup". - :type principal_type: str or ~azure.mgmt.authorization.v2020_04_01_preview.models.PrincipalType - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool - :param description: Description of role assignment. - :type description: str - :param condition: The conditions on the role assignment. This limits the resources it can be + :ivar scope: The role assignment scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", and "ForeignGroup". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2020_04_01_preview.models.PrincipalType + :ivar can_delegate: The Delegation flag for the role assignment. + :vartype can_delegate: bool + :ivar description: Description of role assignment. + :vartype description: str + :ivar condition: The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param created_on: Time it was created. - :type created_on: ~datetime.datetime - :param updated_on: Time it was updated. - :type updated_on: ~datetime.datetime - :param created_by: Id of the user who created the assignment. - :type created_by: str - :param updated_by: Id of the user who updated the assignment. - :type updated_by: str - :param delegated_managed_identity_resource_id: Id of the delegated managed identity resource. - :type delegated_managed_identity_resource_id: str + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: Time it was created. + :vartype created_on: ~datetime.datetime + :ivar updated_on: Time it was updated. + :vartype updated_on: ~datetime.datetime + :ivar created_by: Id of the user who created the assignment. + :vartype created_by: str + :ivar updated_by: Id of the user who updated the assignment. + :vartype updated_by: str + :ivar delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :vartype delegated_managed_identity_resource_id: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'updated_on': {'key': 'properties.updatedOn', 'type': 'iso-8601'}, - 'created_by': {'key': 'properties.createdBy', 'type': 'str'}, - 'updated_by': {'key': 'properties.updatedBy', 'type': 'str'}, - 'delegated_managed_identity_resource_id': {'key': 'properties.delegatedManagedIdentityResourceId', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "can_delegate": {"key": "properties.canDelegate", "type": "bool"}, + "description": {"key": "properties.description", "type": "str"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "updated_on": {"key": "properties.updatedOn", "type": "iso-8601"}, + "created_by": {"key": "properties.createdBy", "type": "str"}, + "updated_by": {"key": "properties.updatedBy", "type": "str"}, + "delegated_managed_identity_resource_id": { + "key": "properties.delegatedManagedIdentityResourceId", + "type": "str", + }, } def __init__( @@ -186,7 +187,7 @@ def __init__( scope: Optional[str] = None, role_definition_id: Optional[str] = None, principal_id: Optional[str] = None, - principal_type: Optional[Union[str, "PrincipalType"]] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, can_delegate: Optional[bool] = None, description: Optional[str] = None, condition: Optional[str] = None, @@ -198,7 +199,40 @@ def __init__( delegated_managed_identity_resource_id: Optional[str] = None, **kwargs ): - super(RoleAssignment, self).__init__(**kwargs) + """ + :keyword scope: The role assignment scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", and "ForeignGroup". + :paramtype principal_type: str or + ~azure.mgmt.authorization.v2020_04_01_preview.models.PrincipalType + :keyword can_delegate: The Delegation flag for the role assignment. + :paramtype can_delegate: bool + :keyword description: Description of role assignment. + :paramtype description: str + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword created_on: Time it was created. + :paramtype created_on: ~datetime.datetime + :keyword updated_on: Time it was updated. + :paramtype updated_on: ~datetime.datetime + :keyword created_by: Id of the user who created the assignment. + :paramtype created_by: str + :keyword updated_by: Id of the user who updated the assignment. + :paramtype updated_by: str + :keyword delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :paramtype delegated_managed_identity_resource_id: str + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -217,48 +251,52 @@ def __init__( self.delegated_managed_identity_resource_id = delegated_managed_identity_resource_id -class RoleAssignmentCreateParameters(msrest.serialization.Model): +class RoleAssignmentCreateParameters(_serialization.Model): """Role assignment create parameters. All required parameters must be populated in order to send to Azure. - :param role_definition_id: Required. The role definition ID used in the role assignment. - :type role_definition_id: str - :param principal_id: Required. The principal ID assigned to the role. This maps to the ID - inside the Active Directory. It can point to a user, service principal, or security group. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup". - :type principal_type: str or ~azure.mgmt.authorization.v2020_04_01_preview.models.PrincipalType - :param can_delegate: The delegation flag used for creating a role assignment. - :type can_delegate: bool - :param description: Description of role assignment. - :type description: str - :param condition: The conditions on the role assignment. This limits the resources it can be + :ivar role_definition_id: The role definition ID used in the role assignment. Required. + :vartype role_definition_id: str + :ivar principal_id: The principal ID assigned to the role. This maps to the ID inside the + Active Directory. It can point to a user, service principal, or security group. Required. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", and "ForeignGroup". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2020_04_01_preview.models.PrincipalType + :ivar can_delegate: The delegation flag used for creating a role assignment. + :vartype can_delegate: bool + :ivar description: Description of role assignment. + :vartype description: str + :ivar condition: The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param delegated_managed_identity_resource_id: Id of the delegated managed identity resource. - :type delegated_managed_identity_resource_id: str + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :vartype delegated_managed_identity_resource_id: str """ _validation = { - 'role_definition_id': {'required': True}, - 'principal_id': {'required': True}, + "role_definition_id": {"required": True}, + "principal_id": {"required": True}, } _attribute_map = { - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'delegated_managed_identity_resource_id': {'key': 'properties.delegatedManagedIdentityResourceId', 'type': 'str'}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "can_delegate": {"key": "properties.canDelegate", "type": "bool"}, + "description": {"key": "properties.description", "type": "str"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "delegated_managed_identity_resource_id": { + "key": "properties.delegatedManagedIdentityResourceId", + "type": "str", + }, } def __init__( @@ -266,7 +304,7 @@ def __init__( *, role_definition_id: str, principal_id: str, - principal_type: Optional[Union[str, "PrincipalType"]] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, can_delegate: Optional[bool] = None, description: Optional[str] = None, condition: Optional[str] = None, @@ -274,7 +312,31 @@ def __init__( delegated_managed_identity_resource_id: Optional[str] = None, **kwargs ): - super(RoleAssignmentCreateParameters, self).__init__(**kwargs) + """ + :keyword role_definition_id: The role definition ID used in the role assignment. Required. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID assigned to the role. This maps to the ID inside the + Active Directory. It can point to a user, service principal, or security group. Required. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", and "ForeignGroup". + :paramtype principal_type: str or + ~azure.mgmt.authorization.v2020_04_01_preview.models.PrincipalType + :keyword can_delegate: The delegation flag used for creating a role assignment. + :paramtype can_delegate: bool + :keyword description: Description of role assignment. + :paramtype description: str + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :paramtype delegated_managed_identity_resource_id: str + """ + super().__init__(**kwargs) self.role_definition_id = role_definition_id self.principal_id = principal_id self.principal_type = principal_type @@ -285,53 +347,55 @@ def __init__( self.delegated_managed_identity_resource_id = delegated_managed_identity_resource_id -class RoleAssignmentFilter(msrest.serialization.Model): +class RoleAssignmentFilter(_serialization.Model): """Role Assignments filter. - :param principal_id: Returns role assignment of the specific principal. - :type principal_id: str - :param can_delegate: The Delegation flag for the role assignment. - :type can_delegate: bool + :ivar principal_id: Returns role assignment of the specific principal. + :vartype principal_id: str + :ivar can_delegate: The Delegation flag for the role assignment. + :vartype can_delegate: bool """ _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'can_delegate': {'key': 'canDelegate', 'type': 'bool'}, + "principal_id": {"key": "principalId", "type": "str"}, + "can_delegate": {"key": "canDelegate", "type": "bool"}, } - def __init__( - self, - *, - principal_id: Optional[str] = None, - can_delegate: Optional[bool] = None, - **kwargs - ): - super(RoleAssignmentFilter, self).__init__(**kwargs) + def __init__(self, *, principal_id: Optional[str] = None, can_delegate: Optional[bool] = None, **kwargs): + """ + :keyword principal_id: Returns role assignment of the specific principal. + :paramtype principal_id: str + :keyword can_delegate: The Delegation flag for the role assignment. + :paramtype can_delegate: bool + """ + super().__init__(**kwargs) self.principal_id = principal_id self.can_delegate = can_delegate -class RoleAssignmentListResult(msrest.serialization.Model): +class RoleAssignmentListResult(_serialization.Model): """Role assignment list operation result. - :param value: Role assignment list. - :type value: list[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Role assignment list. + :vartype value: list[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["RoleAssignment"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.RoleAssignment"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleAssignmentListResult, self).__init__(**kwargs) + """ + :keyword value: Role assignment list. + :paramtype value: list[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/__init__.py index b9e31fd2db9..3b7b5d5c272 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/__init__.py @@ -8,6 +8,12 @@ from ._role_assignments_operations import RoleAssignmentsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RoleAssignmentsOperations', + "RoleAssignmentsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/_role_assignments_operations.py index b6b21369439..b0d27b11d52 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/_role_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_04_01_preview/operations/_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,123 +6,458 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceProviderNamespace": _SERIALIZER.url( + "resource_provider_namespace", resource_provider_namespace, "str", skip_quote=True + ), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_group_request( + resource_group_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + scope: str, role_assignment_name: str, *, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + scope: str, role_assignment_name: str, *, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request(role_id: str, *, tenant_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleId}") + path_format_arguments = { + "roleId": _SERIALIZER.url("role_id", role_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_by_id_request(role_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleId}") + path_format_arguments = { + "roleId": _SERIALIZER.url("role_id", role_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(role_id: str, *, tenant_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleId}") + path_format_arguments = { + "roleId": _SERIALIZER.url("role_id", role_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +def build_list_request( + subscription_id: str, *, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") -class RoleAssignmentsOperations(object): - """RoleAssignmentsOperations operations. + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + _url = _format_url_section(_url, **path_format_arguments) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_04_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request( + scope: str, *, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_04_01_preview.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_resource( self, - resource_group_name, # type: str - resource_provider_namespace, # type: str - parent_resource_path, # type: str - resource_type, # type: str - resource_name, # type: str - filter=None, # type: Optional[str] - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """List role assignments for a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str - :param parent_resource_path: The parent resource identity. + :param parent_resource_path: The parent resource identity. Required. :type parent_resource_path: str - :param resource_type: The resource type of the resource. + :param resource_type: The resource type of the resource. Required. :type resource_type: str - :param resource_name: The name of the resource to get role assignments for. + :param resource_name: The name of the resource to get role assignments for. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'parentResourcePath': self._serialize.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -130,82 +466,86 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace def list_for_resource_group( - self, - resource_group_name, # type: str - filter=None, # type: Optional[str] - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, resource_group_name: str, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """List role assignments for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -214,95 +554,97 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace def delete( - self, - scope, # type: str - role_assignment_name, # type: str - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleAssignment"] + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: """Delete a role assignment. - :param scope: The scope of the role assignment to delete. + :param scope: The scope of the role assignment to delete. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to delete. + :param role_assignment_name: The name of the role assignment to delete. Required. :type role_assignment_name: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload def create( self, - scope, # type: str - role_assignment_name, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + scope: str, + role_assignment_name: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: """Create a role assignment. :param scope: The scope of the role assignment to create. The scope can be any REST resource @@ -310,370 +652,508 @@ def create( '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to create. It can be any valid - GUID. + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Create a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Create a role assignment. + + :param scope: The scope of the role assignment to create. The scope can be any REST resource + instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_name: A GUID for the role assignment to create. The name must be unique + and different for each role assignment. Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace def get( - self, - scope, # type: str - role_assignment_name, # type: str - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> _models.RoleAssignment: """Get the specified role assignment. - :param scope: The scope of the role assignment. + :param scope: The scope of the role assignment. Required. :type scope: str - :param role_assignment_name: The name of the role assignment to get. + :param role_assignment_name: The name of the role assignment to get. Required. :type role_assignment_name: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace def delete_by_id( - self, - role_id, # type: str - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleAssignment"] + self, role_id: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: """Delete a role assignment. - :param role_id: The ID of the role assignment to delete. + :param role_id: The ID of the role assignment to delete. Required. :type role_id: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + request = build_delete_by_id_request( + role_id=role_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_id.metadata = {'url': '/{roleId}'} # type: ignore + delete_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @overload def create_by_id( self, - role_id, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + role_id: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_by_id( + self, role_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: + """Creates a role assignment by ID. + + :param role_id: The ID of the role assignment to create. Required. + :type role_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_by_id( + self, role_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: """Creates a role assignment by ID. - :param role_id: The ID of the role assignment to create. + :param role_id: The ID of the role assignment to create. Required. :type role_id: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_id=role_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_by_id.metadata = {'url': '/{roleId}'} # type: ignore - def get_by_id( - self, - role_id, # type: str - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + create_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace + def get_by_id(self, role_id: str, tenant_id: Optional[str] = None, **kwargs: Any) -> _models.RoleAssignment: """Gets a role assignment by ID. - :param role_id: The ID of the role assignment to get. + :param role_id: The ID of the role assignment to get. Required. :type role_id: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleId': self._serialize.url("role_id", role_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_by_id_request( + role_id=role_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleId}'} # type: ignore + get_by_id.metadata = {"url": "/{roleId}"} # type: ignore + + @distributed_trace def list( - self, - filter=None, # type: Optional[str] - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """Gets all role assignments for the subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -682,81 +1162,84 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, scope: str, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """Gets role assignments for a scope. - :param scope: The scope of the role assignments. + :param scope: The scope of the role assignments. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_04_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-04-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-04-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -765,17 +1248,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/__init__.py new file mode 100644 index 00000000000..9eb8d3ec28c --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/__init__.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._authorization_management_client import AuthorizationManagementClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_authorization_management_client.py new file mode 100644 index 00000000000..397a326166d --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_authorization_management_client.py @@ -0,0 +1,148 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + EligibleChildResourcesOperations, + RoleAssignmentScheduleInstancesOperations, + RoleAssignmentScheduleRequestsOperations, + RoleAssignmentSchedulesOperations, + RoleEligibilityScheduleInstancesOperations, + RoleEligibilityScheduleRequestsOperations, + RoleEligibilitySchedulesOperations, + RoleManagementPoliciesOperations, + RoleManagementPolicyAssignmentsOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + assignments. A role assignment grants access to Azure Active Directory users. + + :ivar eligible_child_resources: EligibleChildResourcesOperations operations + :vartype eligible_child_resources: + azure.mgmt.authorization.v2020_10_01.operations.EligibleChildResourcesOperations + :ivar role_assignment_schedules: RoleAssignmentSchedulesOperations operations + :vartype role_assignment_schedules: + azure.mgmt.authorization.v2020_10_01.operations.RoleAssignmentSchedulesOperations + :ivar role_assignment_schedule_instances: RoleAssignmentScheduleInstancesOperations operations + :vartype role_assignment_schedule_instances: + azure.mgmt.authorization.v2020_10_01.operations.RoleAssignmentScheduleInstancesOperations + :ivar role_assignment_schedule_requests: RoleAssignmentScheduleRequestsOperations operations + :vartype role_assignment_schedule_requests: + azure.mgmt.authorization.v2020_10_01.operations.RoleAssignmentScheduleRequestsOperations + :ivar role_eligibility_schedules: RoleEligibilitySchedulesOperations operations + :vartype role_eligibility_schedules: + azure.mgmt.authorization.v2020_10_01.operations.RoleEligibilitySchedulesOperations + :ivar role_eligibility_schedule_instances: RoleEligibilityScheduleInstancesOperations + operations + :vartype role_eligibility_schedule_instances: + azure.mgmt.authorization.v2020_10_01.operations.RoleEligibilityScheduleInstancesOperations + :ivar role_eligibility_schedule_requests: RoleEligibilityScheduleRequestsOperations operations + :vartype role_eligibility_schedule_requests: + azure.mgmt.authorization.v2020_10_01.operations.RoleEligibilityScheduleRequestsOperations + :ivar role_management_policies: RoleManagementPoliciesOperations operations + :vartype role_management_policies: + azure.mgmt.authorization.v2020_10_01.operations.RoleManagementPoliciesOperations + :ivar role_management_policy_assignments: RoleManagementPolicyAssignmentsOperations operations + :vartype role_management_policy_assignments: + azure.mgmt.authorization.v2020_10_01.operations.RoleManagementPolicyAssignmentsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2020-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration(credential=credential, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.eligible_child_resources = EligibleChildResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_assignment_schedules = RoleAssignmentSchedulesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_assignment_schedule_instances = RoleAssignmentScheduleInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_assignment_schedule_requests = RoleAssignmentScheduleRequestsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_eligibility_schedules = RoleEligibilitySchedulesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_eligibility_schedule_instances = RoleEligibilityScheduleInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_eligibility_schedule_requests = RoleEligibilityScheduleRequestsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_management_policies = RoleManagementPoliciesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_management_policy_assignments = RoleManagementPolicyAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> AuthorizationManagementClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_configuration.py new file mode 100644 index 00000000000..c4a52b09f71 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_configuration.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for AuthorizationManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :keyword api_version: Api Version. Default value is "2020-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2020-10-01") # type: str + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_metadata.json new file mode 100644 index 00000000000..15e1f81b048 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_metadata.json @@ -0,0 +1,98 @@ +{ + "chosen_version": "2020-10-01", + "total_api_version_list": ["2020-10-01"], + "client": { + "name": "AuthorizationManagementClient", + "filename": "_authorization_management_client", + "description": "Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users.", + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, + "azure_arm": true, + "has_lro_operations": false, + "client_side_validation": false, + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "global_parameters": { + "sync": { + "credential": { + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials.TokenCredential", + "required": true + } + }, + "async": { + "credential": { + "signature": "credential: \"AsyncTokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", + "required": true + } + }, + "constant": { + }, + "call": "credential", + "service_client_specific": { + "sync": { + "api_version": { + "signature": "api_version=None, # type: Optional[str]", + "description": "API version to use if no profile is provided, or if missing in profile.", + "docstring_type": "str", + "required": false + }, + "base_url": { + "signature": "base_url: str = \"https://management.azure.com\",", + "description": "Service URL", + "docstring_type": "str", + "required": false + }, + "profile": { + "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "description": "A profile definition, from KnownProfiles to dict.", + "docstring_type": "azure.profiles.KnownProfiles", + "required": false + } + }, + "async": { + "api_version": { + "signature": "api_version: Optional[str] = None,", + "description": "API version to use if no profile is provided, or if missing in profile.", + "docstring_type": "str", + "required": false + }, + "base_url": { + "signature": "base_url: str = \"https://management.azure.com\",", + "description": "Service URL", + "docstring_type": "str", + "required": false + }, + "profile": { + "signature": "profile: KnownProfiles = KnownProfiles.default,", + "description": "A profile definition, from KnownProfiles to dict.", + "docstring_type": "azure.profiles.KnownProfiles", + "required": false + } + } + } + }, + "config": { + "credential": true, + "credential_scopes": ["https://management.azure.com/.default"], + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "operation_groups": { + "eligible_child_resources": "EligibleChildResourcesOperations", + "role_assignment_schedules": "RoleAssignmentSchedulesOperations", + "role_assignment_schedule_instances": "RoleAssignmentScheduleInstancesOperations", + "role_assignment_schedule_requests": "RoleAssignmentScheduleRequestsOperations", + "role_eligibility_schedules": "RoleEligibilitySchedulesOperations", + "role_eligibility_schedule_instances": "RoleEligibilityScheduleInstancesOperations", + "role_eligibility_schedule_requests": "RoleEligibilityScheduleRequestsOperations", + "role_management_policies": "RoleManagementPoliciesOperations", + "role_management_policy_assignments": "RoleManagementPolicyAssignmentsOperations" + } +} \ No newline at end of file diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_version.py new file mode 100644 index 00000000000..cac9f5d10f8 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/__init__.py new file mode 100644 index 00000000000..dd28625b36f --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._authorization_management_client import AuthorizationManagementClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_authorization_management_client.py new file mode 100644 index 00000000000..a315f4ed9df --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_authorization_management_client.py @@ -0,0 +1,145 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + EligibleChildResourcesOperations, + RoleAssignmentScheduleInstancesOperations, + RoleAssignmentScheduleRequestsOperations, + RoleAssignmentSchedulesOperations, + RoleEligibilityScheduleInstancesOperations, + RoleEligibilityScheduleRequestsOperations, + RoleEligibilitySchedulesOperations, + RoleManagementPoliciesOperations, + RoleManagementPolicyAssignmentsOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + assignments. A role assignment grants access to Azure Active Directory users. + + :ivar eligible_child_resources: EligibleChildResourcesOperations operations + :vartype eligible_child_resources: + azure.mgmt.authorization.v2020_10_01.aio.operations.EligibleChildResourcesOperations + :ivar role_assignment_schedules: RoleAssignmentSchedulesOperations operations + :vartype role_assignment_schedules: + azure.mgmt.authorization.v2020_10_01.aio.operations.RoleAssignmentSchedulesOperations + :ivar role_assignment_schedule_instances: RoleAssignmentScheduleInstancesOperations operations + :vartype role_assignment_schedule_instances: + azure.mgmt.authorization.v2020_10_01.aio.operations.RoleAssignmentScheduleInstancesOperations + :ivar role_assignment_schedule_requests: RoleAssignmentScheduleRequestsOperations operations + :vartype role_assignment_schedule_requests: + azure.mgmt.authorization.v2020_10_01.aio.operations.RoleAssignmentScheduleRequestsOperations + :ivar role_eligibility_schedules: RoleEligibilitySchedulesOperations operations + :vartype role_eligibility_schedules: + azure.mgmt.authorization.v2020_10_01.aio.operations.RoleEligibilitySchedulesOperations + :ivar role_eligibility_schedule_instances: RoleEligibilityScheduleInstancesOperations + operations + :vartype role_eligibility_schedule_instances: + azure.mgmt.authorization.v2020_10_01.aio.operations.RoleEligibilityScheduleInstancesOperations + :ivar role_eligibility_schedule_requests: RoleEligibilityScheduleRequestsOperations operations + :vartype role_eligibility_schedule_requests: + azure.mgmt.authorization.v2020_10_01.aio.operations.RoleEligibilityScheduleRequestsOperations + :ivar role_management_policies: RoleManagementPoliciesOperations operations + :vartype role_management_policies: + azure.mgmt.authorization.v2020_10_01.aio.operations.RoleManagementPoliciesOperations + :ivar role_management_policy_assignments: RoleManagementPolicyAssignmentsOperations operations + :vartype role_management_policy_assignments: + azure.mgmt.authorization.v2020_10_01.aio.operations.RoleManagementPolicyAssignmentsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2020-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration(credential=credential, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.eligible_child_resources = EligibleChildResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_assignment_schedules = RoleAssignmentSchedulesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_assignment_schedule_instances = RoleAssignmentScheduleInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_assignment_schedule_requests = RoleAssignmentScheduleRequestsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_eligibility_schedules = RoleEligibilitySchedulesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_eligibility_schedule_instances = RoleEligibilityScheduleInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_eligibility_schedule_requests = RoleEligibilityScheduleRequestsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_management_policies = RoleManagementPoliciesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_management_policy_assignments = RoleManagementPolicyAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "AuthorizationManagementClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_configuration.py new file mode 100644 index 00000000000..19bf4398fdc --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_configuration.py @@ -0,0 +1,61 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for AuthorizationManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: Api Version. Default value is "2020-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2020-10-01") # type: str + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/__init__.py new file mode 100644 index 00000000000..53e733602ba --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/__init__.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._eligible_child_resources_operations import EligibleChildResourcesOperations +from ._role_assignment_schedules_operations import RoleAssignmentSchedulesOperations +from ._role_assignment_schedule_instances_operations import RoleAssignmentScheduleInstancesOperations +from ._role_assignment_schedule_requests_operations import RoleAssignmentScheduleRequestsOperations +from ._role_eligibility_schedules_operations import RoleEligibilitySchedulesOperations +from ._role_eligibility_schedule_instances_operations import RoleEligibilityScheduleInstancesOperations +from ._role_eligibility_schedule_requests_operations import RoleEligibilityScheduleRequestsOperations +from ._role_management_policies_operations import RoleManagementPoliciesOperations +from ._role_management_policy_assignments_operations import RoleManagementPolicyAssignmentsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "EligibleChildResourcesOperations", + "RoleAssignmentSchedulesOperations", + "RoleAssignmentScheduleInstancesOperations", + "RoleAssignmentScheduleRequestsOperations", + "RoleEligibilitySchedulesOperations", + "RoleEligibilityScheduleInstancesOperations", + "RoleEligibilityScheduleRequestsOperations", + "RoleManagementPoliciesOperations", + "RoleManagementPolicyAssignmentsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_eligible_child_resources_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_eligible_child_resources_operations.py new file mode 100644 index 00000000000..a30e682a949 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_eligible_child_resources_operations.py @@ -0,0 +1,137 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._eligible_child_resources_operations import build_get_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class EligibleChildResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.aio.AuthorizationManagementClient`'s + :attr:`eligible_child_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.EligibleChildResource"]: + """Get the child resources of a resource on which user has eligible access. + + :param scope: The scope of the role management policy. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=resourceType+eq+'Subscription' + to filter on only resource of type = 'Subscription'. Use + $filter=resourceType+eq+'subscription'+or+resourceType+eq+'resourcegroup' to filter on resource + of type = 'Subscription' or 'ResourceGroup'. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either EligibleChildResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01.models.EligibleChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.EligibleChildResourcesListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_get_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("EligibleChildResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/eligibleChildResources"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedule_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedule_instances_operations.py new file mode 100644 index 00000000000..ab4ae525a7e --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedule_instances_operations.py @@ -0,0 +1,200 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_assignment_schedule_instances_operations import build_get_request, build_list_for_scope_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RoleAssignmentScheduleInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.aio.AuthorizationManagementClient`'s + :attr:`role_assignment_schedule_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignmentScheduleInstance"]: + """Gets role assignment schedule instances of a role assignment schedule. + + :param scope: The scope of the role assignment schedule. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role + assignment schedules at, above or below the scope for the specified principal. Use + $filter=assignedTo('{userId}') to return all role assignment schedule instances for the user. + Use $filter=asTarget() to return all role assignment schedule instances created for the current + user. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignmentScheduleInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentScheduleInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances"} # type: ignore + + @distributed_trace_async + async def get( + self, scope: str, role_assignment_schedule_instance_name: str, **kwargs: Any + ) -> _models.RoleAssignmentScheduleInstance: + """Gets the specified role assignment schedule instance. + + :param scope: The scope of the role assignments schedules. Required. + :type scope: str + :param role_assignment_schedule_instance_name: The name (hash of schedule name + time) of the + role assignment schedule to get. Required. + :type role_assignment_schedule_instance_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleInstance] + + request = build_get_request( + scope=scope, + role_assignment_schedule_instance_name=role_assignment_schedule_instance_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignmentScheduleInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances/{roleAssignmentScheduleInstanceName}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedule_requests_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedule_requests_operations.py new file mode 100644 index 00000000000..f4488f2ea60 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedule_requests_operations.py @@ -0,0 +1,556 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_assignment_schedule_requests_operations import ( + build_cancel_request, + build_create_request, + build_get_request, + build_list_for_scope_request, + build_validate_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RoleAssignmentScheduleRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.aio.AuthorizationManagementClient`'s + :attr:`role_assignment_schedule_requests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: _models.RoleAssignmentScheduleRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Creates a role assignment schedule request. + + :param scope: The scope of the role assignment schedule request to create. The scope can be any + REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Creates a role assignment schedule request. + + :param scope: The scope of the role assignment schedule request to create. The scope can be any + REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: Union[_models.RoleAssignmentScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Creates a role assignment schedule request. + + :param scope: The scope of the role assignment schedule request to create. The scope can be any + REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentScheduleRequest") + + request = build_create_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignmentScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}"} # type: ignore + + @distributed_trace_async + async def get( + self, scope: str, role_assignment_schedule_request_name: str, **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Get the specified role assignment schedule request. + + :param scope: The scope of the role assignment schedule request. Required. + :type scope: str + :param role_assignment_schedule_request_name: The name (guid) of the role assignment schedule + request to get. Required. + :type role_assignment_schedule_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequest] + + request = build_get_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignmentScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignmentScheduleRequest"]: + """Gets role assignment schedule requests for a scope. + + :param scope: The scope of the role assignments schedule requests. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignment schedule requests at or above the scope. Use $filter=principalId eq {id} to return + all role assignment schedule requests at, above or below the scope for the specified principal. + Use $filter=asRequestor() to return all role assignment schedule requests requested by the + current user. Use $filter=asTarget() to return all role assignment schedule requests created + for the current user. Use $filter=asApprover() to return all role assignment schedule requests + where the current user is an approver. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignmentScheduleRequest or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequestListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentScheduleRequestListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests"} # type: ignore + + @distributed_trace_async + async def cancel( # pylint: disable=inconsistent-return-statements + self, scope: str, role_assignment_schedule_request_name: str, **kwargs: Any + ) -> None: + """Cancels a pending role assignment schedule request. + + :param scope: The scope of the role assignment request to cancel. Required. + :type scope: str + :param role_assignment_schedule_request_name: The name of the role assignment request to + cancel. Required. + :type role_assignment_schedule_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_cancel_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + template_url=self.cancel.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + cancel.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}/cancel"} # type: ignore + + @overload + async def validate( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: _models.RoleAssignmentScheduleRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Validates a new role assignment schedule request. + + :param scope: The scope of the role assignment request to validate. Required. + :type scope: str + :param role_assignment_schedule_request_name: The name of the role assignment request to + validate. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def validate( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Validates a new role assignment schedule request. + + :param scope: The scope of the role assignment request to validate. Required. + :type scope: str + :param role_assignment_schedule_request_name: The name of the role assignment request to + validate. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def validate( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: Union[_models.RoleAssignmentScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Validates a new role assignment schedule request. + + :param scope: The scope of the role assignment request to validate. Required. + :type scope: str + :param role_assignment_schedule_request_name: The name of the role assignment request to + validate. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentScheduleRequest") + + request = build_validate_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignmentScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + validate.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}/validate"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedules_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedules_operations.py new file mode 100644 index 00000000000..8632c1348a3 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_assignment_schedules_operations.py @@ -0,0 +1,200 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_assignment_schedules_operations import build_get_request, build_list_for_scope_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RoleAssignmentSchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.aio.AuthorizationManagementClient`'s + :attr:`role_assignment_schedules` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, scope: str, role_assignment_schedule_name: str, **kwargs: Any + ) -> _models.RoleAssignmentSchedule: + """Get the specified role assignment schedule for a resource scope. + + :param scope: The scope of the role assignment schedule. Required. + :type scope: str + :param role_assignment_schedule_name: The name (guid) of the role assignment schedule to get. + Required. + :type role_assignment_schedule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentSchedule or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentSchedule] + + request = build_get_request( + scope=scope, + role_assignment_schedule_name=role_assignment_schedule_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignmentSchedule", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules/{roleAssignmentScheduleName}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignmentSchedule"]: + """Gets role assignment schedules for a resource scope. + + :param scope: The scope of the role assignments schedules. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role + assignment schedules at, above or below the scope for the specified principal. Use + $filter=assignedTo('{userId}') to return all role assignment schedules for the current user. + Use $filter=asTarget() to return all role assignment schedules created for the current user. + Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignmentSchedule or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentSchedule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentScheduleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedule_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedule_instances_operations.py new file mode 100644 index 00000000000..1addcecc8cf --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedule_instances_operations.py @@ -0,0 +1,203 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_eligibility_schedule_instances_operations import ( + build_get_request, + build_list_for_scope_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RoleEligibilityScheduleInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.aio.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedule_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleEligibilityScheduleInstance"]: + """Gets role eligibility schedule instances of a role eligibility schedule. + + :param scope: The scope of the role eligibility schedule. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role + assignment schedules at, above or below the scope for the specified principal. Use + $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use + $filter=asTarget() to return all role eligibility schedules created for the current user. + Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleEligibilityScheduleInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleEligibilityScheduleInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances"} # type: ignore + + @distributed_trace_async + async def get( + self, scope: str, role_eligibility_schedule_instance_name: str, **kwargs: Any + ) -> _models.RoleEligibilityScheduleInstance: + """Gets the specified role eligibility schedule instance. + + :param scope: The scope of the role eligibility schedules. Required. + :type scope: str + :param role_eligibility_schedule_instance_name: The name (hash of schedule name + time) of the + role eligibility schedule to get. Required. + :type role_eligibility_schedule_instance_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleInstance] + + request = build_get_request( + scope=scope, + role_eligibility_schedule_instance_name=role_eligibility_schedule_instance_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleEligibilityScheduleInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances/{roleEligibilityScheduleInstanceName}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedule_requests_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedule_requests_operations.py new file mode 100644 index 00000000000..509c518b93b --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedule_requests_operations.py @@ -0,0 +1,556 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_eligibility_schedule_requests_operations import ( + build_cancel_request, + build_create_request, + build_get_request, + build_list_for_scope_request, + build_validate_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RoleEligibilityScheduleRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.aio.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedule_requests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: _models.RoleEligibilityScheduleRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Creates a role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request to create. The scope can be + any REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It + can be any valid GUID. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Creates a role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request to create. The scope can be + any REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It + can be any valid GUID. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: Union[_models.RoleEligibilityScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Creates a role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request to create. The scope can be + any REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It + can be any valid GUID. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleEligibilityScheduleRequest") + + request = build_create_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleEligibilityScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}"} # type: ignore + + @distributed_trace_async + async def get( + self, scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Get the specified role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name (guid) of the role eligibility schedule + request to get. Required. + :type role_eligibility_schedule_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequest] + + request = build_get_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleEligibilityScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleEligibilityScheduleRequest"]: + """Gets role eligibility schedule requests for a scope. + + :param scope: The scope of the role eligibility schedule requests. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + eligibility schedule requests at or above the scope. Use $filter=principalId eq {id} to return + all role eligibility schedule requests at, above or below the scope for the specified + principal. Use $filter=asRequestor() to return all role eligibility schedule requests requested + by the current user. Use $filter=asTarget() to return all role eligibility schedule requests + created for the current user. Use $filter=asApprover() to return all role eligibility schedule + requests where the current user is an approver. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleEligibilityScheduleRequest or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequestListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleEligibilityScheduleRequestListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests"} # type: ignore + + @distributed_trace_async + async def cancel( # pylint: disable=inconsistent-return-statements + self, scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any + ) -> None: + """Cancels a pending role eligibility schedule request. + + :param scope: The scope of the role eligibility request to cancel. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility request to + cancel. Required. + :type role_eligibility_schedule_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_cancel_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + template_url=self.cancel.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + cancel.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}/cancel"} # type: ignore + + @overload + async def validate( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: _models.RoleEligibilityScheduleRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Validates a new role eligibility schedule request. + + :param scope: The scope of the role eligibility request to validate. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility request to + validate. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def validate( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Validates a new role eligibility schedule request. + + :param scope: The scope of the role eligibility request to validate. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility request to + validate. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def validate( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: Union[_models.RoleEligibilityScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Validates a new role eligibility schedule request. + + :param scope: The scope of the role eligibility request to validate. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility request to + validate. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleEligibilityScheduleRequest") + + request = build_validate_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleEligibilityScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + validate.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}/validate"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedules_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedules_operations.py new file mode 100644 index 00000000000..573ec559964 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_eligibility_schedules_operations.py @@ -0,0 +1,200 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_eligibility_schedules_operations import build_get_request, build_list_for_scope_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RoleEligibilitySchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.aio.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedules` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, scope: str, role_eligibility_schedule_name: str, **kwargs: Any + ) -> _models.RoleEligibilitySchedule: + """Get the specified role eligibility schedule for a resource scope. + + :param scope: The scope of the role eligibility schedule. Required. + :type scope: str + :param role_eligibility_schedule_name: The name (guid) of the role eligibility schedule to get. + Required. + :type role_eligibility_schedule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilitySchedule or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilitySchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilitySchedule] + + request = build_get_request( + scope=scope, + role_eligibility_schedule_name=role_eligibility_schedule_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleEligibilitySchedule", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules/{roleEligibilityScheduleName}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleEligibilitySchedule"]: + """Gets role eligibility schedules for a resource scope. + + :param scope: The scope of the role eligibility schedules. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + eligibility schedules at or above the scope. Use $filter=principalId eq {id} to return all role + eligibility schedules at, above or below the scope for the specified principal. Use + $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use + $filter=asTarget() to return all role eligibility schedules created for the current user. + Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleEligibilitySchedule or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilitySchedule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleEligibilityScheduleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_management_policies_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_management_policies_operations.py new file mode 100644 index 00000000000..f81040e9716 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_management_policies_operations.py @@ -0,0 +1,387 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_management_policies_operations import ( + build_delete_request, + build_get_request, + build_list_for_scope_request, + build_update_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RoleManagementPoliciesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.aio.AuthorizationManagementClient`'s + :attr:`role_management_policies` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, scope: str, role_management_policy_name: str, **kwargs: Any) -> _models.RoleManagementPolicy: + """Get the specified role management policy for a resource scope. + + :param scope: The scope of the role management policy. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to get. + Required. + :type role_management_policy_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicy] + + request = build_get_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleManagementPolicy", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore + + @overload + async def update( + self, + scope: str, + role_management_policy_name: str, + parameters: _models.RoleManagementPolicy, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicy: + """Update a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :param parameters: Parameters for the role management policy. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + scope: str, + role_management_policy_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicy: + """Update a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :param parameters: Parameters for the role management policy. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + scope: str, + role_management_policy_name: str, + parameters: Union[_models.RoleManagementPolicy, IO], + **kwargs: Any + ) -> _models.RoleManagementPolicy: + """Update a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :param parameters: Parameters for the role management policy. Is either a model type or a IO + type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicy] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleManagementPolicy") + + request = build_update_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleManagementPolicy", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, role_management_policy_name: str, **kwargs: Any + ) -> None: + """Delete a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.RoleManagementPolicy"]: + """Gets role management policies for a resource scope. + + :param scope: The scope of the role management policy. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleManagementPolicy or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleManagementPolicyListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_management_policy_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_management_policy_assignments_operations.py new file mode 100644 index 00000000000..b0b097fbddf --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/aio/operations/_role_management_policy_assignments_operations.py @@ -0,0 +1,390 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_management_policy_assignments_operations import ( + build_create_request, + build_delete_request, + build_get_request, + build_list_for_scope_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RoleManagementPolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.aio.AuthorizationManagementClient`'s + :attr:`role_management_policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, scope: str, role_management_policy_assignment_name: str, **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Get the specified role management policy assignment for a resource scope. + + :param scope: The scope of the role management policy. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to get. Required. + :type role_management_policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignment] + + request = build_get_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleManagementPolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore + + @overload + async def create( + self, + scope: str, + role_management_policy_assignment_name: str, + parameters: _models.RoleManagementPolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Create a role management policy assignment. + + :param scope: The scope of the role management policy assignment to upsert. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to upsert. Required. + :type role_management_policy_assignment_name: str + :param parameters: Parameters for the role management policy assignment. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + role_management_policy_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Create a role management policy assignment. + + :param scope: The scope of the role management policy assignment to upsert. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to upsert. Required. + :type role_management_policy_assignment_name: str + :param parameters: Parameters for the role management policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_management_policy_assignment_name: str, + parameters: Union[_models.RoleManagementPolicyAssignment, IO], + **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Create a role management policy assignment. + + :param scope: The scope of the role management policy assignment to upsert. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to upsert. Required. + :type role_management_policy_assignment_name: str + :param parameters: Parameters for the role management policy assignment. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleManagementPolicyAssignment") + + request = build_create_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleManagementPolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, role_management_policy_assignment_name: str, **kwargs: Any + ) -> None: + """Delete a role management policy assignment. + + :param scope: The scope of the role management policy assignment to delete. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to delete. Required. + :type role_management_policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.RoleManagementPolicyAssignment"]: + """Gets role management assignment policies for a resource scope. + + :param scope: The scope of the role management policy. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleManagementPolicyAssignment or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleManagementPolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/__init__.py new file mode 100644 index 00000000000..ef957fbb40f --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/__init__.py @@ -0,0 +1,149 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import ApprovalSettings +from ._models_py3 import ApprovalStage +from ._models_py3 import CloudErrorBody +from ._models_py3 import EligibleChildResource +from ._models_py3 import EligibleChildResourcesListResult +from ._models_py3 import ExpandedProperties +from ._models_py3 import ExpandedPropertiesPrincipal +from ._models_py3 import ExpandedPropertiesRoleDefinition +from ._models_py3 import ExpandedPropertiesScope +from ._models_py3 import Permission +from ._models_py3 import PolicyAssignmentProperties +from ._models_py3 import PolicyAssignmentPropertiesPolicy +from ._models_py3 import PolicyAssignmentPropertiesRoleDefinition +from ._models_py3 import PolicyAssignmentPropertiesScope +from ._models_py3 import PolicyProperties +from ._models_py3 import PolicyPropertiesScope +from ._models_py3 import Principal +from ._models_py3 import RoleAssignmentSchedule +from ._models_py3 import RoleAssignmentScheduleFilter +from ._models_py3 import RoleAssignmentScheduleInstance +from ._models_py3 import RoleAssignmentScheduleInstanceFilter +from ._models_py3 import RoleAssignmentScheduleInstanceListResult +from ._models_py3 import RoleAssignmentScheduleListResult +from ._models_py3 import RoleAssignmentScheduleRequest +from ._models_py3 import RoleAssignmentScheduleRequestFilter +from ._models_py3 import RoleAssignmentScheduleRequestListResult +from ._models_py3 import RoleAssignmentScheduleRequestPropertiesScheduleInfo +from ._models_py3 import RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration +from ._models_py3 import RoleAssignmentScheduleRequestPropertiesTicketInfo +from ._models_py3 import RoleEligibilitySchedule +from ._models_py3 import RoleEligibilityScheduleFilter +from ._models_py3 import RoleEligibilityScheduleInstance +from ._models_py3 import RoleEligibilityScheduleInstanceFilter +from ._models_py3 import RoleEligibilityScheduleInstanceListResult +from ._models_py3 import RoleEligibilityScheduleListResult +from ._models_py3 import RoleEligibilityScheduleRequest +from ._models_py3 import RoleEligibilityScheduleRequestFilter +from ._models_py3 import RoleEligibilityScheduleRequestListResult +from ._models_py3 import RoleEligibilityScheduleRequestPropertiesScheduleInfo +from ._models_py3 import RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration +from ._models_py3 import RoleEligibilityScheduleRequestPropertiesTicketInfo +from ._models_py3 import RoleManagementPolicy +from ._models_py3 import RoleManagementPolicyApprovalRule +from ._models_py3 import RoleManagementPolicyAssignment +from ._models_py3 import RoleManagementPolicyAssignmentListResult +from ._models_py3 import RoleManagementPolicyAuthenticationContextRule +from ._models_py3 import RoleManagementPolicyEnablementRule +from ._models_py3 import RoleManagementPolicyExpirationRule +from ._models_py3 import RoleManagementPolicyListResult +from ._models_py3 import RoleManagementPolicyNotificationRule +from ._models_py3 import RoleManagementPolicyRule +from ._models_py3 import RoleManagementPolicyRuleTarget +from ._models_py3 import UserSet + +from ._authorization_management_client_enums import ApprovalMode +from ._authorization_management_client_enums import AssignmentType +from ._authorization_management_client_enums import EnablementRules +from ._authorization_management_client_enums import MemberType +from ._authorization_management_client_enums import NotificationDeliveryMechanism +from ._authorization_management_client_enums import NotificationLevel +from ._authorization_management_client_enums import PrincipalType +from ._authorization_management_client_enums import RecipientType +from ._authorization_management_client_enums import RequestType +from ._authorization_management_client_enums import RoleManagementPolicyRuleType +from ._authorization_management_client_enums import Status +from ._authorization_management_client_enums import Type +from ._authorization_management_client_enums import UserType +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ApprovalSettings", + "ApprovalStage", + "CloudErrorBody", + "EligibleChildResource", + "EligibleChildResourcesListResult", + "ExpandedProperties", + "ExpandedPropertiesPrincipal", + "ExpandedPropertiesRoleDefinition", + "ExpandedPropertiesScope", + "Permission", + "PolicyAssignmentProperties", + "PolicyAssignmentPropertiesPolicy", + "PolicyAssignmentPropertiesRoleDefinition", + "PolicyAssignmentPropertiesScope", + "PolicyProperties", + "PolicyPropertiesScope", + "Principal", + "RoleAssignmentSchedule", + "RoleAssignmentScheduleFilter", + "RoleAssignmentScheduleInstance", + "RoleAssignmentScheduleInstanceFilter", + "RoleAssignmentScheduleInstanceListResult", + "RoleAssignmentScheduleListResult", + "RoleAssignmentScheduleRequest", + "RoleAssignmentScheduleRequestFilter", + "RoleAssignmentScheduleRequestListResult", + "RoleAssignmentScheduleRequestPropertiesScheduleInfo", + "RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration", + "RoleAssignmentScheduleRequestPropertiesTicketInfo", + "RoleEligibilitySchedule", + "RoleEligibilityScheduleFilter", + "RoleEligibilityScheduleInstance", + "RoleEligibilityScheduleInstanceFilter", + "RoleEligibilityScheduleInstanceListResult", + "RoleEligibilityScheduleListResult", + "RoleEligibilityScheduleRequest", + "RoleEligibilityScheduleRequestFilter", + "RoleEligibilityScheduleRequestListResult", + "RoleEligibilityScheduleRequestPropertiesScheduleInfo", + "RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration", + "RoleEligibilityScheduleRequestPropertiesTicketInfo", + "RoleManagementPolicy", + "RoleManagementPolicyApprovalRule", + "RoleManagementPolicyAssignment", + "RoleManagementPolicyAssignmentListResult", + "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", + "RoleManagementPolicyExpirationRule", + "RoleManagementPolicyListResult", + "RoleManagementPolicyNotificationRule", + "RoleManagementPolicyRule", + "RoleManagementPolicyRuleTarget", + "UserSet", + "ApprovalMode", + "AssignmentType", + "EnablementRules", + "MemberType", + "NotificationDeliveryMechanism", + "NotificationLevel", + "PrincipalType", + "RecipientType", + "RequestType", + "RoleManagementPolicyRuleType", + "Status", + "Type", + "UserType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_authorization_management_client_enums.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_authorization_management_client_enums.py new file mode 100644 index 00000000000..b7fe646a992 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_authorization_management_client_enums.py @@ -0,0 +1,140 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ApprovalMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of rule.""" + + SINGLE_STAGE = "SingleStage" + SERIAL = "Serial" + PARALLEL = "Parallel" + NO_APPROVAL = "NoApproval" + + +class AssignmentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Assignment type of the role assignment schedule.""" + + ACTIVATED = "Activated" + ASSIGNED = "Assigned" + + +class EnablementRules(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of enablement rule.""" + + MULTI_FACTOR_AUTHENTICATION = "MultiFactorAuthentication" + JUSTIFICATION = "Justification" + TICKETING = "Ticketing" + + +class MemberType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Membership type of the role assignment schedule.""" + + INHERITED = "Inherited" + DIRECT = "Direct" + GROUP = "Group" + + +class NotificationDeliveryMechanism(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of notification.""" + + EMAIL = "Email" + + +class NotificationLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The notification level.""" + + NONE = "None" + CRITICAL = "Critical" + ALL = "All" + + +class PrincipalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The principal type of the assigned principal ID.""" + + USER = "User" + GROUP = "Group" + SERVICE_PRINCIPAL = "ServicePrincipal" + FOREIGN_GROUP = "ForeignGroup" + DEVICE = "Device" + + +class RecipientType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The recipient type.""" + + REQUESTOR = "Requestor" + APPROVER = "Approver" + ADMIN = "Admin" + + +class RequestType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the role assignment schedule request. Eg: SelfActivate, AdminAssign etc.""" + + ADMIN_ASSIGN = "AdminAssign" + ADMIN_REMOVE = "AdminRemove" + ADMIN_UPDATE = "AdminUpdate" + ADMIN_EXTEND = "AdminExtend" + ADMIN_RENEW = "AdminRenew" + SELF_ACTIVATE = "SelfActivate" + SELF_DEACTIVATE = "SelfDeactivate" + SELF_EXTEND = "SelfExtend" + SELF_RENEW = "SelfRenew" + + +class RoleManagementPolicyRuleType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of rule.""" + + ROLE_MANAGEMENT_POLICY_APPROVAL_RULE = "RoleManagementPolicyApprovalRule" + ROLE_MANAGEMENT_POLICY_AUTHENTICATION_CONTEXT_RULE = "RoleManagementPolicyAuthenticationContextRule" + ROLE_MANAGEMENT_POLICY_ENABLEMENT_RULE = "RoleManagementPolicyEnablementRule" + ROLE_MANAGEMENT_POLICY_EXPIRATION_RULE = "RoleManagementPolicyExpirationRule" + ROLE_MANAGEMENT_POLICY_NOTIFICATION_RULE = "RoleManagementPolicyNotificationRule" + + +class Status(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the role assignment schedule.""" + + ACCEPTED = "Accepted" + PENDING_EVALUATION = "PendingEvaluation" + GRANTED = "Granted" + DENIED = "Denied" + PENDING_PROVISIONING = "PendingProvisioning" + PROVISIONED = "Provisioned" + PENDING_REVOCATION = "PendingRevocation" + REVOKED = "Revoked" + CANCELED = "Canceled" + FAILED = "Failed" + PENDING_APPROVAL_PROVISIONING = "PendingApprovalProvisioning" + PENDING_APPROVAL = "PendingApproval" + FAILED_AS_RESOURCE_IS_LOCKED = "FailedAsResourceIsLocked" + PENDING_ADMIN_DECISION = "PendingAdminDecision" + ADMIN_APPROVED = "AdminApproved" + ADMIN_DENIED = "AdminDenied" + TIMED_OUT = "TimedOut" + PROVISIONING_STARTED = "ProvisioningStarted" + INVALID = "Invalid" + PENDING_SCHEDULE_CREATION = "PendingScheduleCreation" + SCHEDULE_CREATED = "ScheduleCreated" + PENDING_EXTERNAL_PROVISIONING = "PendingExternalProvisioning" + + +class Type(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the role assignment schedule expiration.""" + + AFTER_DURATION = "AfterDuration" + AFTER_DATE_TIME = "AfterDateTime" + NO_EXPIRATION = "NoExpiration" + + +class UserType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of user.""" + + USER = "User" + GROUP = "Group" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_models_py3.py new file mode 100644 index 00000000000..fbaefb8b5e2 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_models_py3.py @@ -0,0 +1,3118 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class ApprovalSettings(_serialization.Model): + """The approval settings. + + :ivar is_approval_required: Determines whether approval is required or not. + :vartype is_approval_required: bool + :ivar is_approval_required_for_extension: Determines whether approval is required for + assignment extension. + :vartype is_approval_required_for_extension: bool + :ivar is_requestor_justification_required: Determine whether requestor justification is + required. + :vartype is_requestor_justification_required: bool + :ivar approval_mode: The type of rule. Known values are: "SingleStage", "Serial", "Parallel", + and "NoApproval". + :vartype approval_mode: str or ~azure.mgmt.authorization.v2020_10_01.models.ApprovalMode + :ivar approval_stages: The approval stages of the request. + :vartype approval_stages: list[~azure.mgmt.authorization.v2020_10_01.models.ApprovalStage] + """ + + _attribute_map = { + "is_approval_required": {"key": "isApprovalRequired", "type": "bool"}, + "is_approval_required_for_extension": {"key": "isApprovalRequiredForExtension", "type": "bool"}, + "is_requestor_justification_required": {"key": "isRequestorJustificationRequired", "type": "bool"}, + "approval_mode": {"key": "approvalMode", "type": "str"}, + "approval_stages": {"key": "approvalStages", "type": "[ApprovalStage]"}, + } + + def __init__( + self, + *, + is_approval_required: Optional[bool] = None, + is_approval_required_for_extension: Optional[bool] = None, + is_requestor_justification_required: Optional[bool] = None, + approval_mode: Optional[Union[str, "_models.ApprovalMode"]] = None, + approval_stages: Optional[List["_models.ApprovalStage"]] = None, + **kwargs + ): + """ + :keyword is_approval_required: Determines whether approval is required or not. + :paramtype is_approval_required: bool + :keyword is_approval_required_for_extension: Determines whether approval is required for + assignment extension. + :paramtype is_approval_required_for_extension: bool + :keyword is_requestor_justification_required: Determine whether requestor justification is + required. + :paramtype is_requestor_justification_required: bool + :keyword approval_mode: The type of rule. Known values are: "SingleStage", "Serial", + "Parallel", and "NoApproval". + :paramtype approval_mode: str or ~azure.mgmt.authorization.v2020_10_01.models.ApprovalMode + :keyword approval_stages: The approval stages of the request. + :paramtype approval_stages: list[~azure.mgmt.authorization.v2020_10_01.models.ApprovalStage] + """ + super().__init__(**kwargs) + self.is_approval_required = is_approval_required + self.is_approval_required_for_extension = is_approval_required_for_extension + self.is_requestor_justification_required = is_requestor_justification_required + self.approval_mode = approval_mode + self.approval_stages = approval_stages + + +class ApprovalStage(_serialization.Model): + """The approval stage. + + :ivar approval_stage_time_out_in_days: The time in days when approval request would be timed + out. + :vartype approval_stage_time_out_in_days: int + :ivar is_approver_justification_required: Determines whether approver need to provide + justification for his decision. + :vartype is_approver_justification_required: bool + :ivar escalation_time_in_minutes: The time in minutes when the approval request would be + escalated if the primary approver does not approve. + :vartype escalation_time_in_minutes: int + :ivar primary_approvers: The primary approver of the request. + :vartype primary_approvers: list[~azure.mgmt.authorization.v2020_10_01.models.UserSet] + :ivar is_escalation_enabled: The value determine whether escalation feature is enabled. + :vartype is_escalation_enabled: bool + :ivar escalation_approvers: The escalation approver of the request. + :vartype escalation_approvers: list[~azure.mgmt.authorization.v2020_10_01.models.UserSet] + """ + + _attribute_map = { + "approval_stage_time_out_in_days": {"key": "approvalStageTimeOutInDays", "type": "int"}, + "is_approver_justification_required": {"key": "isApproverJustificationRequired", "type": "bool"}, + "escalation_time_in_minutes": {"key": "escalationTimeInMinutes", "type": "int"}, + "primary_approvers": {"key": "primaryApprovers", "type": "[UserSet]"}, + "is_escalation_enabled": {"key": "isEscalationEnabled", "type": "bool"}, + "escalation_approvers": {"key": "escalationApprovers", "type": "[UserSet]"}, + } + + def __init__( + self, + *, + approval_stage_time_out_in_days: Optional[int] = None, + is_approver_justification_required: Optional[bool] = None, + escalation_time_in_minutes: Optional[int] = None, + primary_approvers: Optional[List["_models.UserSet"]] = None, + is_escalation_enabled: Optional[bool] = None, + escalation_approvers: Optional[List["_models.UserSet"]] = None, + **kwargs + ): + """ + :keyword approval_stage_time_out_in_days: The time in days when approval request would be timed + out. + :paramtype approval_stage_time_out_in_days: int + :keyword is_approver_justification_required: Determines whether approver need to provide + justification for his decision. + :paramtype is_approver_justification_required: bool + :keyword escalation_time_in_minutes: The time in minutes when the approval request would be + escalated if the primary approver does not approve. + :paramtype escalation_time_in_minutes: int + :keyword primary_approvers: The primary approver of the request. + :paramtype primary_approvers: list[~azure.mgmt.authorization.v2020_10_01.models.UserSet] + :keyword is_escalation_enabled: The value determine whether escalation feature is enabled. + :paramtype is_escalation_enabled: bool + :keyword escalation_approvers: The escalation approver of the request. + :paramtype escalation_approvers: list[~azure.mgmt.authorization.v2020_10_01.models.UserSet] + """ + super().__init__(**kwargs) + self.approval_stage_time_out_in_days = approval_stage_time_out_in_days + self.is_approver_justification_required = is_approver_justification_required + self.escalation_time_in_minutes = escalation_time_in_minutes + self.primary_approvers = primary_approvers + self.is_escalation_enabled = is_escalation_enabled + self.escalation_approvers = escalation_approvers + + +class CloudErrorBody(_serialization.Model): + """An error response from the service. + + :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. + :vartype code: str + :ivar message: A message describing the error, intended to be suitable for display in a user + interface. + :vartype message: str + """ + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs): + """ + :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. + :paramtype code: str + :keyword message: A message describing the error, intended to be suitable for display in a user + interface. + :paramtype message: str + """ + super().__init__(**kwargs) + self.code = code + self.message = message + + +class EligibleChildResource(_serialization.Model): + """Eligible child resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The resource scope Id. + :vartype id: str + :ivar name: The resource name. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class EligibleChildResourcesListResult(_serialization.Model): + """Eligible child resources list operation result. + + :ivar value: Eligible child resource list. + :vartype value: list[~azure.mgmt.authorization.v2020_10_01.models.EligibleChildResource] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[EligibleChildResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.EligibleChildResource"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Eligible child resource list. + :paramtype value: list[~azure.mgmt.authorization.v2020_10_01.models.EligibleChildResource] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ExpandedProperties(_serialization.Model): + """ExpandedProperties. + + :ivar scope: Details of the resource scope. + :vartype scope: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedPropertiesScope + :ivar role_definition: Details of role definition. + :vartype role_definition: + ~azure.mgmt.authorization.v2020_10_01.models.ExpandedPropertiesRoleDefinition + :ivar principal: Details of the principal. + :vartype principal: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedPropertiesPrincipal + """ + + _attribute_map = { + "scope": {"key": "scope", "type": "ExpandedPropertiesScope"}, + "role_definition": {"key": "roleDefinition", "type": "ExpandedPropertiesRoleDefinition"}, + "principal": {"key": "principal", "type": "ExpandedPropertiesPrincipal"}, + } + + def __init__( + self, + *, + scope: Optional["_models.ExpandedPropertiesScope"] = None, + role_definition: Optional["_models.ExpandedPropertiesRoleDefinition"] = None, + principal: Optional["_models.ExpandedPropertiesPrincipal"] = None, + **kwargs + ): + """ + :keyword scope: Details of the resource scope. + :paramtype scope: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedPropertiesScope + :keyword role_definition: Details of role definition. + :paramtype role_definition: + ~azure.mgmt.authorization.v2020_10_01.models.ExpandedPropertiesRoleDefinition + :keyword principal: Details of the principal. + :paramtype principal: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedPropertiesPrincipal + """ + super().__init__(**kwargs) + self.scope = scope + self.role_definition = role_definition + self.principal = principal + + +class ExpandedPropertiesPrincipal(_serialization.Model): + """Details of the principal. + + :ivar id: Id of the principal. + :vartype id: str + :ivar display_name: Display name of the principal. + :vartype display_name: str + :ivar email: Email id of the principal. + :vartype email: str + :ivar type: Type of the principal. + :vartype type: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "email": {"key": "email", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + display_name: Optional[str] = None, + email: Optional[str] = None, + type: Optional[str] = None, + **kwargs + ): + """ + :keyword id: Id of the principal. + :paramtype id: str + :keyword display_name: Display name of the principal. + :paramtype display_name: str + :keyword email: Email id of the principal. + :paramtype email: str + :keyword type: Type of the principal. + :paramtype type: str + """ + super().__init__(**kwargs) + self.id = id + self.display_name = display_name + self.email = email + self.type = type + + +class ExpandedPropertiesRoleDefinition(_serialization.Model): + """Details of role definition. + + :ivar id: Id of the role definition. + :vartype id: str + :ivar display_name: Display name of the role definition. + :vartype display_name: str + :ivar type: Type of the role definition. + :vartype type: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + display_name: Optional[str] = None, + type: Optional[str] = None, + **kwargs + ): + """ + :keyword id: Id of the role definition. + :paramtype id: str + :keyword display_name: Display name of the role definition. + :paramtype display_name: str + :keyword type: Type of the role definition. + :paramtype type: str + """ + super().__init__(**kwargs) + self.id = id + self.display_name = display_name + self.type = type + + +class ExpandedPropertiesScope(_serialization.Model): + """Details of the resource scope. + + :ivar id: Scope id of the resource. + :vartype id: str + :ivar display_name: Display name of the resource. + :vartype display_name: str + :ivar type: Type of the resource. + :vartype type: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + display_name: Optional[str] = None, + type: Optional[str] = None, + **kwargs + ): + """ + :keyword id: Scope id of the resource. + :paramtype id: str + :keyword display_name: Display name of the resource. + :paramtype display_name: str + :keyword type: Type of the resource. + :paramtype type: str + """ + super().__init__(**kwargs) + self.id = id + self.display_name = display_name + self.type = type + + +class Permission(_serialization.Model): + """Role definition permissions. + + :ivar actions: Allowed actions. + :vartype actions: list[str] + :ivar not_actions: Denied actions. + :vartype not_actions: list[str] + :ivar data_actions: Allowed Data actions. + :vartype data_actions: list[str] + :ivar not_data_actions: Denied Data actions. + :vartype not_data_actions: list[str] + """ + + _attribute_map = { + "actions": {"key": "actions", "type": "[str]"}, + "not_actions": {"key": "notActions", "type": "[str]"}, + "data_actions": {"key": "dataActions", "type": "[str]"}, + "not_data_actions": {"key": "notDataActions", "type": "[str]"}, + } + + def __init__( + self, + *, + actions: Optional[List[str]] = None, + not_actions: Optional[List[str]] = None, + data_actions: Optional[List[str]] = None, + not_data_actions: Optional[List[str]] = None, + **kwargs + ): + """ + :keyword actions: Allowed actions. + :paramtype actions: list[str] + :keyword not_actions: Denied actions. + :paramtype not_actions: list[str] + :keyword data_actions: Allowed Data actions. + :paramtype data_actions: list[str] + :keyword not_data_actions: Denied Data actions. + :paramtype not_data_actions: list[str] + """ + super().__init__(**kwargs) + self.actions = actions + self.not_actions = not_actions + self.data_actions = data_actions + self.not_data_actions = not_data_actions + + +class PolicyAssignmentProperties(_serialization.Model): + """Expanded info of resource scope, role definition and policy. + + :ivar scope: Details of the resource scope. + :vartype scope: ~azure.mgmt.authorization.v2020_10_01.models.PolicyAssignmentPropertiesScope + :ivar role_definition: Details of role definition. + :vartype role_definition: + ~azure.mgmt.authorization.v2020_10_01.models.PolicyAssignmentPropertiesRoleDefinition + :ivar policy: Details of the policy. + :vartype policy: ~azure.mgmt.authorization.v2020_10_01.models.PolicyAssignmentPropertiesPolicy + """ + + _attribute_map = { + "scope": {"key": "scope", "type": "PolicyAssignmentPropertiesScope"}, + "role_definition": {"key": "roleDefinition", "type": "PolicyAssignmentPropertiesRoleDefinition"}, + "policy": {"key": "policy", "type": "PolicyAssignmentPropertiesPolicy"}, + } + + def __init__( + self, + *, + scope: Optional["_models.PolicyAssignmentPropertiesScope"] = None, + role_definition: Optional["_models.PolicyAssignmentPropertiesRoleDefinition"] = None, + policy: Optional["_models.PolicyAssignmentPropertiesPolicy"] = None, + **kwargs + ): + """ + :keyword scope: Details of the resource scope. + :paramtype scope: ~azure.mgmt.authorization.v2020_10_01.models.PolicyAssignmentPropertiesScope + :keyword role_definition: Details of role definition. + :paramtype role_definition: + ~azure.mgmt.authorization.v2020_10_01.models.PolicyAssignmentPropertiesRoleDefinition + :keyword policy: Details of the policy. + :paramtype policy: + ~azure.mgmt.authorization.v2020_10_01.models.PolicyAssignmentPropertiesPolicy + """ + super().__init__(**kwargs) + self.scope = scope + self.role_definition = role_definition + self.policy = policy + + +class PolicyAssignmentPropertiesPolicy(_serialization.Model): + """Details of the policy. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Id of the policy. + :vartype id: str + :ivar last_modified_by: The name of the entity last modified it. + :vartype last_modified_by: ~azure.mgmt.authorization.v2020_10_01.models.Principal + :ivar last_modified_date_time: The last modified date time. + :vartype last_modified_date_time: ~datetime.datetime + """ + + _validation = { + "last_modified_by": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "Principal"}, + "last_modified_date_time": {"key": "lastModifiedDateTime", "type": "iso-8601"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + last_modified_date_time: Optional[datetime.datetime] = None, + **kwargs + ): + """ + :keyword id: Id of the policy. + :paramtype id: str + :keyword last_modified_date_time: The last modified date time. + :paramtype last_modified_date_time: ~datetime.datetime + """ + super().__init__(**kwargs) + self.id = id + self.last_modified_by = None + self.last_modified_date_time = last_modified_date_time + + +class PolicyAssignmentPropertiesRoleDefinition(_serialization.Model): + """Details of role definition. + + :ivar id: Id of the role definition. + :vartype id: str + :ivar display_name: Display name of the role definition. + :vartype display_name: str + :ivar type: Type of the role definition. + :vartype type: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + display_name: Optional[str] = None, + type: Optional[str] = None, + **kwargs + ): + """ + :keyword id: Id of the role definition. + :paramtype id: str + :keyword display_name: Display name of the role definition. + :paramtype display_name: str + :keyword type: Type of the role definition. + :paramtype type: str + """ + super().__init__(**kwargs) + self.id = id + self.display_name = display_name + self.type = type + + +class PolicyAssignmentPropertiesScope(_serialization.Model): + """Details of the resource scope. + + :ivar id: Scope id of the resource. + :vartype id: str + :ivar display_name: Display name of the resource. + :vartype display_name: str + :ivar type: Type of the resource. + :vartype type: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + display_name: Optional[str] = None, + type: Optional[str] = None, + **kwargs + ): + """ + :keyword id: Scope id of the resource. + :paramtype id: str + :keyword display_name: Display name of the resource. + :paramtype display_name: str + :keyword type: Type of the resource. + :paramtype type: str + """ + super().__init__(**kwargs) + self.id = id + self.display_name = display_name + self.type = type + + +class PolicyProperties(_serialization.Model): + """Expanded info of resource scope. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar scope: Details of the resource scope. + :vartype scope: ~azure.mgmt.authorization.v2020_10_01.models.PolicyPropertiesScope + """ + + _validation = { + "scope": {"readonly": True}, + } + + _attribute_map = { + "scope": {"key": "scope", "type": "PolicyPropertiesScope"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.scope = None + + +class PolicyPropertiesScope(_serialization.Model): + """Details of the resource scope. + + :ivar id: Scope id of the resource. + :vartype id: str + :ivar display_name: Display name of the resource. + :vartype display_name: str + :ivar type: Type of the resource. + :vartype type: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + display_name: Optional[str] = None, + type: Optional[str] = None, + **kwargs + ): + """ + :keyword id: Scope id of the resource. + :paramtype id: str + :keyword display_name: Display name of the resource. + :paramtype display_name: str + :keyword type: Type of the resource. + :paramtype type: str + """ + super().__init__(**kwargs) + self.id = id + self.display_name = display_name + self.type = type + + +class Principal(_serialization.Model): + """The name of the entity last modified it. + + :ivar id: The id of the principal made changes. + :vartype id: str + :ivar display_name: The name of the principal made changes. + :vartype display_name: str + :ivar type: Type of principal such as user , group etc. + :vartype type: str + :ivar email: Email of principal. + :vartype email: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "email": {"key": "email", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + display_name: Optional[str] = None, + type: Optional[str] = None, + email: Optional[str] = None, + **kwargs + ): + """ + :keyword id: The id of the principal made changes. + :paramtype id: str + :keyword display_name: The name of the principal made changes. + :paramtype display_name: str + :keyword type: Type of principal such as user , group etc. + :paramtype type: str + :keyword email: Email of principal. + :paramtype email: str + """ + super().__init__(**kwargs) + self.id = id + self.display_name = display_name + self.type = type + self.email = email + + +class RoleAssignmentSchedule(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Role Assignment schedule. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role assignment schedule Id. + :vartype id: str + :ivar name: The role assignment schedule name. + :vartype name: str + :ivar type: The role assignment schedule type. + :vartype type: str + :ivar scope: The role assignment schedule scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or ~azure.mgmt.authorization.v2020_10_01.models.PrincipalType + :ivar role_assignment_schedule_request_id: The id of roleAssignmentScheduleRequest used to + create this roleAssignmentSchedule. + :vartype role_assignment_schedule_request_id: str + :ivar linked_role_eligibility_schedule_id: The id of roleEligibilitySchedule used to activated + this roleAssignmentSchedule. + :vartype linked_role_eligibility_schedule_id: str + :ivar assignment_type: Assignment type of the role assignment schedule. Known values are: + "Activated" and "Assigned". + :vartype assignment_type: str or ~azure.mgmt.authorization.v2020_10_01.models.AssignmentType + :ivar member_type: Membership type of the role assignment schedule. Known values are: + "Inherited", "Direct", and "Group". + :vartype member_type: str or ~azure.mgmt.authorization.v2020_10_01.models.MemberType + :ivar status: The status of the role assignment schedule. Known values are: "Accepted", + "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :vartype status: str or ~azure.mgmt.authorization.v2020_10_01.models.Status + :ivar start_date_time: Start DateTime when role assignment schedule. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: End DateTime when role assignment schedule. + :vartype end_date_time: ~datetime.datetime + :ivar condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: DateTime when role assignment schedule was created. + :vartype created_on: ~datetime.datetime + :ivar updated_on: DateTime when role assignment schedule was modified. + :vartype updated_on: ~datetime.datetime + :ivar expanded_properties: Additional properties of principal, scope and role definition. + :vartype expanded_properties: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "role_assignment_schedule_request_id": {"key": "properties.roleAssignmentScheduleRequestId", "type": "str"}, + "linked_role_eligibility_schedule_id": {"key": "properties.linkedRoleEligibilityScheduleId", "type": "str"}, + "assignment_type": {"key": "properties.assignmentType", "type": "str"}, + "member_type": {"key": "properties.memberType", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "updated_on": {"key": "properties.updatedOn", "type": "iso-8601"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, + } + + def __init__( + self, + *, + scope: Optional[str] = None, + role_definition_id: Optional[str] = None, + principal_id: Optional[str] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, + role_assignment_schedule_request_id: Optional[str] = None, + linked_role_eligibility_schedule_id: Optional[str] = None, + assignment_type: Optional[Union[str, "_models.AssignmentType"]] = None, + member_type: Optional[Union[str, "_models.MemberType"]] = None, + status: Optional[Union[str, "_models.Status"]] = None, + start_date_time: Optional[datetime.datetime] = None, + end_date_time: Optional[datetime.datetime] = None, + condition: Optional[str] = None, + condition_version: Optional[str] = None, + created_on: Optional[datetime.datetime] = None, + updated_on: Optional[datetime.datetime] = None, + expanded_properties: Optional["_models.ExpandedProperties"] = None, + **kwargs + ): + """ + :keyword scope: The role assignment schedule scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or ~azure.mgmt.authorization.v2020_10_01.models.PrincipalType + :keyword role_assignment_schedule_request_id: The id of roleAssignmentScheduleRequest used to + create this roleAssignmentSchedule. + :paramtype role_assignment_schedule_request_id: str + :keyword linked_role_eligibility_schedule_id: The id of roleEligibilitySchedule used to + activated this roleAssignmentSchedule. + :paramtype linked_role_eligibility_schedule_id: str + :keyword assignment_type: Assignment type of the role assignment schedule. Known values are: + "Activated" and "Assigned". + :paramtype assignment_type: str or ~azure.mgmt.authorization.v2020_10_01.models.AssignmentType + :keyword member_type: Membership type of the role assignment schedule. Known values are: + "Inherited", "Direct", and "Group". + :paramtype member_type: str or ~azure.mgmt.authorization.v2020_10_01.models.MemberType + :keyword status: The status of the role assignment schedule. Known values are: "Accepted", + "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :paramtype status: str or ~azure.mgmt.authorization.v2020_10_01.models.Status + :keyword start_date_time: Start DateTime when role assignment schedule. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: End DateTime when role assignment schedule. + :paramtype end_date_time: ~datetime.datetime + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword created_on: DateTime when role assignment schedule was created. + :paramtype created_on: ~datetime.datetime + :keyword updated_on: DateTime when role assignment schedule was modified. + :paramtype updated_on: ~datetime.datetime + :keyword expanded_properties: Additional properties of principal, scope and role definition. + :paramtype expanded_properties: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedProperties + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.scope = scope + self.role_definition_id = role_definition_id + self.principal_id = principal_id + self.principal_type = principal_type + self.role_assignment_schedule_request_id = role_assignment_schedule_request_id + self.linked_role_eligibility_schedule_id = linked_role_eligibility_schedule_id + self.assignment_type = assignment_type + self.member_type = member_type + self.status = status + self.start_date_time = start_date_time + self.end_date_time = end_date_time + self.condition = condition + self.condition_version = condition_version + self.created_on = created_on + self.updated_on = updated_on + self.expanded_properties = expanded_properties + + +class RoleAssignmentScheduleFilter(_serialization.Model): + """Role assignment schedule filter. + + :ivar principal_id: Returns role assignment schedule of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role assignment schedule of the specific role definition. + :vartype role_definition_id: str + :ivar status: Returns role assignment schedule instances of the specific status. + :vartype status: str + """ + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "status": {"key": "status", "type": "str"}, + } + + def __init__( + self, + *, + principal_id: Optional[str] = None, + role_definition_id: Optional[str] = None, + status: Optional[str] = None, + **kwargs + ): + """ + :keyword principal_id: Returns role assignment schedule of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role assignment schedule of the specific role definition. + :paramtype role_definition_id: str + :keyword status: Returns role assignment schedule instances of the specific status. + :paramtype status: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.role_definition_id = role_definition_id + self.status = status + + +class RoleAssignmentScheduleInstance(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Information about current or upcoming role assignment schedule instance. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role assignment schedule instance ID. + :vartype id: str + :ivar name: The role assignment schedule instance name. + :vartype name: str + :ivar type: The role assignment schedule instance type. + :vartype type: str + :ivar scope: The role assignment schedule scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or ~azure.mgmt.authorization.v2020_10_01.models.PrincipalType + :ivar role_assignment_schedule_id: Id of the master role assignment schedule. + :vartype role_assignment_schedule_id: str + :ivar origin_role_assignment_id: Role Assignment Id in external system. + :vartype origin_role_assignment_id: str + :ivar status: The status of the role assignment schedule instance. Known values are: + "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :vartype status: str or ~azure.mgmt.authorization.v2020_10_01.models.Status + :ivar start_date_time: The startDateTime of the role assignment schedule instance. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: The endDateTime of the role assignment schedule instance. + :vartype end_date_time: ~datetime.datetime + :ivar linked_role_eligibility_schedule_id: roleEligibilityScheduleId used to activate. + :vartype linked_role_eligibility_schedule_id: str + :ivar linked_role_eligibility_schedule_instance_id: roleEligibilityScheduleInstanceId linked to + this roleAssignmentScheduleInstance. + :vartype linked_role_eligibility_schedule_instance_id: str + :ivar assignment_type: Assignment type of the role assignment schedule. Known values are: + "Activated" and "Assigned". + :vartype assignment_type: str or ~azure.mgmt.authorization.v2020_10_01.models.AssignmentType + :ivar member_type: Membership type of the role assignment schedule. Known values are: + "Inherited", "Direct", and "Group". + :vartype member_type: str or ~azure.mgmt.authorization.v2020_10_01.models.MemberType + :ivar condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: DateTime when role assignment schedule was created. + :vartype created_on: ~datetime.datetime + :ivar expanded_properties: Additional properties of principal, scope and role definition. + :vartype expanded_properties: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "role_assignment_schedule_id": {"key": "properties.roleAssignmentScheduleId", "type": "str"}, + "origin_role_assignment_id": {"key": "properties.originRoleAssignmentId", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, + "linked_role_eligibility_schedule_id": {"key": "properties.linkedRoleEligibilityScheduleId", "type": "str"}, + "linked_role_eligibility_schedule_instance_id": { + "key": "properties.linkedRoleEligibilityScheduleInstanceId", + "type": "str", + }, + "assignment_type": {"key": "properties.assignmentType", "type": "str"}, + "member_type": {"key": "properties.memberType", "type": "str"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, + } + + def __init__( + self, + *, + scope: Optional[str] = None, + role_definition_id: Optional[str] = None, + principal_id: Optional[str] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, + role_assignment_schedule_id: Optional[str] = None, + origin_role_assignment_id: Optional[str] = None, + status: Optional[Union[str, "_models.Status"]] = None, + start_date_time: Optional[datetime.datetime] = None, + end_date_time: Optional[datetime.datetime] = None, + linked_role_eligibility_schedule_id: Optional[str] = None, + linked_role_eligibility_schedule_instance_id: Optional[str] = None, + assignment_type: Optional[Union[str, "_models.AssignmentType"]] = None, + member_type: Optional[Union[str, "_models.MemberType"]] = None, + condition: Optional[str] = None, + condition_version: Optional[str] = None, + created_on: Optional[datetime.datetime] = None, + expanded_properties: Optional["_models.ExpandedProperties"] = None, + **kwargs + ): + """ + :keyword scope: The role assignment schedule scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or ~azure.mgmt.authorization.v2020_10_01.models.PrincipalType + :keyword role_assignment_schedule_id: Id of the master role assignment schedule. + :paramtype role_assignment_schedule_id: str + :keyword origin_role_assignment_id: Role Assignment Id in external system. + :paramtype origin_role_assignment_id: str + :keyword status: The status of the role assignment schedule instance. Known values are: + "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :paramtype status: str or ~azure.mgmt.authorization.v2020_10_01.models.Status + :keyword start_date_time: The startDateTime of the role assignment schedule instance. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: The endDateTime of the role assignment schedule instance. + :paramtype end_date_time: ~datetime.datetime + :keyword linked_role_eligibility_schedule_id: roleEligibilityScheduleId used to activate. + :paramtype linked_role_eligibility_schedule_id: str + :keyword linked_role_eligibility_schedule_instance_id: roleEligibilityScheduleInstanceId linked + to this roleAssignmentScheduleInstance. + :paramtype linked_role_eligibility_schedule_instance_id: str + :keyword assignment_type: Assignment type of the role assignment schedule. Known values are: + "Activated" and "Assigned". + :paramtype assignment_type: str or ~azure.mgmt.authorization.v2020_10_01.models.AssignmentType + :keyword member_type: Membership type of the role assignment schedule. Known values are: + "Inherited", "Direct", and "Group". + :paramtype member_type: str or ~azure.mgmt.authorization.v2020_10_01.models.MemberType + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword created_on: DateTime when role assignment schedule was created. + :paramtype created_on: ~datetime.datetime + :keyword expanded_properties: Additional properties of principal, scope and role definition. + :paramtype expanded_properties: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedProperties + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.scope = scope + self.role_definition_id = role_definition_id + self.principal_id = principal_id + self.principal_type = principal_type + self.role_assignment_schedule_id = role_assignment_schedule_id + self.origin_role_assignment_id = origin_role_assignment_id + self.status = status + self.start_date_time = start_date_time + self.end_date_time = end_date_time + self.linked_role_eligibility_schedule_id = linked_role_eligibility_schedule_id + self.linked_role_eligibility_schedule_instance_id = linked_role_eligibility_schedule_instance_id + self.assignment_type = assignment_type + self.member_type = member_type + self.condition = condition + self.condition_version = condition_version + self.created_on = created_on + self.expanded_properties = expanded_properties + + +class RoleAssignmentScheduleInstanceFilter(_serialization.Model): + """Role assignment schedule instance filter. + + :ivar principal_id: Returns role assignment schedule instances of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role assignment schedule instances of the specific role + definition. + :vartype role_definition_id: str + :ivar status: Returns role assignment schedule instances of the specific status. + :vartype status: str + :ivar role_assignment_schedule_id: Returns role assignment schedule instances belonging to a + specific role assignment schedule. + :vartype role_assignment_schedule_id: str + """ + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "role_assignment_schedule_id": {"key": "roleAssignmentScheduleId", "type": "str"}, + } + + def __init__( + self, + *, + principal_id: Optional[str] = None, + role_definition_id: Optional[str] = None, + status: Optional[str] = None, + role_assignment_schedule_id: Optional[str] = None, + **kwargs + ): + """ + :keyword principal_id: Returns role assignment schedule instances of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role assignment schedule instances of the specific role + definition. + :paramtype role_definition_id: str + :keyword status: Returns role assignment schedule instances of the specific status. + :paramtype status: str + :keyword role_assignment_schedule_id: Returns role assignment schedule instances belonging to a + specific role assignment schedule. + :paramtype role_assignment_schedule_id: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.role_definition_id = role_definition_id + self.status = status + self.role_assignment_schedule_id = role_assignment_schedule_id + + +class RoleAssignmentScheduleInstanceListResult(_serialization.Model): + """Role assignment schedule instance list operation result. + + :ivar value: Role assignment schedule instance list. + :vartype value: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleInstance] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[RoleAssignmentScheduleInstance]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.RoleAssignmentScheduleInstance"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Role assignment schedule instance list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleInstance] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RoleAssignmentScheduleListResult(_serialization.Model): + """Role assignment schedule list operation result. + + :ivar value: Role assignment schedule list. + :vartype value: list[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentSchedule] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[RoleAssignmentSchedule]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.RoleAssignmentSchedule"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Role assignment schedule list. + :paramtype value: list[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentSchedule] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RoleAssignmentScheduleRequest(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Role Assignment schedule request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role assignment schedule request ID. + :vartype id: str + :ivar name: The role assignment schedule request name. + :vartype name: str + :ivar type: The role assignment schedule request type. + :vartype type: str + :ivar scope: The role assignment schedule request scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or ~azure.mgmt.authorization.v2020_10_01.models.PrincipalType + :ivar request_type: The type of the role assignment schedule request. Eg: SelfActivate, + AdminAssign etc. Known values are: "AdminAssign", "AdminRemove", "AdminUpdate", "AdminExtend", + "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", and "SelfRenew". + :vartype request_type: str or ~azure.mgmt.authorization.v2020_10_01.models.RequestType + :ivar status: The status of the role assignment schedule request. Known values are: "Accepted", + "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :vartype status: str or ~azure.mgmt.authorization.v2020_10_01.models.Status + :ivar approval_id: The approvalId of the role assignment schedule request. + :vartype approval_id: str + :ivar target_role_assignment_schedule_id: The resultant role assignment schedule id or the role + assignment schedule id being updated. + :vartype target_role_assignment_schedule_id: str + :ivar target_role_assignment_schedule_instance_id: The role assignment schedule instance id + being updated. + :vartype target_role_assignment_schedule_instance_id: str + :ivar schedule_info: Schedule info of the role assignment schedule. + :vartype schedule_info: + ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequestPropertiesScheduleInfo + :ivar linked_role_eligibility_schedule_id: The linked role eligibility schedule id - to + activate an eligibility. + :vartype linked_role_eligibility_schedule_id: str + :ivar justification: Justification for the role assignment. + :vartype justification: str + :ivar ticket_info: Ticket Info of the role assignment. + :vartype ticket_info: + ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequestPropertiesTicketInfo + :ivar condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: DateTime when role assignment schedule request was created. + :vartype created_on: ~datetime.datetime + :ivar requestor_id: Id of the user who created this request. + :vartype requestor_id: str + :ivar expanded_properties: Additional properties of principal, scope and role definition. + :vartype expanded_properties: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "scope": {"readonly": True}, + "principal_type": {"readonly": True}, + "status": {"readonly": True}, + "approval_id": {"readonly": True}, + "created_on": {"readonly": True}, + "requestor_id": {"readonly": True}, + "expanded_properties": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "request_type": {"key": "properties.requestType", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "approval_id": {"key": "properties.approvalId", "type": "str"}, + "target_role_assignment_schedule_id": {"key": "properties.targetRoleAssignmentScheduleId", "type": "str"}, + "target_role_assignment_schedule_instance_id": { + "key": "properties.targetRoleAssignmentScheduleInstanceId", + "type": "str", + }, + "schedule_info": { + "key": "properties.scheduleInfo", + "type": "RoleAssignmentScheduleRequestPropertiesScheduleInfo", + }, + "linked_role_eligibility_schedule_id": {"key": "properties.linkedRoleEligibilityScheduleId", "type": "str"}, + "justification": {"key": "properties.justification", "type": "str"}, + "ticket_info": {"key": "properties.ticketInfo", "type": "RoleAssignmentScheduleRequestPropertiesTicketInfo"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "requestor_id": {"key": "properties.requestorId", "type": "str"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, + } + + def __init__( + self, + *, + role_definition_id: Optional[str] = None, + principal_id: Optional[str] = None, + request_type: Optional[Union[str, "_models.RequestType"]] = None, + target_role_assignment_schedule_id: Optional[str] = None, + target_role_assignment_schedule_instance_id: Optional[str] = None, + schedule_info: Optional["_models.RoleAssignmentScheduleRequestPropertiesScheduleInfo"] = None, + linked_role_eligibility_schedule_id: Optional[str] = None, + justification: Optional[str] = None, + ticket_info: Optional["_models.RoleAssignmentScheduleRequestPropertiesTicketInfo"] = None, + condition: Optional[str] = None, + condition_version: Optional[str] = None, + **kwargs + ): + """ + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword request_type: The type of the role assignment schedule request. Eg: SelfActivate, + AdminAssign etc. Known values are: "AdminAssign", "AdminRemove", "AdminUpdate", "AdminExtend", + "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", and "SelfRenew". + :paramtype request_type: str or ~azure.mgmt.authorization.v2020_10_01.models.RequestType + :keyword target_role_assignment_schedule_id: The resultant role assignment schedule id or the + role assignment schedule id being updated. + :paramtype target_role_assignment_schedule_id: str + :keyword target_role_assignment_schedule_instance_id: The role assignment schedule instance id + being updated. + :paramtype target_role_assignment_schedule_instance_id: str + :keyword schedule_info: Schedule info of the role assignment schedule. + :paramtype schedule_info: + ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequestPropertiesScheduleInfo + :keyword linked_role_eligibility_schedule_id: The linked role eligibility schedule id - to + activate an eligibility. + :paramtype linked_role_eligibility_schedule_id: str + :keyword justification: Justification for the role assignment. + :paramtype justification: str + :keyword ticket_info: Ticket Info of the role assignment. + :paramtype ticket_info: + ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequestPropertiesTicketInfo + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.scope = None + self.role_definition_id = role_definition_id + self.principal_id = principal_id + self.principal_type = None + self.request_type = request_type + self.status = None + self.approval_id = None + self.target_role_assignment_schedule_id = target_role_assignment_schedule_id + self.target_role_assignment_schedule_instance_id = target_role_assignment_schedule_instance_id + self.schedule_info = schedule_info + self.linked_role_eligibility_schedule_id = linked_role_eligibility_schedule_id + self.justification = justification + self.ticket_info = ticket_info + self.condition = condition + self.condition_version = condition_version + self.created_on = None + self.requestor_id = None + self.expanded_properties = None + + +class RoleAssignmentScheduleRequestFilter(_serialization.Model): + """Role assignment schedule request filter. + + :ivar principal_id: Returns role assignment requests of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role assignment requests of the specific role definition. + :vartype role_definition_id: str + :ivar requestor_id: Returns role assignment requests created by specific principal. + :vartype requestor_id: str + :ivar status: Returns role assignment requests of specific status. + :vartype status: str + """ + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "requestor_id": {"key": "requestorId", "type": "str"}, + "status": {"key": "status", "type": "str"}, + } + + def __init__( + self, + *, + principal_id: Optional[str] = None, + role_definition_id: Optional[str] = None, + requestor_id: Optional[str] = None, + status: Optional[str] = None, + **kwargs + ): + """ + :keyword principal_id: Returns role assignment requests of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role assignment requests of the specific role definition. + :paramtype role_definition_id: str + :keyword requestor_id: Returns role assignment requests created by specific principal. + :paramtype requestor_id: str + :keyword status: Returns role assignment requests of specific status. + :paramtype status: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.role_definition_id = role_definition_id + self.requestor_id = requestor_id + self.status = status + + +class RoleAssignmentScheduleRequestListResult(_serialization.Model): + """Role assignment schedule request list operation result. + + :ivar value: Role assignment schedule request list. + :vartype value: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[RoleAssignmentScheduleRequest]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.RoleAssignmentScheduleRequest"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Role assignment schedule request list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RoleAssignmentScheduleRequestPropertiesScheduleInfo(_serialization.Model): + """Schedule info of the role assignment schedule. + + :ivar start_date_time: Start DateTime of the role assignment schedule. + :vartype start_date_time: ~datetime.datetime + :ivar expiration: Expiration of the role assignment schedule. + :vartype expiration: + ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration + """ + + _attribute_map = { + "start_date_time": {"key": "startDateTime", "type": "iso-8601"}, + "expiration": {"key": "expiration", "type": "RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration"}, + } + + def __init__( + self, + *, + start_date_time: Optional[datetime.datetime] = None, + expiration: Optional["_models.RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration"] = None, + **kwargs + ): + """ + :keyword start_date_time: Start DateTime of the role assignment schedule. + :paramtype start_date_time: ~datetime.datetime + :keyword expiration: Expiration of the role assignment schedule. + :paramtype expiration: + ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration + """ + super().__init__(**kwargs) + self.start_date_time = start_date_time + self.expiration = expiration + + +class RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration(_serialization.Model): + """Expiration of the role assignment schedule. + + :ivar type: Type of the role assignment schedule expiration. Known values are: "AfterDuration", + "AfterDateTime", and "NoExpiration". + :vartype type: str or ~azure.mgmt.authorization.v2020_10_01.models.Type + :ivar end_date_time: End DateTime of the role assignment schedule. + :vartype end_date_time: ~datetime.datetime + :ivar duration: Duration of the role assignment schedule in TimeSpan. + :vartype duration: str + """ + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "end_date_time": {"key": "endDateTime", "type": "iso-8601"}, + "duration": {"key": "duration", "type": "str"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.Type"]] = None, + end_date_time: Optional[datetime.datetime] = None, + duration: Optional[str] = None, + **kwargs + ): + """ + :keyword type: Type of the role assignment schedule expiration. Known values are: + "AfterDuration", "AfterDateTime", and "NoExpiration". + :paramtype type: str or ~azure.mgmt.authorization.v2020_10_01.models.Type + :keyword end_date_time: End DateTime of the role assignment schedule. + :paramtype end_date_time: ~datetime.datetime + :keyword duration: Duration of the role assignment schedule in TimeSpan. + :paramtype duration: str + """ + super().__init__(**kwargs) + self.type = type + self.end_date_time = end_date_time + self.duration = duration + + +class RoleAssignmentScheduleRequestPropertiesTicketInfo(_serialization.Model): + """Ticket Info of the role assignment. + + :ivar ticket_number: Ticket number for the role assignment. + :vartype ticket_number: str + :ivar ticket_system: Ticket system name for the role assignment. + :vartype ticket_system: str + """ + + _attribute_map = { + "ticket_number": {"key": "ticketNumber", "type": "str"}, + "ticket_system": {"key": "ticketSystem", "type": "str"}, + } + + def __init__(self, *, ticket_number: Optional[str] = None, ticket_system: Optional[str] = None, **kwargs): + """ + :keyword ticket_number: Ticket number for the role assignment. + :paramtype ticket_number: str + :keyword ticket_system: Ticket system name for the role assignment. + :paramtype ticket_system: str + """ + super().__init__(**kwargs) + self.ticket_number = ticket_number + self.ticket_system = ticket_system + + +class RoleEligibilitySchedule(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Role eligibility schedule. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role eligibility schedule Id. + :vartype id: str + :ivar name: The role eligibility schedule name. + :vartype name: str + :ivar type: The role eligibility schedule type. + :vartype type: str + :ivar scope: The role eligibility schedule scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or ~azure.mgmt.authorization.v2020_10_01.models.PrincipalType + :ivar role_eligibility_schedule_request_id: The id of roleEligibilityScheduleRequest used to + create this roleAssignmentSchedule. + :vartype role_eligibility_schedule_request_id: str + :ivar member_type: Membership type of the role eligibility schedule. Known values are: + "Inherited", "Direct", and "Group". + :vartype member_type: str or ~azure.mgmt.authorization.v2020_10_01.models.MemberType + :ivar status: The status of the role eligibility schedule. Known values are: "Accepted", + "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :vartype status: str or ~azure.mgmt.authorization.v2020_10_01.models.Status + :ivar start_date_time: Start DateTime when role eligibility schedule. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: End DateTime when role eligibility schedule. + :vartype end_date_time: ~datetime.datetime + :ivar condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: DateTime when role eligibility schedule was created. + :vartype created_on: ~datetime.datetime + :ivar updated_on: DateTime when role eligibility schedule was modified. + :vartype updated_on: ~datetime.datetime + :ivar expanded_properties: Additional properties of principal, scope and role definition. + :vartype expanded_properties: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "role_eligibility_schedule_request_id": {"key": "properties.roleEligibilityScheduleRequestId", "type": "str"}, + "member_type": {"key": "properties.memberType", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "updated_on": {"key": "properties.updatedOn", "type": "iso-8601"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, + } + + def __init__( + self, + *, + scope: Optional[str] = None, + role_definition_id: Optional[str] = None, + principal_id: Optional[str] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, + role_eligibility_schedule_request_id: Optional[str] = None, + member_type: Optional[Union[str, "_models.MemberType"]] = None, + status: Optional[Union[str, "_models.Status"]] = None, + start_date_time: Optional[datetime.datetime] = None, + end_date_time: Optional[datetime.datetime] = None, + condition: Optional[str] = None, + condition_version: Optional[str] = None, + created_on: Optional[datetime.datetime] = None, + updated_on: Optional[datetime.datetime] = None, + expanded_properties: Optional["_models.ExpandedProperties"] = None, + **kwargs + ): + """ + :keyword scope: The role eligibility schedule scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or ~azure.mgmt.authorization.v2020_10_01.models.PrincipalType + :keyword role_eligibility_schedule_request_id: The id of roleEligibilityScheduleRequest used to + create this roleAssignmentSchedule. + :paramtype role_eligibility_schedule_request_id: str + :keyword member_type: Membership type of the role eligibility schedule. Known values are: + "Inherited", "Direct", and "Group". + :paramtype member_type: str or ~azure.mgmt.authorization.v2020_10_01.models.MemberType + :keyword status: The status of the role eligibility schedule. Known values are: "Accepted", + "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :paramtype status: str or ~azure.mgmt.authorization.v2020_10_01.models.Status + :keyword start_date_time: Start DateTime when role eligibility schedule. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: End DateTime when role eligibility schedule. + :paramtype end_date_time: ~datetime.datetime + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword created_on: DateTime when role eligibility schedule was created. + :paramtype created_on: ~datetime.datetime + :keyword updated_on: DateTime when role eligibility schedule was modified. + :paramtype updated_on: ~datetime.datetime + :keyword expanded_properties: Additional properties of principal, scope and role definition. + :paramtype expanded_properties: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedProperties + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.scope = scope + self.role_definition_id = role_definition_id + self.principal_id = principal_id + self.principal_type = principal_type + self.role_eligibility_schedule_request_id = role_eligibility_schedule_request_id + self.member_type = member_type + self.status = status + self.start_date_time = start_date_time + self.end_date_time = end_date_time + self.condition = condition + self.condition_version = condition_version + self.created_on = created_on + self.updated_on = updated_on + self.expanded_properties = expanded_properties + + +class RoleEligibilityScheduleFilter(_serialization.Model): + """Role eligibility schedule filter. + + :ivar principal_id: Returns role eligibility schedule of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role eligibility schedule of the specific role definition. + :vartype role_definition_id: str + :ivar status: Returns role eligibility schedule of the specific status. + :vartype status: str + """ + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "status": {"key": "status", "type": "str"}, + } + + def __init__( + self, + *, + principal_id: Optional[str] = None, + role_definition_id: Optional[str] = None, + status: Optional[str] = None, + **kwargs + ): + """ + :keyword principal_id: Returns role eligibility schedule of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role eligibility schedule of the specific role definition. + :paramtype role_definition_id: str + :keyword status: Returns role eligibility schedule of the specific status. + :paramtype status: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.role_definition_id = role_definition_id + self.status = status + + +class RoleEligibilityScheduleInstance(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Information about current or upcoming role eligibility schedule instance. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role eligibility schedule instance ID. + :vartype id: str + :ivar name: The role eligibility schedule instance name. + :vartype name: str + :ivar type: The role eligibility schedule instance type. + :vartype type: str + :ivar scope: The role eligibility schedule scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or ~azure.mgmt.authorization.v2020_10_01.models.PrincipalType + :ivar role_eligibility_schedule_id: Id of the master role eligibility schedule. + :vartype role_eligibility_schedule_id: str + :ivar status: The status of the role eligibility schedule instance. Known values are: + "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :vartype status: str or ~azure.mgmt.authorization.v2020_10_01.models.Status + :ivar start_date_time: The startDateTime of the role eligibility schedule instance. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: The endDateTime of the role eligibility schedule instance. + :vartype end_date_time: ~datetime.datetime + :ivar member_type: Membership type of the role eligibility schedule. Known values are: + "Inherited", "Direct", and "Group". + :vartype member_type: str or ~azure.mgmt.authorization.v2020_10_01.models.MemberType + :ivar condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: DateTime when role eligibility schedule was created. + :vartype created_on: ~datetime.datetime + :ivar expanded_properties: Additional properties of principal, scope and role definition. + :vartype expanded_properties: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "role_eligibility_schedule_id": {"key": "properties.roleEligibilityScheduleId", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, + "member_type": {"key": "properties.memberType", "type": "str"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, + } + + def __init__( + self, + *, + scope: Optional[str] = None, + role_definition_id: Optional[str] = None, + principal_id: Optional[str] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, + role_eligibility_schedule_id: Optional[str] = None, + status: Optional[Union[str, "_models.Status"]] = None, + start_date_time: Optional[datetime.datetime] = None, + end_date_time: Optional[datetime.datetime] = None, + member_type: Optional[Union[str, "_models.MemberType"]] = None, + condition: Optional[str] = None, + condition_version: Optional[str] = None, + created_on: Optional[datetime.datetime] = None, + expanded_properties: Optional["_models.ExpandedProperties"] = None, + **kwargs + ): + """ + :keyword scope: The role eligibility schedule scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or ~azure.mgmt.authorization.v2020_10_01.models.PrincipalType + :keyword role_eligibility_schedule_id: Id of the master role eligibility schedule. + :paramtype role_eligibility_schedule_id: str + :keyword status: The status of the role eligibility schedule instance. Known values are: + "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :paramtype status: str or ~azure.mgmt.authorization.v2020_10_01.models.Status + :keyword start_date_time: The startDateTime of the role eligibility schedule instance. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: The endDateTime of the role eligibility schedule instance. + :paramtype end_date_time: ~datetime.datetime + :keyword member_type: Membership type of the role eligibility schedule. Known values are: + "Inherited", "Direct", and "Group". + :paramtype member_type: str or ~azure.mgmt.authorization.v2020_10_01.models.MemberType + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword created_on: DateTime when role eligibility schedule was created. + :paramtype created_on: ~datetime.datetime + :keyword expanded_properties: Additional properties of principal, scope and role definition. + :paramtype expanded_properties: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedProperties + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.scope = scope + self.role_definition_id = role_definition_id + self.principal_id = principal_id + self.principal_type = principal_type + self.role_eligibility_schedule_id = role_eligibility_schedule_id + self.status = status + self.start_date_time = start_date_time + self.end_date_time = end_date_time + self.member_type = member_type + self.condition = condition + self.condition_version = condition_version + self.created_on = created_on + self.expanded_properties = expanded_properties + + +class RoleEligibilityScheduleInstanceFilter(_serialization.Model): + """Role eligibility schedule instance filter. + + :ivar principal_id: Returns role eligibility schedule instances of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role eligibility schedule instances of the specific role + definition. + :vartype role_definition_id: str + :ivar status: Returns role eligibility schedule instances of the specific status. + :vartype status: str + :ivar role_eligibility_schedule_id: Returns role eligibility schedule instances belonging to a + specific role eligibility schedule. + :vartype role_eligibility_schedule_id: str + """ + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "role_eligibility_schedule_id": {"key": "roleEligibilityScheduleId", "type": "str"}, + } + + def __init__( + self, + *, + principal_id: Optional[str] = None, + role_definition_id: Optional[str] = None, + status: Optional[str] = None, + role_eligibility_schedule_id: Optional[str] = None, + **kwargs + ): + """ + :keyword principal_id: Returns role eligibility schedule instances of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role eligibility schedule instances of the specific role + definition. + :paramtype role_definition_id: str + :keyword status: Returns role eligibility schedule instances of the specific status. + :paramtype status: str + :keyword role_eligibility_schedule_id: Returns role eligibility schedule instances belonging to + a specific role eligibility schedule. + :paramtype role_eligibility_schedule_id: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.role_definition_id = role_definition_id + self.status = status + self.role_eligibility_schedule_id = role_eligibility_schedule_id + + +class RoleEligibilityScheduleInstanceListResult(_serialization.Model): + """Role eligibility schedule instance list operation result. + + :ivar value: Role eligibility schedule instance list. + :vartype value: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleInstance] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[RoleEligibilityScheduleInstance]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.RoleEligibilityScheduleInstance"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Role eligibility schedule instance list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleInstance] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RoleEligibilityScheduleListResult(_serialization.Model): + """role eligibility schedule list operation result. + + :ivar value: role eligibility schedule list. + :vartype value: list[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilitySchedule] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[RoleEligibilitySchedule]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.RoleEligibilitySchedule"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: role eligibility schedule list. + :paramtype value: list[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilitySchedule] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RoleEligibilityScheduleRequest(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Role Eligibility schedule request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role eligibility schedule request ID. + :vartype id: str + :ivar name: The role eligibility schedule request name. + :vartype name: str + :ivar type: The role eligibility schedule request type. + :vartype type: str + :ivar scope: The role eligibility schedule request scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or ~azure.mgmt.authorization.v2020_10_01.models.PrincipalType + :ivar request_type: The type of the role assignment schedule request. Eg: SelfActivate, + AdminAssign etc. Known values are: "AdminAssign", "AdminRemove", "AdminUpdate", "AdminExtend", + "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", and "SelfRenew". + :vartype request_type: str or ~azure.mgmt.authorization.v2020_10_01.models.RequestType + :ivar status: The status of the role eligibility schedule request. Known values are: + "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :vartype status: str or ~azure.mgmt.authorization.v2020_10_01.models.Status + :ivar approval_id: The approvalId of the role eligibility schedule request. + :vartype approval_id: str + :ivar schedule_info: Schedule info of the role eligibility schedule. + :vartype schedule_info: + ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequestPropertiesScheduleInfo + :ivar target_role_eligibility_schedule_id: The resultant role eligibility schedule id or the + role eligibility schedule id being updated. + :vartype target_role_eligibility_schedule_id: str + :ivar target_role_eligibility_schedule_instance_id: The role eligibility schedule instance id + being updated. + :vartype target_role_eligibility_schedule_instance_id: str + :ivar justification: Justification for the role eligibility. + :vartype justification: str + :ivar ticket_info: Ticket Info of the role eligibility. + :vartype ticket_info: + ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequestPropertiesTicketInfo + :ivar condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: DateTime when role eligibility schedule request was created. + :vartype created_on: ~datetime.datetime + :ivar requestor_id: Id of the user who created this request. + :vartype requestor_id: str + :ivar expanded_properties: Additional properties of principal, scope and role definition. + :vartype expanded_properties: ~azure.mgmt.authorization.v2020_10_01.models.ExpandedProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "scope": {"readonly": True}, + "principal_type": {"readonly": True}, + "status": {"readonly": True}, + "approval_id": {"readonly": True}, + "created_on": {"readonly": True}, + "requestor_id": {"readonly": True}, + "expanded_properties": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "request_type": {"key": "properties.requestType", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "approval_id": {"key": "properties.approvalId", "type": "str"}, + "schedule_info": { + "key": "properties.scheduleInfo", + "type": "RoleEligibilityScheduleRequestPropertiesScheduleInfo", + }, + "target_role_eligibility_schedule_id": {"key": "properties.targetRoleEligibilityScheduleId", "type": "str"}, + "target_role_eligibility_schedule_instance_id": { + "key": "properties.targetRoleEligibilityScheduleInstanceId", + "type": "str", + }, + "justification": {"key": "properties.justification", "type": "str"}, + "ticket_info": {"key": "properties.ticketInfo", "type": "RoleEligibilityScheduleRequestPropertiesTicketInfo"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "requestor_id": {"key": "properties.requestorId", "type": "str"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, + } + + def __init__( + self, + *, + role_definition_id: Optional[str] = None, + principal_id: Optional[str] = None, + request_type: Optional[Union[str, "_models.RequestType"]] = None, + schedule_info: Optional["_models.RoleEligibilityScheduleRequestPropertiesScheduleInfo"] = None, + target_role_eligibility_schedule_id: Optional[str] = None, + target_role_eligibility_schedule_instance_id: Optional[str] = None, + justification: Optional[str] = None, + ticket_info: Optional["_models.RoleEligibilityScheduleRequestPropertiesTicketInfo"] = None, + condition: Optional[str] = None, + condition_version: Optional[str] = None, + **kwargs + ): + """ + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword request_type: The type of the role assignment schedule request. Eg: SelfActivate, + AdminAssign etc. Known values are: "AdminAssign", "AdminRemove", "AdminUpdate", "AdminExtend", + "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", and "SelfRenew". + :paramtype request_type: str or ~azure.mgmt.authorization.v2020_10_01.models.RequestType + :keyword schedule_info: Schedule info of the role eligibility schedule. + :paramtype schedule_info: + ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequestPropertiesScheduleInfo + :keyword target_role_eligibility_schedule_id: The resultant role eligibility schedule id or the + role eligibility schedule id being updated. + :paramtype target_role_eligibility_schedule_id: str + :keyword target_role_eligibility_schedule_instance_id: The role eligibility schedule instance + id being updated. + :paramtype target_role_eligibility_schedule_instance_id: str + :keyword justification: Justification for the role eligibility. + :paramtype justification: str + :keyword ticket_info: Ticket Info of the role eligibility. + :paramtype ticket_info: + ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequestPropertiesTicketInfo + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.scope = None + self.role_definition_id = role_definition_id + self.principal_id = principal_id + self.principal_type = None + self.request_type = request_type + self.status = None + self.approval_id = None + self.schedule_info = schedule_info + self.target_role_eligibility_schedule_id = target_role_eligibility_schedule_id + self.target_role_eligibility_schedule_instance_id = target_role_eligibility_schedule_instance_id + self.justification = justification + self.ticket_info = ticket_info + self.condition = condition + self.condition_version = condition_version + self.created_on = None + self.requestor_id = None + self.expanded_properties = None + + +class RoleEligibilityScheduleRequestFilter(_serialization.Model): + """Role eligibility schedule request filter. + + :ivar principal_id: Returns role eligibility requests of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role eligibility requests of the specific role definition. + :vartype role_definition_id: str + :ivar requestor_id: Returns role eligibility requests created by specific principal. + :vartype requestor_id: str + :ivar status: Returns role eligibility requests of specific status. + :vartype status: str + """ + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "requestor_id": {"key": "requestorId", "type": "str"}, + "status": {"key": "status", "type": "str"}, + } + + def __init__( + self, + *, + principal_id: Optional[str] = None, + role_definition_id: Optional[str] = None, + requestor_id: Optional[str] = None, + status: Optional[str] = None, + **kwargs + ): + """ + :keyword principal_id: Returns role eligibility requests of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role eligibility requests of the specific role definition. + :paramtype role_definition_id: str + :keyword requestor_id: Returns role eligibility requests created by specific principal. + :paramtype requestor_id: str + :keyword status: Returns role eligibility requests of specific status. + :paramtype status: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.role_definition_id = role_definition_id + self.requestor_id = requestor_id + self.status = status + + +class RoleEligibilityScheduleRequestListResult(_serialization.Model): + """Role eligibility schedule request list operation result. + + :ivar value: Role eligibility schedule request list. + :vartype value: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[RoleEligibilityScheduleRequest]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.RoleEligibilityScheduleRequest"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Role eligibility schedule request list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RoleEligibilityScheduleRequestPropertiesScheduleInfo(_serialization.Model): + """Schedule info of the role eligibility schedule. + + :ivar start_date_time: Start DateTime of the role eligibility schedule. + :vartype start_date_time: ~datetime.datetime + :ivar expiration: Expiration of the role eligibility schedule. + :vartype expiration: + ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration + """ + + _attribute_map = { + "start_date_time": {"key": "startDateTime", "type": "iso-8601"}, + "expiration": {"key": "expiration", "type": "RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration"}, + } + + def __init__( + self, + *, + start_date_time: Optional[datetime.datetime] = None, + expiration: Optional["_models.RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration"] = None, + **kwargs + ): + """ + :keyword start_date_time: Start DateTime of the role eligibility schedule. + :paramtype start_date_time: ~datetime.datetime + :keyword expiration: Expiration of the role eligibility schedule. + :paramtype expiration: + ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration + """ + super().__init__(**kwargs) + self.start_date_time = start_date_time + self.expiration = expiration + + +class RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration(_serialization.Model): + """Expiration of the role eligibility schedule. + + :ivar type: Type of the role eligibility schedule expiration. Known values are: + "AfterDuration", "AfterDateTime", and "NoExpiration". + :vartype type: str or ~azure.mgmt.authorization.v2020_10_01.models.Type + :ivar end_date_time: End DateTime of the role eligibility schedule. + :vartype end_date_time: ~datetime.datetime + :ivar duration: Duration of the role eligibility schedule in TimeSpan. + :vartype duration: str + """ + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "end_date_time": {"key": "endDateTime", "type": "iso-8601"}, + "duration": {"key": "duration", "type": "str"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.Type"]] = None, + end_date_time: Optional[datetime.datetime] = None, + duration: Optional[str] = None, + **kwargs + ): + """ + :keyword type: Type of the role eligibility schedule expiration. Known values are: + "AfterDuration", "AfterDateTime", and "NoExpiration". + :paramtype type: str or ~azure.mgmt.authorization.v2020_10_01.models.Type + :keyword end_date_time: End DateTime of the role eligibility schedule. + :paramtype end_date_time: ~datetime.datetime + :keyword duration: Duration of the role eligibility schedule in TimeSpan. + :paramtype duration: str + """ + super().__init__(**kwargs) + self.type = type + self.end_date_time = end_date_time + self.duration = duration + + +class RoleEligibilityScheduleRequestPropertiesTicketInfo(_serialization.Model): + """Ticket Info of the role eligibility. + + :ivar ticket_number: Ticket number for the role eligibility. + :vartype ticket_number: str + :ivar ticket_system: Ticket system name for the role eligibility. + :vartype ticket_system: str + """ + + _attribute_map = { + "ticket_number": {"key": "ticketNumber", "type": "str"}, + "ticket_system": {"key": "ticketSystem", "type": "str"}, + } + + def __init__(self, *, ticket_number: Optional[str] = None, ticket_system: Optional[str] = None, **kwargs): + """ + :keyword ticket_number: Ticket number for the role eligibility. + :paramtype ticket_number: str + :keyword ticket_system: Ticket system name for the role eligibility. + :paramtype ticket_system: str + """ + super().__init__(**kwargs) + self.ticket_number = ticket_number + self.ticket_system = ticket_system + + +class RoleManagementPolicy(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Role management policy. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role management policy Id. + :vartype id: str + :ivar name: The role management policy name. + :vartype name: str + :ivar type: The role management policy type. + :vartype type: str + :ivar scope: The role management policy scope. + :vartype scope: str + :ivar display_name: The role management policy display name. + :vartype display_name: str + :ivar description: The role management policy description. + :vartype description: str + :ivar is_organization_default: The role management policy is default policy. + :vartype is_organization_default: bool + :ivar last_modified_by: The name of the entity last modified it. + :vartype last_modified_by: ~azure.mgmt.authorization.v2020_10_01.models.Principal + :ivar last_modified_date_time: The last modified date time. + :vartype last_modified_date_time: ~datetime.datetime + :ivar rules: The rule applied to the policy. + :vartype rules: list[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRule] + :ivar effective_rules: The readonly computed rule applied to the policy. + :vartype effective_rules: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRule] + :ivar policy_properties: Additional properties of scope. + :vartype policy_properties: ~azure.mgmt.authorization.v2020_10_01.models.PolicyProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "last_modified_by": {"readonly": True}, + "last_modified_date_time": {"readonly": True}, + "effective_rules": {"readonly": True}, + "policy_properties": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "is_organization_default": {"key": "properties.isOrganizationDefault", "type": "bool"}, + "last_modified_by": {"key": "properties.lastModifiedBy", "type": "Principal"}, + "last_modified_date_time": {"key": "properties.lastModifiedDateTime", "type": "iso-8601"}, + "rules": {"key": "properties.rules", "type": "[RoleManagementPolicyRule]"}, + "effective_rules": {"key": "properties.effectiveRules", "type": "[RoleManagementPolicyRule]"}, + "policy_properties": {"key": "properties.policyProperties", "type": "PolicyProperties"}, + } + + def __init__( + self, + *, + scope: Optional[str] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + is_organization_default: Optional[bool] = None, + rules: Optional[List["_models.RoleManagementPolicyRule"]] = None, + **kwargs + ): + """ + :keyword scope: The role management policy scope. + :paramtype scope: str + :keyword display_name: The role management policy display name. + :paramtype display_name: str + :keyword description: The role management policy description. + :paramtype description: str + :keyword is_organization_default: The role management policy is default policy. + :paramtype is_organization_default: bool + :keyword rules: The rule applied to the policy. + :paramtype rules: list[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRule] + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.scope = scope + self.display_name = display_name + self.description = description + self.is_organization_default = is_organization_default + self.last_modified_by = None + self.last_modified_date_time = None + self.rules = rules + self.effective_rules = None + self.policy_properties = None + + +class RoleManagementPolicyRule(_serialization.Model): + """The role management policy rule. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + RoleManagementPolicyApprovalRule, RoleManagementPolicyAuthenticationContextRule, + RoleManagementPolicyEnablementRule, RoleManagementPolicyExpirationRule, + RoleManagementPolicyNotificationRule + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + } + + _subtype_map = { + "rule_type": { + "RoleManagementPolicyApprovalRule": "RoleManagementPolicyApprovalRule", + "RoleManagementPolicyAuthenticationContextRule": "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule": "RoleManagementPolicyEnablementRule", + "RoleManagementPolicyExpirationRule": "RoleManagementPolicyExpirationRule", + "RoleManagementPolicyNotificationRule": "RoleManagementPolicyNotificationRule", + } + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + """ + super().__init__(**kwargs) + self.id = id + self.rule_type = None # type: Optional[str] + self.target = target + + +class RoleManagementPolicyApprovalRule(RoleManagementPolicyRule): + """The role management policy approval rule. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + :ivar setting: The approval setting. + :vartype setting: ~azure.mgmt.authorization.v2020_10_01.models.ApprovalSettings + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "setting": {"key": "setting", "type": "ApprovalSettings"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + setting: Optional["_models.ApprovalSettings"] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + :keyword setting: The approval setting. + :paramtype setting: ~azure.mgmt.authorization.v2020_10_01.models.ApprovalSettings + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyApprovalRule" # type: str + self.setting = setting + + +class RoleManagementPolicyAssignment(_serialization.Model): + """Role management policy. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role management policy Id. + :vartype id: str + :ivar name: The role management policy name. + :vartype name: str + :ivar type: The role management policy type. + :vartype type: str + :ivar scope: The role management policy scope. + :vartype scope: str + :ivar role_definition_id: The role definition of management policy assignment. + :vartype role_definition_id: str + :ivar policy_id: The policy id role management policy assignment. + :vartype policy_id: str + :ivar effective_rules: The readonly computed rule applied to the policy. + :vartype effective_rules: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRule] + :ivar policy_assignment_properties: Additional properties of scope, role definition and policy. + :vartype policy_assignment_properties: + ~azure.mgmt.authorization.v2020_10_01.models.PolicyAssignmentProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "effective_rules": {"readonly": True}, + "policy_assignment_properties": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "policy_id": {"key": "properties.policyId", "type": "str"}, + "effective_rules": {"key": "properties.effectiveRules", "type": "[RoleManagementPolicyRule]"}, + "policy_assignment_properties": { + "key": "properties.policyAssignmentProperties", + "type": "PolicyAssignmentProperties", + }, + } + + def __init__( + self, + *, + scope: Optional[str] = None, + role_definition_id: Optional[str] = None, + policy_id: Optional[str] = None, + **kwargs + ): + """ + :keyword scope: The role management policy scope. + :paramtype scope: str + :keyword role_definition_id: The role definition of management policy assignment. + :paramtype role_definition_id: str + :keyword policy_id: The policy id role management policy assignment. + :paramtype policy_id: str + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.scope = scope + self.role_definition_id = role_definition_id + self.policy_id = policy_id + self.effective_rules = None + self.policy_assignment_properties = None + + +class RoleManagementPolicyAssignmentListResult(_serialization.Model): + """Role management policy assignment list operation result. + + :ivar value: Role management policy assignment list. + :vartype value: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[RoleManagementPolicyAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.RoleManagementPolicyAssignment"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Role management policy assignment list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RoleManagementPolicyAuthenticationContextRule(RoleManagementPolicyRule): + """The role management policy authentication context rule. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + :ivar is_enabled: The value indicating if rule is enabled. + :vartype is_enabled: bool + :ivar claim_value: The claim value. + :vartype claim_value: str + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "is_enabled": {"key": "isEnabled", "type": "bool"}, + "claim_value": {"key": "claimValue", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + is_enabled: Optional[bool] = None, + claim_value: Optional[str] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + :keyword is_enabled: The value indicating if rule is enabled. + :paramtype is_enabled: bool + :keyword claim_value: The claim value. + :paramtype claim_value: str + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyAuthenticationContextRule" # type: str + self.is_enabled = is_enabled + self.claim_value = claim_value + + +class RoleManagementPolicyEnablementRule(RoleManagementPolicyRule): + """The role management policy enablement rule. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + :ivar enabled_rules: The list of enabled rules. + :vartype enabled_rules: list[str or + ~azure.mgmt.authorization.v2020_10_01.models.EnablementRules] + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "enabled_rules": {"key": "enabledRules", "type": "[str]"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + enabled_rules: Optional[List[Union[str, "_models.EnablementRules"]]] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + :keyword enabled_rules: The list of enabled rules. + :paramtype enabled_rules: list[str or + ~azure.mgmt.authorization.v2020_10_01.models.EnablementRules] + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyEnablementRule" # type: str + self.enabled_rules = enabled_rules + + +class RoleManagementPolicyExpirationRule(RoleManagementPolicyRule): + """The role management policy expiration rule. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + :ivar is_expiration_required: The value indicating whether expiration is required. + :vartype is_expiration_required: bool + :ivar maximum_duration: The maximum duration of expiration in timespan. + :vartype maximum_duration: str + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "is_expiration_required": {"key": "isExpirationRequired", "type": "bool"}, + "maximum_duration": {"key": "maximumDuration", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + is_expiration_required: Optional[bool] = None, + maximum_duration: Optional[str] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + :keyword is_expiration_required: The value indicating whether expiration is required. + :paramtype is_expiration_required: bool + :keyword maximum_duration: The maximum duration of expiration in timespan. + :paramtype maximum_duration: str + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyExpirationRule" # type: str + self.is_expiration_required = is_expiration_required + self.maximum_duration = maximum_duration + + +class RoleManagementPolicyListResult(_serialization.Model): + """Role management policy list operation result. + + :ivar value: Role management policy list. + :vartype value: list[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[RoleManagementPolicy]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.RoleManagementPolicy"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: Role management policy list. + :paramtype value: list[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RoleManagementPolicyNotificationRule(RoleManagementPolicyRule): + """The role management policy notification rule. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + :ivar notification_type: The type of notification. "Email" + :vartype notification_type: str or + ~azure.mgmt.authorization.v2020_10_01.models.NotificationDeliveryMechanism + :ivar notification_level: The notification level. Known values are: "None", "Critical", and + "All". + :vartype notification_level: str or + ~azure.mgmt.authorization.v2020_10_01.models.NotificationLevel + :ivar recipient_type: The recipient type. Known values are: "Requestor", "Approver", and + "Admin". + :vartype recipient_type: str or ~azure.mgmt.authorization.v2020_10_01.models.RecipientType + :ivar notification_recipients: The list of notification recipients. + :vartype notification_recipients: list[str] + :ivar is_default_recipients_enabled: Determines if the notification will be sent to the + recipient type specified in the policy rule. + :vartype is_default_recipients_enabled: bool + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "notification_type": {"key": "notificationType", "type": "str"}, + "notification_level": {"key": "notificationLevel", "type": "str"}, + "recipient_type": {"key": "recipientType", "type": "str"}, + "notification_recipients": {"key": "notificationRecipients", "type": "[str]"}, + "is_default_recipients_enabled": {"key": "isDefaultRecipientsEnabled", "type": "bool"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + notification_type: Optional[Union[str, "_models.NotificationDeliveryMechanism"]] = None, + notification_level: Optional[Union[str, "_models.NotificationLevel"]] = None, + recipient_type: Optional[Union[str, "_models.RecipientType"]] = None, + notification_recipients: Optional[List[str]] = None, + is_default_recipients_enabled: Optional[bool] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyRuleTarget + :keyword notification_type: The type of notification. "Email" + :paramtype notification_type: str or + ~azure.mgmt.authorization.v2020_10_01.models.NotificationDeliveryMechanism + :keyword notification_level: The notification level. Known values are: "None", "Critical", and + "All". + :paramtype notification_level: str or + ~azure.mgmt.authorization.v2020_10_01.models.NotificationLevel + :keyword recipient_type: The recipient type. Known values are: "Requestor", "Approver", and + "Admin". + :paramtype recipient_type: str or ~azure.mgmt.authorization.v2020_10_01.models.RecipientType + :keyword notification_recipients: The list of notification recipients. + :paramtype notification_recipients: list[str] + :keyword is_default_recipients_enabled: Determines if the notification will be sent to the + recipient type specified in the policy rule. + :paramtype is_default_recipients_enabled: bool + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyNotificationRule" # type: str + self.notification_type = notification_type + self.notification_level = notification_level + self.recipient_type = recipient_type + self.notification_recipients = notification_recipients + self.is_default_recipients_enabled = is_default_recipients_enabled + + +class RoleManagementPolicyRuleTarget(_serialization.Model): + """The role management policy rule target. + + :ivar caller: The caller of the setting. + :vartype caller: str + :ivar operations: The type of operation. + :vartype operations: list[str] + :ivar level: The assignment level to which rule is applied. + :vartype level: str + :ivar target_objects: The list of target objects. + :vartype target_objects: list[str] + :ivar inheritable_settings: The list of inheritable settings. + :vartype inheritable_settings: list[str] + :ivar enforced_settings: The list of enforced settings. + :vartype enforced_settings: list[str] + """ + + _attribute_map = { + "caller": {"key": "caller", "type": "str"}, + "operations": {"key": "operations", "type": "[str]"}, + "level": {"key": "level", "type": "str"}, + "target_objects": {"key": "targetObjects", "type": "[str]"}, + "inheritable_settings": {"key": "inheritableSettings", "type": "[str]"}, + "enforced_settings": {"key": "enforcedSettings", "type": "[str]"}, + } + + def __init__( + self, + *, + caller: Optional[str] = None, + operations: Optional[List[str]] = None, + level: Optional[str] = None, + target_objects: Optional[List[str]] = None, + inheritable_settings: Optional[List[str]] = None, + enforced_settings: Optional[List[str]] = None, + **kwargs + ): + """ + :keyword caller: The caller of the setting. + :paramtype caller: str + :keyword operations: The type of operation. + :paramtype operations: list[str] + :keyword level: The assignment level to which rule is applied. + :paramtype level: str + :keyword target_objects: The list of target objects. + :paramtype target_objects: list[str] + :keyword inheritable_settings: The list of inheritable settings. + :paramtype inheritable_settings: list[str] + :keyword enforced_settings: The list of enforced settings. + :paramtype enforced_settings: list[str] + """ + super().__init__(**kwargs) + self.caller = caller + self.operations = operations + self.level = level + self.target_objects = target_objects + self.inheritable_settings = inheritable_settings + self.enforced_settings = enforced_settings + + +class UserSet(_serialization.Model): + """The detail of a user. + + :ivar user_type: The type of user. Known values are: "User" and "Group". + :vartype user_type: str or ~azure.mgmt.authorization.v2020_10_01.models.UserType + :ivar is_backup: The value indicating whether the user is a backup fallback approver. + :vartype is_backup: bool + :ivar id: The object id of the user. + :vartype id: str + :ivar description: The description of the user. + :vartype description: str + """ + + _attribute_map = { + "user_type": {"key": "userType", "type": "str"}, + "is_backup": {"key": "isBackup", "type": "bool"}, + "id": {"key": "id", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__( + self, + *, + user_type: Optional[Union[str, "_models.UserType"]] = None, + is_backup: Optional[bool] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + description: Optional[str] = None, + **kwargs + ): + """ + :keyword user_type: The type of user. Known values are: "User" and "Group". + :paramtype user_type: str or ~azure.mgmt.authorization.v2020_10_01.models.UserType + :keyword is_backup: The value indicating whether the user is a backup fallback approver. + :paramtype is_backup: bool + :keyword id: The object id of the user. + :paramtype id: str + :keyword description: The description of the user. + :paramtype description: str + """ + super().__init__(**kwargs) + self.user_type = user_type + self.is_backup = is_backup + self.id = id + self.description = description diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/__init__.py new file mode 100644 index 00000000000..53e733602ba --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/__init__.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._eligible_child_resources_operations import EligibleChildResourcesOperations +from ._role_assignment_schedules_operations import RoleAssignmentSchedulesOperations +from ._role_assignment_schedule_instances_operations import RoleAssignmentScheduleInstancesOperations +from ._role_assignment_schedule_requests_operations import RoleAssignmentScheduleRequestsOperations +from ._role_eligibility_schedules_operations import RoleEligibilitySchedulesOperations +from ._role_eligibility_schedule_instances_operations import RoleEligibilityScheduleInstancesOperations +from ._role_eligibility_schedule_requests_operations import RoleEligibilityScheduleRequestsOperations +from ._role_management_policies_operations import RoleManagementPoliciesOperations +from ._role_management_policy_assignments_operations import RoleManagementPolicyAssignmentsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "EligibleChildResourcesOperations", + "RoleAssignmentSchedulesOperations", + "RoleAssignmentScheduleInstancesOperations", + "RoleAssignmentScheduleRequestsOperations", + "RoleEligibilitySchedulesOperations", + "RoleEligibilityScheduleInstancesOperations", + "RoleEligibilityScheduleRequestsOperations", + "RoleManagementPoliciesOperations", + "RoleManagementPolicyAssignmentsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_eligible_child_resources_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_eligible_child_resources_operations.py new file mode 100644 index 00000000000..babb8b81629 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_eligible_child_resources_operations.py @@ -0,0 +1,164 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/eligibleChildResources") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class EligibleChildResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.AuthorizationManagementClient`'s + :attr:`eligible_child_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.EligibleChildResource"]: + """Get the child resources of a resource on which user has eligible access. + + :param scope: The scope of the role management policy. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=resourceType+eq+'Subscription' + to filter on only resource of type = 'Subscription'. Use + $filter=resourceType+eq+'subscription'+or+resourceType+eq+'resourcegroup' to filter on resource + of type = 'Subscription' or 'ResourceGroup'. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either EligibleChildResource or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01.models.EligibleChildResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.EligibleChildResourcesListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_get_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("EligibleChildResourcesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/eligibleChildResources"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedule_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedule_instances_operations.py new file mode 100644 index 00000000000..ba447575db0 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedule_instances_operations.py @@ -0,0 +1,258 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_assignment_schedule_instance_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances/{roleAssignmentScheduleInstanceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentScheduleInstanceName": _SERIALIZER.url( + "role_assignment_schedule_instance_name", role_assignment_schedule_instance_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentScheduleInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.AuthorizationManagementClient`'s + :attr:`role_assignment_schedule_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignmentScheduleInstance"]: + """Gets role assignment schedule instances of a role assignment schedule. + + :param scope: The scope of the role assignment schedule. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role + assignment schedules at, above or below the scope for the specified principal. Use + $filter=assignedTo('{userId}') to return all role assignment schedule instances for the user. + Use $filter=asTarget() to return all role assignment schedule instances created for the current + user. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignmentScheduleInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentScheduleInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances"} # type: ignore + + @distributed_trace + def get( + self, scope: str, role_assignment_schedule_instance_name: str, **kwargs: Any + ) -> _models.RoleAssignmentScheduleInstance: + """Gets the specified role assignment schedule instance. + + :param scope: The scope of the role assignments schedules. Required. + :type scope: str + :param role_assignment_schedule_instance_name: The name (hash of schedule name + time) of the + role assignment schedule to get. Required. + :type role_assignment_schedule_instance_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleInstance] + + request = build_get_request( + scope=scope, + role_assignment_schedule_instance_name=role_assignment_schedule_instance_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignmentScheduleInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances/{roleAssignmentScheduleInstanceName}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedule_requests_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedule_requests_operations.py new file mode 100644 index 00000000000..ec1be49d323 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedule_requests_operations.py @@ -0,0 +1,704 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_request(scope: str, role_assignment_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentScheduleRequestName": _SERIALIZER.url( + "role_assignment_schedule_request_name", role_assignment_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_assignment_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentScheduleRequestName": _SERIALIZER.url( + "role_assignment_schedule_request_name", role_assignment_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_cancel_request(scope: str, role_assignment_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}/cancel", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentScheduleRequestName": _SERIALIZER.url( + "role_assignment_schedule_request_name", role_assignment_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_validate_request(scope: str, role_assignment_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}/validate", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentScheduleRequestName": _SERIALIZER.url( + "role_assignment_schedule_request_name", role_assignment_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentScheduleRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.AuthorizationManagementClient`'s + :attr:`role_assignment_schedule_requests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: _models.RoleAssignmentScheduleRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Creates a role assignment schedule request. + + :param scope: The scope of the role assignment schedule request to create. The scope can be any + REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Creates a role assignment schedule request. + + :param scope: The scope of the role assignment schedule request to create. The scope can be any + REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: Union[_models.RoleAssignmentScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Creates a role assignment schedule request. + + :param scope: The scope of the role assignment schedule request to create. The scope can be any + REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentScheduleRequest") + + request = build_create_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignmentScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}"} # type: ignore + + @distributed_trace + def get( + self, scope: str, role_assignment_schedule_request_name: str, **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Get the specified role assignment schedule request. + + :param scope: The scope of the role assignment schedule request. Required. + :type scope: str + :param role_assignment_schedule_request_name: The name (guid) of the role assignment schedule + request to get. Required. + :type role_assignment_schedule_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequest] + + request = build_get_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignmentScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignmentScheduleRequest"]: + """Gets role assignment schedule requests for a scope. + + :param scope: The scope of the role assignments schedule requests. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignment schedule requests at or above the scope. Use $filter=principalId eq {id} to return + all role assignment schedule requests at, above or below the scope for the specified principal. + Use $filter=asRequestor() to return all role assignment schedule requests requested by the + current user. Use $filter=asTarget() to return all role assignment schedule requests created + for the current user. Use $filter=asApprover() to return all role assignment schedule requests + where the current user is an approver. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignmentScheduleRequest or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequestListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentScheduleRequestListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests"} # type: ignore + + @distributed_trace + def cancel( # pylint: disable=inconsistent-return-statements + self, scope: str, role_assignment_schedule_request_name: str, **kwargs: Any + ) -> None: + """Cancels a pending role assignment schedule request. + + :param scope: The scope of the role assignment request to cancel. Required. + :type scope: str + :param role_assignment_schedule_request_name: The name of the role assignment request to + cancel. Required. + :type role_assignment_schedule_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_cancel_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + template_url=self.cancel.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + cancel.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}/cancel"} # type: ignore + + @overload + def validate( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: _models.RoleAssignmentScheduleRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Validates a new role assignment schedule request. + + :param scope: The scope of the role assignment request to validate. Required. + :type scope: str + :param role_assignment_schedule_request_name: The name of the role assignment request to + validate. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def validate( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Validates a new role assignment schedule request. + + :param scope: The scope of the role assignment request to validate. Required. + :type scope: str + :param role_assignment_schedule_request_name: The name of the role assignment request to + validate. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def validate( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: Union[_models.RoleAssignmentScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Validates a new role assignment schedule request. + + :param scope: The scope of the role assignment request to validate. Required. + :type scope: str + :param role_assignment_schedule_request_name: The name of the role assignment request to + validate. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentScheduleRequest") + + request = build_validate_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignmentScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + validate.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}/validate"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedules_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedules_operations.py new file mode 100644 index 00000000000..b8f2c1f688b --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_assignment_schedules_operations.py @@ -0,0 +1,256 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, role_assignment_schedule_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules/{roleAssignmentScheduleName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentScheduleName": _SERIALIZER.url( + "role_assignment_schedule_name", role_assignment_schedule_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentSchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.AuthorizationManagementClient`'s + :attr:`role_assignment_schedules` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, role_assignment_schedule_name: str, **kwargs: Any) -> _models.RoleAssignmentSchedule: + """Get the specified role assignment schedule for a resource scope. + + :param scope: The scope of the role assignment schedule. Required. + :type scope: str + :param role_assignment_schedule_name: The name (guid) of the role assignment schedule to get. + Required. + :type role_assignment_schedule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentSchedule or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentSchedule] + + request = build_get_request( + scope=scope, + role_assignment_schedule_name=role_assignment_schedule_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignmentSchedule", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules/{roleAssignmentScheduleName}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignmentSchedule"]: + """Gets role assignment schedules for a resource scope. + + :param scope: The scope of the role assignments schedules. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role + assignment schedules at, above or below the scope for the specified principal. Use + $filter=assignedTo('{userId}') to return all role assignment schedules for the current user. + Use $filter=asTarget() to return all role assignment schedules created for the current user. + Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignmentSchedule or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleAssignmentSchedule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentScheduleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedule_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedule_instances_operations.py new file mode 100644 index 00000000000..fdec036dbba --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedule_instances_operations.py @@ -0,0 +1,258 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_eligibility_schedule_instance_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances/{roleEligibilityScheduleInstanceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleEligibilityScheduleInstanceName": _SERIALIZER.url( + "role_eligibility_schedule_instance_name", role_eligibility_schedule_instance_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleEligibilityScheduleInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedule_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleEligibilityScheduleInstance"]: + """Gets role eligibility schedule instances of a role eligibility schedule. + + :param scope: The scope of the role eligibility schedule. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role + assignment schedules at, above or below the scope for the specified principal. Use + $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use + $filter=asTarget() to return all role eligibility schedules created for the current user. + Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleEligibilityScheduleInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleEligibilityScheduleInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances"} # type: ignore + + @distributed_trace + def get( + self, scope: str, role_eligibility_schedule_instance_name: str, **kwargs: Any + ) -> _models.RoleEligibilityScheduleInstance: + """Gets the specified role eligibility schedule instance. + + :param scope: The scope of the role eligibility schedules. Required. + :type scope: str + :param role_eligibility_schedule_instance_name: The name (hash of schedule name + time) of the + role eligibility schedule to get. Required. + :type role_eligibility_schedule_instance_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleInstance] + + request = build_get_request( + scope=scope, + role_eligibility_schedule_instance_name=role_eligibility_schedule_instance_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleEligibilityScheduleInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances/{roleEligibilityScheduleInstanceName}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedule_requests_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedule_requests_operations.py new file mode 100644 index 00000000000..80415c24b3f --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedule_requests_operations.py @@ -0,0 +1,704 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_request(scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleEligibilityScheduleRequestName": _SERIALIZER.url( + "role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleEligibilityScheduleRequestName": _SERIALIZER.url( + "role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_cancel_request(scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}/cancel", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleEligibilityScheduleRequestName": _SERIALIZER.url( + "role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_validate_request(scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}/validate", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleEligibilityScheduleRequestName": _SERIALIZER.url( + "role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleEligibilityScheduleRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedule_requests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: _models.RoleEligibilityScheduleRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Creates a role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request to create. The scope can be + any REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It + can be any valid GUID. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Creates a role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request to create. The scope can be + any REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It + can be any valid GUID. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: Union[_models.RoleEligibilityScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Creates a role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request to create. The scope can be + any REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a + subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a + resource group, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It + can be any valid GUID. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleEligibilityScheduleRequest") + + request = build_create_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleEligibilityScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}"} # type: ignore + + @distributed_trace + def get( + self, scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Get the specified role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name (guid) of the role eligibility schedule + request to get. Required. + :type role_eligibility_schedule_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequest] + + request = build_get_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleEligibilityScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleEligibilityScheduleRequest"]: + """Gets role eligibility schedule requests for a scope. + + :param scope: The scope of the role eligibility schedule requests. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + eligibility schedule requests at or above the scope. Use $filter=principalId eq {id} to return + all role eligibility schedule requests at, above or below the scope for the specified + principal. Use $filter=asRequestor() to return all role eligibility schedule requests requested + by the current user. Use $filter=asTarget() to return all role eligibility schedule requests + created for the current user. Use $filter=asApprover() to return all role eligibility schedule + requests where the current user is an approver. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleEligibilityScheduleRequest or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequestListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleEligibilityScheduleRequestListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests"} # type: ignore + + @distributed_trace + def cancel( # pylint: disable=inconsistent-return-statements + self, scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any + ) -> None: + """Cancels a pending role eligibility schedule request. + + :param scope: The scope of the role eligibility request to cancel. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility request to + cancel. Required. + :type role_eligibility_schedule_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_cancel_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + template_url=self.cancel.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + cancel.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}/cancel"} # type: ignore + + @overload + def validate( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: _models.RoleEligibilityScheduleRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Validates a new role eligibility schedule request. + + :param scope: The scope of the role eligibility request to validate. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility request to + validate. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def validate( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Validates a new role eligibility schedule request. + + :param scope: The scope of the role eligibility request to validate. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility request to + validate. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def validate( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: Union[_models.RoleEligibilityScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Validates a new role eligibility schedule request. + + :param scope: The scope of the role eligibility request to validate. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility request to + validate. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleEligibilityScheduleRequest") + + request = build_validate_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleEligibilityScheduleRequest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + validate.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}/validate"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedules_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedules_operations.py new file mode 100644 index 00000000000..cb3b0f6eb00 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_eligibility_schedules_operations.py @@ -0,0 +1,256 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, role_eligibility_schedule_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules/{roleEligibilityScheduleName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleEligibilityScheduleName": _SERIALIZER.url( + "role_eligibility_schedule_name", role_eligibility_schedule_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleEligibilitySchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedules` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, role_eligibility_schedule_name: str, **kwargs: Any) -> _models.RoleEligibilitySchedule: + """Get the specified role eligibility schedule for a resource scope. + + :param scope: The scope of the role eligibility schedule. Required. + :type scope: str + :param role_eligibility_schedule_name: The name (guid) of the role eligibility schedule to get. + Required. + :type role_eligibility_schedule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilitySchedule or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilitySchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilitySchedule] + + request = build_get_request( + scope=scope, + role_eligibility_schedule_name=role_eligibility_schedule_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleEligibilitySchedule", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules/{roleEligibilityScheduleName}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleEligibilitySchedule"]: + """Gets role eligibility schedules for a resource scope. + + :param scope: The scope of the role eligibility schedules. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + eligibility schedules at or above the scope. Use $filter=principalId eq {id} to return all role + eligibility schedules at, above or below the scope for the specified principal. Use + $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use + $filter=asTarget() to return all role eligibility schedules created for the current user. + Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleEligibilitySchedule or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleEligibilitySchedule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleEligibilityScheduleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_management_policies_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_management_policies_operations.py new file mode 100644 index 00000000000..78e288890b1 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_management_policies_operations.py @@ -0,0 +1,492 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, role_management_policy_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyName": _SERIALIZER.url("role_management_policy_name", role_management_policy_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request(scope: str, role_management_policy_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyName": _SERIALIZER.url("role_management_policy_name", role_management_policy_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(scope: str, role_management_policy_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyName": _SERIALIZER.url("role_management_policy_name", role_management_policy_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleManagementPoliciesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.AuthorizationManagementClient`'s + :attr:`role_management_policies` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, role_management_policy_name: str, **kwargs: Any) -> _models.RoleManagementPolicy: + """Get the specified role management policy for a resource scope. + + :param scope: The scope of the role management policy. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to get. + Required. + :type role_management_policy_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicy] + + request = build_get_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleManagementPolicy", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore + + @overload + def update( + self, + scope: str, + role_management_policy_name: str, + parameters: _models.RoleManagementPolicy, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicy: + """Update a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :param parameters: Parameters for the role management policy. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + scope: str, + role_management_policy_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicy: + """Update a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :param parameters: Parameters for the role management policy. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + scope: str, + role_management_policy_name: str, + parameters: Union[_models.RoleManagementPolicy, IO], + **kwargs: Any + ) -> _models.RoleManagementPolicy: + """Update a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :param parameters: Parameters for the role management policy. Is either a model type or a IO + type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicy] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleManagementPolicy") + + request = build_update_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleManagementPolicy", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, role_management_policy_name: str, **kwargs: Any + ) -> None: + """Delete a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.RoleManagementPolicy"]: + """Gets role management policies for a resource scope. + + :param scope: The scope of the role management policy. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleManagementPolicy or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleManagementPolicyListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_management_policy_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_management_policy_assignments_operations.py new file mode 100644 index 00000000000..779aff60d74 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/operations/_role_management_policy_assignments_operations.py @@ -0,0 +1,504 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, role_management_policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyAssignmentName": _SERIALIZER.url( + "role_management_policy_assignment_name", role_management_policy_assignment_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(scope: str, role_management_policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyAssignmentName": _SERIALIZER.url( + "role_management_policy_assignment_name", role_management_policy_assignment_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(scope: str, role_management_policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyAssignmentName": _SERIALIZER.url( + "role_management_policy_assignment_name", role_management_policy_assignment_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleManagementPolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01.AuthorizationManagementClient`'s + :attr:`role_management_policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, scope: str, role_management_policy_assignment_name: str, **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Get the specified role management policy assignment for a resource scope. + + :param scope: The scope of the role management policy. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to get. Required. + :type role_management_policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignment] + + request = build_get_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleManagementPolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore + + @overload + def create( + self, + scope: str, + role_management_policy_assignment_name: str, + parameters: _models.RoleManagementPolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Create a role management policy assignment. + + :param scope: The scope of the role management policy assignment to upsert. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to upsert. Required. + :type role_management_policy_assignment_name: str + :param parameters: Parameters for the role management policy assignment. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + role_management_policy_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Create a role management policy assignment. + + :param scope: The scope of the role management policy assignment to upsert. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to upsert. Required. + :type role_management_policy_assignment_name: str + :param parameters: Parameters for the role management policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_management_policy_assignment_name: str, + parameters: Union[_models.RoleManagementPolicyAssignment, IO], + **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Create a role management policy assignment. + + :param scope: The scope of the role management policy assignment to upsert. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to upsert. Required. + :type role_management_policy_assignment_name: str + :param parameters: Parameters for the role management policy assignment. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleManagementPolicyAssignment") + + request = build_create_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleManagementPolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, role_management_policy_assignment_name: str, **kwargs: Any + ) -> None: + """Delete a role management policy assignment. + + :param scope: The scope of the role management policy assignment to delete. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to delete. Required. + :type role_management_policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.RoleManagementPolicyAssignment"]: + """Gets role management assignment policies for a resource scope. + + :param scope: The scope of the role management policy. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleManagementPolicyAssignment or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01.models.RoleManagementPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleManagementPolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/py.typed b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/py.typed new file mode 100644 index 00000000000..e5aff4f83af --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/__init__.py index ae11ad3e4d9..9eb8d3ec28c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AuthorizationManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_authorization_management_client.py index ea267e40412..ba9327b59d3 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_authorization_management_client.py @@ -6,118 +6,148 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + EligibleChildResourcesOperations, + RoleAssignmentScheduleInstancesOperations, + RoleAssignmentScheduleRequestsOperations, + RoleAssignmentSchedulesOperations, + RoleAssignmentsOperations, + RoleEligibilityScheduleInstancesOperations, + RoleEligibilityScheduleRequestsOperations, + RoleEligibilitySchedulesOperations, + RoleManagementPoliciesOperations, + RoleManagementPolicyAssignmentsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import RoleAssignmentsOperations -from .operations import EligibleChildResourcesOperations -from .operations import RoleAssignmentSchedulesOperations -from .operations import RoleAssignmentScheduleInstancesOperations -from .operations import RoleAssignmentScheduleRequestsOperations -from .operations import RoleEligibilitySchedulesOperations -from .operations import RoleEligibilityScheduleInstancesOperations -from .operations import RoleEligibilityScheduleRequestsOperations -from .operations import RoleManagementPoliciesOperations -from .operations import RoleManagementPolicyAssignmentsOperations -from . import models -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + assignments. A role assignment grants access to Azure Active Directory users. :ivar role_assignments: RoleAssignmentsOperations operations - :vartype role_assignments: azure.mgmt.authorization.v2020_10_01_preview.operations.RoleAssignmentsOperations + :vartype role_assignments: + azure.mgmt.authorization.v2020_10_01_preview.operations.RoleAssignmentsOperations :ivar eligible_child_resources: EligibleChildResourcesOperations operations - :vartype eligible_child_resources: azure.mgmt.authorization.v2020_10_01_preview.operations.EligibleChildResourcesOperations + :vartype eligible_child_resources: + azure.mgmt.authorization.v2020_10_01_preview.operations.EligibleChildResourcesOperations :ivar role_assignment_schedules: RoleAssignmentSchedulesOperations operations - :vartype role_assignment_schedules: azure.mgmt.authorization.v2020_10_01_preview.operations.RoleAssignmentSchedulesOperations + :vartype role_assignment_schedules: + azure.mgmt.authorization.v2020_10_01_preview.operations.RoleAssignmentSchedulesOperations :ivar role_assignment_schedule_instances: RoleAssignmentScheduleInstancesOperations operations - :vartype role_assignment_schedule_instances: azure.mgmt.authorization.v2020_10_01_preview.operations.RoleAssignmentScheduleInstancesOperations + :vartype role_assignment_schedule_instances: + azure.mgmt.authorization.v2020_10_01_preview.operations.RoleAssignmentScheduleInstancesOperations :ivar role_assignment_schedule_requests: RoleAssignmentScheduleRequestsOperations operations - :vartype role_assignment_schedule_requests: azure.mgmt.authorization.v2020_10_01_preview.operations.RoleAssignmentScheduleRequestsOperations + :vartype role_assignment_schedule_requests: + azure.mgmt.authorization.v2020_10_01_preview.operations.RoleAssignmentScheduleRequestsOperations :ivar role_eligibility_schedules: RoleEligibilitySchedulesOperations operations - :vartype role_eligibility_schedules: azure.mgmt.authorization.v2020_10_01_preview.operations.RoleEligibilitySchedulesOperations - :ivar role_eligibility_schedule_instances: RoleEligibilityScheduleInstancesOperations operations - :vartype role_eligibility_schedule_instances: azure.mgmt.authorization.v2020_10_01_preview.operations.RoleEligibilityScheduleInstancesOperations + :vartype role_eligibility_schedules: + azure.mgmt.authorization.v2020_10_01_preview.operations.RoleEligibilitySchedulesOperations + :ivar role_eligibility_schedule_instances: RoleEligibilityScheduleInstancesOperations + operations + :vartype role_eligibility_schedule_instances: + azure.mgmt.authorization.v2020_10_01_preview.operations.RoleEligibilityScheduleInstancesOperations :ivar role_eligibility_schedule_requests: RoleEligibilityScheduleRequestsOperations operations - :vartype role_eligibility_schedule_requests: azure.mgmt.authorization.v2020_10_01_preview.operations.RoleEligibilityScheduleRequestsOperations + :vartype role_eligibility_schedule_requests: + azure.mgmt.authorization.v2020_10_01_preview.operations.RoleEligibilityScheduleRequestsOperations :ivar role_management_policies: RoleManagementPoliciesOperations operations - :vartype role_management_policies: azure.mgmt.authorization.v2020_10_01_preview.operations.RoleManagementPoliciesOperations + :vartype role_management_policies: + azure.mgmt.authorization.v2020_10_01_preview.operations.RoleManagementPoliciesOperations :ivar role_management_policy_assignments: RoleManagementPolicyAssignmentsOperations operations - :vartype role_management_policy_assignments: azure.mgmt.authorization.v2020_10_01_preview.operations.RoleManagementPolicyAssignmentsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype role_management_policy_assignments: + azure.mgmt.authorization.v2020_10_01_preview.operations.RoleManagementPolicyAssignmentsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2020-10-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.role_assignments = RoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.eligible_child_resources = EligibleChildResourcesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignment_schedules = RoleAssignmentSchedulesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignment_schedule_instances = RoleAssignmentScheduleInstancesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignment_schedule_requests = RoleAssignmentScheduleRequestsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_eligibility_schedules = RoleEligibilitySchedulesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_eligibility_schedule_instances = RoleEligibilityScheduleInstancesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_eligibility_schedule_requests = RoleEligibilityScheduleRequestsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_management_policies = RoleManagementPoliciesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_management_policy_assignments = RoleManagementPolicyAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_configuration.py index 9e18c0b4399..8d58a6a56d8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_configuration.py @@ -6,66 +6,64 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2020-10-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2020-10-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2020-10-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_metadata.json index bd67cca3e12..de12071396e 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_metadata.json +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_metadata.json @@ -5,25 +5,25 @@ "name": "AuthorizationManagementClient", "filename": "_authorization_management_client", "description": "Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, "azure_arm": true, "has_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -54,7 +54,7 @@ "required": false }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -74,7 +74,7 @@ "required": false }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -91,11 +91,10 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "role_assignments": "RoleAssignmentsOperations", diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_version.py index 48944bf3938..cac9f5d10f8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/__init__.py index ffc49d028e4..dd28625b36f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._authorization_management_client import AuthorizationManagementClient -__all__ = ['AuthorizationManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_authorization_management_client.py index a1de37eddf5..402f800c341 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_authorization_management_client.py @@ -6,114 +6,148 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + EligibleChildResourcesOperations, + RoleAssignmentScheduleInstancesOperations, + RoleAssignmentScheduleRequestsOperations, + RoleAssignmentSchedulesOperations, + RoleAssignmentsOperations, + RoleEligibilityScheduleInstancesOperations, + RoleEligibilityScheduleRequestsOperations, + RoleEligibilitySchedulesOperations, + RoleManagementPoliciesOperations, + RoleManagementPolicyAssignmentsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import RoleAssignmentsOperations -from .operations import EligibleChildResourcesOperations -from .operations import RoleAssignmentSchedulesOperations -from .operations import RoleAssignmentScheduleInstancesOperations -from .operations import RoleAssignmentScheduleRequestsOperations -from .operations import RoleEligibilitySchedulesOperations -from .operations import RoleEligibilityScheduleInstancesOperations -from .operations import RoleEligibilityScheduleRequestsOperations -from .operations import RoleManagementPoliciesOperations -from .operations import RoleManagementPolicyAssignmentsOperations -from .. import models - -class AuthorizationManagementClient(object): - """Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to manage role + assignments. A role assignment grants access to Azure Active Directory users. :ivar role_assignments: RoleAssignmentsOperations operations - :vartype role_assignments: azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleAssignmentsOperations + :vartype role_assignments: + azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleAssignmentsOperations :ivar eligible_child_resources: EligibleChildResourcesOperations operations - :vartype eligible_child_resources: azure.mgmt.authorization.v2020_10_01_preview.aio.operations.EligibleChildResourcesOperations + :vartype eligible_child_resources: + azure.mgmt.authorization.v2020_10_01_preview.aio.operations.EligibleChildResourcesOperations :ivar role_assignment_schedules: RoleAssignmentSchedulesOperations operations - :vartype role_assignment_schedules: azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleAssignmentSchedulesOperations + :vartype role_assignment_schedules: + azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleAssignmentSchedulesOperations :ivar role_assignment_schedule_instances: RoleAssignmentScheduleInstancesOperations operations - :vartype role_assignment_schedule_instances: azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleAssignmentScheduleInstancesOperations + :vartype role_assignment_schedule_instances: + azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleAssignmentScheduleInstancesOperations :ivar role_assignment_schedule_requests: RoleAssignmentScheduleRequestsOperations operations - :vartype role_assignment_schedule_requests: azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleAssignmentScheduleRequestsOperations + :vartype role_assignment_schedule_requests: + azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleAssignmentScheduleRequestsOperations :ivar role_eligibility_schedules: RoleEligibilitySchedulesOperations operations - :vartype role_eligibility_schedules: azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleEligibilitySchedulesOperations - :ivar role_eligibility_schedule_instances: RoleEligibilityScheduleInstancesOperations operations - :vartype role_eligibility_schedule_instances: azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleEligibilityScheduleInstancesOperations + :vartype role_eligibility_schedules: + azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleEligibilitySchedulesOperations + :ivar role_eligibility_schedule_instances: RoleEligibilityScheduleInstancesOperations + operations + :vartype role_eligibility_schedule_instances: + azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleEligibilityScheduleInstancesOperations :ivar role_eligibility_schedule_requests: RoleEligibilityScheduleRequestsOperations operations - :vartype role_eligibility_schedule_requests: azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleEligibilityScheduleRequestsOperations + :vartype role_eligibility_schedule_requests: + azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleEligibilityScheduleRequestsOperations :ivar role_management_policies: RoleManagementPoliciesOperations operations - :vartype role_management_policies: azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleManagementPoliciesOperations + :vartype role_management_policies: + azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleManagementPoliciesOperations :ivar role_management_policy_assignments: RoleManagementPolicyAssignmentsOperations operations - :vartype role_management_policy_assignments: azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleManagementPolicyAssignmentsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype role_management_policy_assignments: + azure.mgmt.authorization.v2020_10_01_preview.aio.operations.RoleManagementPolicyAssignmentsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2020-10-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.role_assignments = RoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.eligible_child_resources = EligibleChildResourcesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignment_schedules = RoleAssignmentSchedulesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignment_schedule_instances = RoleAssignmentScheduleInstancesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignment_schedule_requests = RoleAssignmentScheduleRequestsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_eligibility_schedules = RoleEligibilitySchedulesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_eligibility_schedule_instances = RoleEligibilityScheduleInstancesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_eligibility_schedule_requests = RoleEligibilityScheduleRequestsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_management_policies = RoleManagementPoliciesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_management_policy_assignments = RoleManagementPolicyAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_configuration.py index 9977bad5f6d..76759d0c5f1 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,49 +19,48 @@ from azure.core.credentials_async import AsyncTokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2020-10-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2020-10-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2020-10-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/__init__.py index 97e8639830c..baf561800ad 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/__init__.py @@ -17,15 +17,21 @@ from ._role_management_policies_operations import RoleManagementPoliciesOperations from ._role_management_policy_assignments_operations import RoleManagementPolicyAssignmentsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RoleAssignmentsOperations', - 'EligibleChildResourcesOperations', - 'RoleAssignmentSchedulesOperations', - 'RoleAssignmentScheduleInstancesOperations', - 'RoleAssignmentScheduleRequestsOperations', - 'RoleEligibilitySchedulesOperations', - 'RoleEligibilityScheduleInstancesOperations', - 'RoleEligibilityScheduleRequestsOperations', - 'RoleManagementPoliciesOperations', - 'RoleManagementPolicyAssignmentsOperations', + "RoleAssignmentsOperations", + "EligibleChildResourcesOperations", + "RoleAssignmentSchedulesOperations", + "RoleAssignmentScheduleInstancesOperations", + "RoleAssignmentScheduleRequestsOperations", + "RoleEligibilitySchedulesOperations", + "RoleEligibilityScheduleInstancesOperations", + "RoleEligibilityScheduleRequestsOperations", + "RoleManagementPoliciesOperations", + "RoleManagementPolicyAssignmentsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_eligible_child_resources_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_eligible_child_resources_operations.py index 61bbae50ecc..7399c878a5e 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_eligible_child_resources_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_eligible_child_resources_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,97 +6,113 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._eligible_child_resources_operations import build_get_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class EligibleChildResourcesOperations: - """EligibleChildResourcesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class EligibleChildResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.aio.AuthorizationManagementClient`'s + :attr:`eligible_child_resources` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def get( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.EligibleChildResourcesListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.EligibleChildResource"]: """Get the child resources of a resource on which user has eligible access. - :param scope: The scope of the role management policy. + :param scope: The scope of the role management policy. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=resourceType+eq+'Subscription' to filter on only resource of type = 'Subscription'. Use $filter=resourceType+eq+'subscription'+or+resourceType+eq+'resourcegroup' to filter on resource - of type = 'Subscription' or 'ResourceGroup'. + of type = 'Subscription' or 'ResourceGroup'. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either EligibleChildResourcesListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.EligibleChildResourcesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either EligibleChildResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.EligibleChildResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.EligibleChildResourcesListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.EligibleChildResourcesListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_get_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('EligibleChildResourcesListResult', pipeline_response) + deserialized = self._deserialize("EligibleChildResourcesListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -104,7 +121,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -113,7 +132,6 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/eligibleChildResources'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/eligibleChildResources"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedule_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedule_instances_operations.py index 3efcc5ed2bd..043e4bf1976 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedule_instances_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedule_instances_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,99 +6,116 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_assignment_schedule_instances_operations import build_get_request, build_list_for_scope_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentScheduleInstancesOperations: - """RoleAssignmentScheduleInstancesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentScheduleInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_assignment_schedule_instances` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentScheduleInstanceListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignmentScheduleInstance"]: """Gets role assignment schedule instances of a role assignment schedule. - :param scope: The scope of the role assignment schedule. + :param scope: The scope of the role assignment schedule. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role assignment schedule instances for the user. Use $filter=asTarget() to return all role assignment schedule instances created for the current - user. + user. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentScheduleInstanceListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignmentScheduleInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentScheduleInstanceListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -106,7 +124,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -115,65 +135,66 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances"} # type: ignore + @distributed_trace_async async def get( - self, - scope: str, - role_assignment_schedule_instance_name: str, - **kwargs: Any - ) -> "_models.RoleAssignmentScheduleInstance": + self, scope: str, role_assignment_schedule_instance_name: str, **kwargs: Any + ) -> _models.RoleAssignmentScheduleInstance: """Gets the specified role assignment schedule instance. - :param scope: The scope of the role assignments schedules. + :param scope: The scope of the role assignments schedules. Required. :type scope: str :param role_assignment_schedule_instance_name: The name (hash of schedule name + time) of the - role assignment schedule to get. + role assignment schedule to get. Required. :type role_assignment_schedule_instance_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentScheduleInstance, or the result of cls(response) + :return: RoleAssignmentScheduleInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentScheduleInstanceName': self._serialize.url("role_assignment_schedule_instance_name", role_assignment_schedule_instance_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleInstance] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + role_assignment_schedule_instance_name=role_assignment_schedule_instance_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentScheduleInstance', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances/{roleAssignmentScheduleInstanceName}'} # type: ignore + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances/{roleAssignmentScheduleInstanceName}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedule_requests_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedule_requests_operations.py index d5c1a38e36b..2a7f9a6fc08 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedule_requests_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedule_requests_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,49 +6,68 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_assignment_schedule_requests_operations import ( + build_cancel_request, + build_create_request, + build_get_request, + build_list_for_scope_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentScheduleRequestsOperations: - """RoleAssignmentScheduleRequestsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentScheduleRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_assignment_schedule_requests` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @overload async def create( self, scope: str, role_assignment_schedule_request_name: str, - parameters: "_models.RoleAssignmentScheduleRequest", + parameters: _models.RoleAssignmentScheduleRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignmentScheduleRequest": + ) -> _models.RoleAssignmentScheduleRequest: """Creates a role assignment schedule request. :param scope: The scope of the role assignment schedule request to create. The scope can be any @@ -56,130 +76,213 @@ async def create( '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str - :param role_assignment_schedule_request_name: The name of the role assignment to create. It can - be any valid GUID. + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. :type role_assignment_schedule_request_name: str - :param parameters: Parameters for the role assignment schedule request. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentScheduleRequest, or the result of cls(response) + :return: RoleAssignmentScheduleRequest or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Creates a role assignment schedule request. + + :param scope: The scope of the role assignment schedule request to create. The scope can be any + REST resource instance. For example, use + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: Union[_models.RoleAssignmentScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Creates a role assignment schedule request. + + :param scope: The scope of the role assignment schedule request to create. The scope can be any + REST resource instance. For example, use + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Is either a model type + or a IO type. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleRequest"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentScheduleRequestName': self._serialize.url("role_assignment_schedule_request_name", role_assignment_schedule_request_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentScheduleRequest') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentScheduleRequest") + + request = build_create_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentScheduleRequest', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleRequest", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}'} # type: ignore + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}"} # type: ignore + + @distributed_trace_async async def get( - self, - scope: str, - role_assignment_schedule_request_name: str, - **kwargs: Any - ) -> "_models.RoleAssignmentScheduleRequest": + self, scope: str, role_assignment_schedule_request_name: str, **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: """Get the specified role assignment schedule request. - :param scope: The scope of the role assignment schedule request. + :param scope: The scope of the role assignment schedule request. Required. :type scope: str :param role_assignment_schedule_request_name: The name (guid) of the role assignment schedule - request to get. + request to get. Required. :type role_assignment_schedule_request_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentScheduleRequest, or the result of cls(response) + :return: RoleAssignmentScheduleRequest or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleRequest"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentScheduleRequestName': self._serialize.url("role_assignment_schedule_request_name", role_assignment_schedule_request_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequest] + + request = build_get_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentScheduleRequest', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleRequest", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentScheduleRequestListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignmentScheduleRequest"]: """Gets role assignment schedule requests for a scope. - :param scope: The scope of the role assignments schedule requests. + :param scope: The scope of the role assignments schedule requests. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedule requests at or above the scope. Use $filter=principalId eq {id} to return @@ -187,48 +290,56 @@ def list_for_scope( Use $filter=asRequestor() to return all role assignment schedule requests requested by the current user. Use $filter=asTarget() to return all role assignment schedule requests created for the current user. Use $filter=asApprover() to return all role assignment schedule requests - where the current user is an approver. + where the current user is an approver. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentScheduleRequestListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequestListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignmentScheduleRequest or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleRequestListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequestListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentScheduleRequestListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleRequestListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -237,7 +348,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -246,55 +359,55 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def cancel( - self, - scope: str, - role_assignment_schedule_request_name: str, - **kwargs: Any + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests"} # type: ignore + + @distributed_trace_async + async def cancel( # pylint: disable=inconsistent-return-statements + self, scope: str, role_assignment_schedule_request_name: str, **kwargs: Any ) -> None: """Cancels a pending role assignment schedule request. - :param scope: The scope of the role assignment request to cancel. + :param scope: The scope of the role assignment request to cancel. Required. :type scope: str :param role_assignment_schedule_request_name: The name of the role assignment request to - cancel. + cancel. Required. :type role_assignment_schedule_request_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.cancel.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentScheduleRequestName': self._serialize.url("role_assignment_schedule_request_name", role_assignment_schedule_request_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_cancel_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + template_url=self.cancel.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -304,4 +417,4 @@ async def cancel( if cls: return cls(pipeline_response, None, {}) - cancel.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}/cancel'} # type: ignore + cancel.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}/cancel"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedules_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedules_operations.py index 0a60be766dc..c7702b5bd38 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedules_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignment_schedules_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,155 +6,176 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_assignment_schedules_operations import build_get_request, build_list_for_scope_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentSchedulesOperations: - """RoleAssignmentSchedulesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentSchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_assignment_schedules` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace_async async def get( - self, - scope: str, - role_assignment_schedule_name: str, - **kwargs: Any - ) -> "_models.RoleAssignmentSchedule": + self, scope: str, role_assignment_schedule_name: str, **kwargs: Any + ) -> _models.RoleAssignmentSchedule: """Get the specified role assignment schedule for a resource scope. - :param scope: The scope of the role assignment schedule. + :param scope: The scope of the role assignment schedule. Required. :type scope: str :param role_assignment_schedule_name: The name (guid) of the role assignment schedule to get. + Required. :type role_assignment_schedule_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentSchedule, or the result of cls(response) + :return: RoleAssignmentSchedule or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentSchedule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentSchedule"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentScheduleName': self._serialize.url("role_assignment_schedule_name", role_assignment_schedule_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentSchedule] + + request = build_get_request( + scope=scope, + role_assignment_schedule_name=role_assignment_schedule_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentSchedule', pipeline_response) + deserialized = self._deserialize("RoleAssignmentSchedule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules/{roleAssignmentScheduleName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules/{roleAssignmentScheduleName}"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentScheduleListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignmentSchedule"]: """Gets role assignment schedules for a resource scope. - :param scope: The scope of the role assignments schedules. + :param scope: The scope of the role assignments schedules. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role assignment schedules for the current user. Use $filter=asTarget() to return all role assignment schedules created for the current user. + Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentScheduleListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignmentSchedule or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentSchedule] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentScheduleListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -162,7 +184,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -171,7 +195,6 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignments_operations.py index 9e0bb270be8..a873b099133 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,98 +6,126 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_assignments_operations import ( + build_create_by_id_request, + build_create_request, + build_delete_by_id_request, + build_delete_request, + build_get_by_id_request, + build_get_request, + build_list_for_resource_group_request, + build_list_for_resource_request, + build_list_for_scope_request, + build_list_for_subscription_request, + build_validate_by_id_request, + build_validate_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentsOperations: - """RoleAssignmentsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_subscription( - self, - filter: Optional[str] = None, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """List all role assignments that apply to a subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_subscription_request( + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -105,81 +134,86 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_resource_group( - self, - resource_group_name: str, - filter: Optional[str] = None, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, resource_group_name: str, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """List all role assignments that apply to a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -188,21 +222,23 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace def list_for_resource( self, resource_group_name: str, @@ -212,70 +248,77 @@ def list_for_resource( filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + ) -> AsyncIterable["_models.RoleAssignment"]: """List all role assignments that apply to a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str :param resource_type: The resource type name. For example the type name of a web app is 'sites' - (from Microsoft.Web/sites). + (from Microsoft.Web/sites). Required. :type resource_type: str - :param resource_name: The resource name. + :param resource_name: The resource name. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -284,359 +327,536 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace_async async def get( - self, - scope: str, - role_assignment_name: str, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> "_models.RoleAssignment": + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> _models.RoleAssignment: """Get a role assignment by scope and name. :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. :type scope: str :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. :type role_assignment_name: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload async def create( self, scope: str, role_assignment_name: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignment": + ) -> _models.RoleAssignment: """Create or update a role assignment by scope and name. :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. :type scope: str :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace_async async def delete( - self, - scope: str, - role_assignment_name: str, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> Optional["_models.RoleAssignment"]: + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: """Delete a role assignment by scope and name. :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. :type scope: str :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. :type role_assignment_name: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload + async def validate( + self, + scope: str, + role_assignment_name: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ValidationResponse: + """Validate a role assignment create or update operation by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidationResponse or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def validate( + self, + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ValidationResponse: + """Validate a role assignment create or update operation by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidationResponse or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async async def validate( self, scope: str, role_assignment_name: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any - ) -> "_models.ValidationResponse": + ) -> _models.ValidationResponse: """Validate a role assignment create or update operation by scope and name. :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. :type scope: str :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ValidationResponse, or the result of cls(response) + :return: ValidationResponse or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ValidationResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.validate.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidationResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_validate_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ValidationResponse', pipeline_response) + deserialized = self._deserialize("ValidationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - validate.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}/validate'} # type: ignore + validate.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}/validate"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentListResult"]: + self, scope: str, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: """List all role assignments that apply to a scope. :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -645,277 +865,416 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace_async async def get_by_id( - self, - role_assignment_id: str, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> "_models.RoleAssignment": + self, role_assignment_id: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> _models.RoleAssignment: """Get a role assignment by ID. :param role_assignment_id: The fully qualified ID of the role assignment including scope, resource name, and resource type. Format: /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. :type role_assignment_id: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + role_assignment_id=role_assignment_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore + get_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @overload async def create_by_id( self, role_assignment_id: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignment": + ) -> _models.RoleAssignment: + """Create or update a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, role_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: """Create or update a role assignment by ID. :param role_assignment_id: The fully qualified ID of the role assignment including scope, resource name, and resource type. Format: /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. :type role_assignment_id: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, role_assignment_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore + create_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @distributed_trace_async async def delete_by_id( - self, - role_assignment_id: str, - tenant_id: Optional[str] = None, - **kwargs: Any - ) -> Optional["_models.RoleAssignment"]: + self, role_assignment_id: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: """Delete a role assignment by ID. :param role_assignment_id: The fully qualified ID of the role assignment including scope, resource name, and resource type. Format: /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. :type role_assignment_id: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_by_id_request( + role_assignment_id=role_assignment_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore + delete_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @overload async def validate_by_id( self, role_assignment_id: str, - parameters: "_models.RoleAssignmentCreateParameters", + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.ValidationResponse": + ) -> _models.ValidationResponse: """Validate a role assignment create or update operation by ID. :param role_assignment_id: The fully qualified ID of the role assignment including scope, resource name, and resource type. Format: /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. :type role_assignment_id: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ValidationResponse, or the result of cls(response) + :return: ValidationResponse or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def validate_by_id( + self, role_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ValidationResponse: + """Validate a role assignment create or update operation by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidationResponse or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def validate_by_id( + self, role_assignment_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.ValidationResponse: + """Validate a role assignment create or update operation by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidationResponse or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ValidationResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.validate_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidationResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_validate_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ValidationResponse', pipeline_response) + deserialized = self._deserialize("ValidationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - validate_by_id.metadata = {'url': '/{roleAssignmentId}/validate'} # type: ignore + + validate_by_id.metadata = {"url": "/{roleAssignmentId}/validate"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedule_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedule_instances_operations.py index 87f2bc311b3..8c8f5d1887e 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedule_instances_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedule_instances_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,98 +6,119 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_eligibility_schedule_instances_operations import ( + build_get_request, + build_list_for_scope_request, +) -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleEligibilityScheduleInstancesOperations: - """RoleEligibilityScheduleInstancesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleEligibilityScheduleInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedule_instances` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleEligibilityScheduleInstanceListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleEligibilityScheduleInstance"]: """Gets role eligibility schedule instances of a role eligibility schedule. - :param scope: The scope of the role eligibility schedule. + :param scope: The scope of the role eligibility schedule. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use $filter=asTarget() to return all role eligibility schedules created for the current user. + Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleEligibilityScheduleInstanceListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleEligibilityScheduleInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleEligibilityScheduleInstanceListResult', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -105,7 +127,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -114,65 +138,66 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances"} # type: ignore + @distributed_trace_async async def get( - self, - scope: str, - role_eligibility_schedule_instance_name: str, - **kwargs: Any - ) -> "_models.RoleEligibilityScheduleInstance": + self, scope: str, role_eligibility_schedule_instance_name: str, **kwargs: Any + ) -> _models.RoleEligibilityScheduleInstance: """Gets the specified role eligibility schedule instance. - :param scope: The scope of the role eligibility schedules. + :param scope: The scope of the role eligibility schedules. Required. :type scope: str :param role_eligibility_schedule_instance_name: The name (hash of schedule name + time) of the - role eligibility schedule to get. + role eligibility schedule to get. Required. :type role_eligibility_schedule_instance_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleEligibilityScheduleInstance, or the result of cls(response) + :return: RoleEligibilityScheduleInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleEligibilityScheduleInstanceName': self._serialize.url("role_eligibility_schedule_instance_name", role_eligibility_schedule_instance_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleInstance] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + role_eligibility_schedule_instance_name=role_eligibility_schedule_instance_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleEligibilityScheduleInstance', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances/{roleEligibilityScheduleInstanceName}'} # type: ignore + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances/{roleEligibilityScheduleInstanceName}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedule_requests_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedule_requests_operations.py index fced3034ad2..49003f725e8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedule_requests_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedule_requests_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,49 +6,103 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_eligibility_schedule_requests_operations import ( + build_cancel_request, + build_create_request, + build_get_request, + build_list_for_scope_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleEligibilityScheduleRequestsOperations: - """RoleEligibilityScheduleRequestsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleEligibilityScheduleRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedule_requests` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: _models.RoleEligibilityScheduleRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Creates a role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request to create. The scope can be + any REST resource instance. For example, use + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It + can be any valid GUID. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + @overload async def create( self, scope: str, role_eligibility_schedule_request_name: str, - parameters: "_models.RoleEligibilityScheduleRequest", + parameters: IO, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleEligibilityScheduleRequest": + ) -> _models.RoleEligibilityScheduleRequest: """Creates a role eligibility schedule request. :param scope: The scope of the role eligibility schedule request to create. The scope can be @@ -56,130 +111,178 @@ async def create( '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It - can be any valid GUID. + can be any valid GUID. Required. :type role_eligibility_schedule_request_name: str - :param parameters: Parameters for the role eligibility schedule request. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleEligibilityScheduleRequest, or the result of cls(response) + :return: RoleEligibilityScheduleRequest or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: Union[_models.RoleEligibilityScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Creates a role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request to create. The scope can be + any REST resource instance. For example, use + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It + can be any valid GUID. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Is either a model type + or a IO type. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleRequest"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleEligibilityScheduleRequestName': self._serialize.url("role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleEligibilityScheduleRequest') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleEligibilityScheduleRequest") + + request = build_create_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleEligibilityScheduleRequest', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleRequest", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}'} # type: ignore + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}"} # type: ignore + + @distributed_trace_async async def get( - self, - scope: str, - role_eligibility_schedule_request_name: str, - **kwargs: Any - ) -> "_models.RoleEligibilityScheduleRequest": + self, scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: """Get the specified role eligibility schedule request. - :param scope: The scope of the role eligibility schedule request. + :param scope: The scope of the role eligibility schedule request. Required. :type scope: str :param role_eligibility_schedule_request_name: The name (guid) of the role eligibility schedule - request to get. + request to get. Required. :type role_eligibility_schedule_request_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleEligibilityScheduleRequest, or the result of cls(response) + :return: RoleEligibilityScheduleRequest or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleRequest"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleEligibilityScheduleRequestName': self._serialize.url("role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequest] + + request = build_get_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleEligibilityScheduleRequest', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleRequest", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleEligibilityScheduleRequestListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleEligibilityScheduleRequest"]: """Gets role eligibility schedule requests for a scope. - :param scope: The scope of the role eligibility schedule requests. + :param scope: The scope of the role eligibility schedule requests. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role eligibility schedule requests at or above the scope. Use $filter=principalId eq {id} to return @@ -187,48 +290,56 @@ def list_for_scope( principal. Use $filter=asRequestor() to return all role eligibility schedule requests requested by the current user. Use $filter=asTarget() to return all role eligibility schedule requests created for the current user. Use $filter=asApprover() to return all role eligibility schedule - requests where the current user is an approver. + requests where the current user is an approver. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleEligibilityScheduleRequestListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequestListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleEligibilityScheduleRequest or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleRequestListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequestListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleEligibilityScheduleRequestListResult', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleRequestListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -237,7 +348,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -246,55 +359,55 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def cancel( - self, - scope: str, - role_eligibility_schedule_request_name: str, - **kwargs: Any + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests"} # type: ignore + + @distributed_trace_async + async def cancel( # pylint: disable=inconsistent-return-statements + self, scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any ) -> None: """Cancels a pending role eligibility schedule request. - :param scope: The scope of the role eligibility request to cancel. + :param scope: The scope of the role eligibility request to cancel. Required. :type scope: str :param role_eligibility_schedule_request_name: The name of the role eligibility request to - cancel. + cancel. Required. :type role_eligibility_schedule_request_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.cancel.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleEligibilityScheduleRequestName': self._serialize.url("role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_cancel_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + template_url=self.cancel.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -304,4 +417,4 @@ async def cancel( if cls: return cls(pipeline_response, None, {}) - cancel.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}/cancel'} # type: ignore + cancel.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}/cancel"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedules_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedules_operations.py index d97827812dd..7e5f8b8ab1a 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedules_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_eligibility_schedules_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,155 +6,176 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_eligibility_schedules_operations import build_get_request, build_list_for_scope_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleEligibilitySchedulesOperations: - """RoleEligibilitySchedulesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleEligibilitySchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedules` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace_async async def get( - self, - scope: str, - role_eligibility_schedule_name: str, - **kwargs: Any - ) -> "_models.RoleEligibilitySchedule": + self, scope: str, role_eligibility_schedule_name: str, **kwargs: Any + ) -> _models.RoleEligibilitySchedule: """Get the specified role eligibility schedule for a resource scope. - :param scope: The scope of the role eligibility schedule. + :param scope: The scope of the role eligibility schedule. Required. :type scope: str :param role_eligibility_schedule_name: The name (guid) of the role eligibility schedule to get. + Required. :type role_eligibility_schedule_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleEligibilitySchedule, or the result of cls(response) + :return: RoleEligibilitySchedule or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilitySchedule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilitySchedule"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleEligibilityScheduleName': self._serialize.url("role_eligibility_schedule_name", role_eligibility_schedule_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilitySchedule] + + request = build_get_request( + scope=scope, + role_eligibility_schedule_name=role_eligibility_schedule_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleEligibilitySchedule', pipeline_response) + deserialized = self._deserialize("RoleEligibilitySchedule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules/{roleEligibilityScheduleName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules/{roleEligibilityScheduleName}"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleEligibilityScheduleListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleEligibilitySchedule"]: """Gets role eligibility schedules for a resource scope. - :param scope: The scope of the role eligibility schedules. + :param scope: The scope of the role eligibility schedules. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role eligibility schedules at or above the scope. Use $filter=principalId eq {id} to return all role eligibility schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use $filter=asTarget() to return all role eligibility schedules created for the current user. + Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleEligibilityScheduleListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleEligibilitySchedule or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilitySchedule] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleEligibilityScheduleListResult', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -162,7 +184,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -171,7 +195,6 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_management_policies_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_management_policies_operations.py index be9e97db725..0d997f1bc18 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_management_policies_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_management_policies_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,207 +6,300 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_management_policies_operations import ( + build_delete_request, + build_get_request, + build_list_for_scope_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleManagementPoliciesOperations: - """RoleManagementPoliciesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleManagementPoliciesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_management_policies` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get( - self, - scope: str, - role_management_policy_name: str, - **kwargs: Any - ) -> "_models.RoleManagementPolicy": + @distributed_trace_async + async def get(self, scope: str, role_management_policy_name: str, **kwargs: Any) -> _models.RoleManagementPolicy: """Get the specified role management policy for a resource scope. - :param scope: The scope of the role management policy. + :param scope: The scope of the role management policy. Required. :type scope: str :param role_management_policy_name: The name (guid) of the role management policy to get. + Required. :type role_management_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleManagementPolicy, or the result of cls(response) + :return: RoleManagementPolicy or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyName': self._serialize.url("role_management_policy_name", role_management_policy_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicy] + + request = build_get_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleManagementPolicy', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore + + @overload async def update( self, scope: str, role_management_policy_name: str, - parameters: "_models.RoleManagementPolicy", + parameters: _models.RoleManagementPolicy, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleManagementPolicy": + ) -> _models.RoleManagementPolicy: """Update a role management policy. - :param scope: The scope of the role management policy to upsert. + :param scope: The scope of the role management policy to upsert. Required. :type scope: str :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. :type role_management_policy_name: str - :param parameters: Parameters for the role management policy. + :param parameters: Parameters for the role management policy. Required. :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + scope: str, + role_management_policy_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicy: + """Update a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :param parameters: Parameters for the role management policy. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleManagementPolicy, or the result of cls(response) + :return: RoleManagementPolicy or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + scope: str, + role_management_policy_name: str, + parameters: Union[_models.RoleManagementPolicy, IO], + **kwargs: Any + ) -> _models.RoleManagementPolicy: + """Update a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :param parameters: Parameters for the role management policy. Is either a model type or a IO + type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyName': self._serialize.url("role_management_policy_name", role_management_policy_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleManagementPolicy') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicy] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleManagementPolicy") + + request = build_update_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleManagementPolicy', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}'} # type: ignore - async def delete( - self, - scope: str, - role_management_policy_name: str, - **kwargs: Any + update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, role_management_policy_name: str, **kwargs: Any ) -> None: """Delete a role management policy. - :param scope: The scope of the role management policy to upsert. + :param scope: The scope of the role management policy to upsert. Required. :type scope: str :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. :type role_management_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyName': self._serialize.url("role_management_policy_name", role_management_policy_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_delete_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -215,55 +309,61 @@ async def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore - def list_for_scope( - self, - scope: str, - **kwargs: Any - ) -> AsyncIterable["_models.RoleManagementPolicyListResult"]: + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.RoleManagementPolicy"]: """Gets role management policies for a resource scope. - :param scope: The scope of the role management policy. + :param scope: The scope of the role management policy. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleManagementPolicyListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleManagementPolicy or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicyListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleManagementPolicyListResult', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicyListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -272,7 +372,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -281,7 +383,6 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicies'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_management_policy_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_management_policy_assignments_operations.py index c43bf1591ab..63422414540 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_management_policy_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/aio/operations/_role_management_policy_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,210 +6,303 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_management_policy_assignments_operations import ( + build_create_request, + build_delete_request, + build_get_request, + build_list_for_scope_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleManagementPolicyAssignmentsOperations: - """RoleManagementPolicyAssignmentsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleManagementPolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_management_policy_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace_async async def get( - self, - scope: str, - role_management_policy_assignment_name: str, - **kwargs: Any - ) -> "_models.RoleManagementPolicyAssignment": + self, scope: str, role_management_policy_assignment_name: str, **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: """Get the specified role management policy assignment for a resource scope. - :param scope: The scope of the role management policy. + :param scope: The scope of the role management policy. Required. :type scope: str :param role_management_policy_assignment_name: The name of format {guid_guid} the role - management policy assignment to get. + management policy assignment to get. Required. :type role_management_policy_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleManagementPolicyAssignment, or the result of cls(response) + :return: RoleManagementPolicyAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicyAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyAssignmentName': self._serialize.url("role_management_policy_assignment_name", role_management_policy_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignment] + + request = build_get_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleManagementPolicyAssignment', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicyAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore + + @overload + async def create( + self, + scope: str, + role_management_policy_assignment_name: str, + parameters: _models.RoleManagementPolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Create a role management policy assignment. + + :param scope: The scope of the role management policy assignment to upsert. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to upsert. Required. + :type role_management_policy_assignment_name: str + :param parameters: Parameters for the role management policy assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload async def create( self, scope: str, role_management_policy_assignment_name: str, - parameters: "_models.RoleManagementPolicyAssignment", + parameters: IO, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleManagementPolicyAssignment": + ) -> _models.RoleManagementPolicyAssignment: """Create a role management policy assignment. - :param scope: The scope of the role management policy assignment to upsert. + :param scope: The scope of the role management policy assignment to upsert. Required. :type scope: str :param role_management_policy_assignment_name: The name of format {guid_guid} the role - management policy assignment to upsert. + management policy assignment to upsert. Required. :type role_management_policy_assignment_name: str - :param parameters: Parameters for the role management policy assignment. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment + :param parameters: Parameters for the role management policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleManagementPolicyAssignment, or the result of cls(response) + :return: RoleManagementPolicyAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_management_policy_assignment_name: str, + parameters: Union[_models.RoleManagementPolicyAssignment, IO], + **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Create a role management policy assignment. + + :param scope: The scope of the role management policy assignment to upsert. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to upsert. Required. + :type role_management_policy_assignment_name: str + :param parameters: Parameters for the role management policy assignment. Is either a model type + or a IO type. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicyAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyAssignmentName': self._serialize.url("role_management_policy_assignment_name", role_management_policy_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleManagementPolicyAssignment') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleManagementPolicyAssignment") + + request = build_create_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleManagementPolicyAssignment', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicyAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}'} # type: ignore - async def delete( - self, - scope: str, - role_management_policy_assignment_name: str, - **kwargs: Any + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, role_management_policy_assignment_name: str, **kwargs: Any ) -> None: """Delete a role management policy assignment. - :param scope: The scope of the role management policy assignment to delete. + :param scope: The scope of the role management policy assignment to delete. Required. :type scope: str :param role_management_policy_assignment_name: The name of format {guid_guid} the role - management policy assignment to delete. + management policy assignment to delete. Required. :type role_management_policy_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyAssignmentName': self._serialize.url("role_management_policy_assignment_name", role_management_policy_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_delete_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -218,55 +312,61 @@ async def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore - def list_for_scope( - self, - scope: str, - **kwargs: Any - ) -> AsyncIterable["_models.RoleManagementPolicyAssignmentListResult"]: + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.RoleManagementPolicyAssignment"]: """Gets role management assignment policies for a resource scope. - :param scope: The scope of the role management policy. + :param scope: The scope of the role management policy. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleManagementPolicyAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleManagementPolicyAssignment or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicyAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleManagementPolicyAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicyAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -275,7 +375,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -284,7 +386,6 @@ async def get_next(next_link=None): return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/__init__.py index 7455c3e0a86..e8c2129fdb2 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/__init__.py @@ -6,223 +6,162 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ApprovalSettings - from ._models_py3 import ApprovalStage - from ._models_py3 import CloudErrorBody - from ._models_py3 import EligibleChildResource - from ._models_py3 import EligibleChildResourcesListResult - from ._models_py3 import ErrorAdditionalInfo - from ._models_py3 import ErrorDetail - from ._models_py3 import ErrorResponse - from ._models_py3 import ExpandedProperties - from ._models_py3 import ExpandedPropertiesPrincipal - from ._models_py3 import ExpandedPropertiesRoleDefinition - from ._models_py3 import ExpandedPropertiesScope - from ._models_py3 import Permission - from ._models_py3 import PolicyAssignmentProperties - from ._models_py3 import PolicyAssignmentPropertiesPolicy - from ._models_py3 import PolicyAssignmentPropertiesRoleDefinition - from ._models_py3 import PolicyAssignmentPropertiesScope - from ._models_py3 import PolicyProperties - from ._models_py3 import PolicyPropertiesScope - from ._models_py3 import Principal - from ._models_py3 import RoleAssignment - from ._models_py3 import RoleAssignmentCreateParameters - from ._models_py3 import RoleAssignmentFilter - from ._models_py3 import RoleAssignmentListResult - from ._models_py3 import RoleAssignmentSchedule - from ._models_py3 import RoleAssignmentScheduleFilter - from ._models_py3 import RoleAssignmentScheduleInstance - from ._models_py3 import RoleAssignmentScheduleInstanceFilter - from ._models_py3 import RoleAssignmentScheduleInstanceListResult - from ._models_py3 import RoleAssignmentScheduleListResult - from ._models_py3 import RoleAssignmentScheduleRequest - from ._models_py3 import RoleAssignmentScheduleRequestFilter - from ._models_py3 import RoleAssignmentScheduleRequestListResult - from ._models_py3 import RoleAssignmentScheduleRequestPropertiesScheduleInfo - from ._models_py3 import RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration - from ._models_py3 import RoleAssignmentScheduleRequestPropertiesTicketInfo - from ._models_py3 import RoleEligibilitySchedule - from ._models_py3 import RoleEligibilityScheduleFilter - from ._models_py3 import RoleEligibilityScheduleInstance - from ._models_py3 import RoleEligibilityScheduleInstanceFilter - from ._models_py3 import RoleEligibilityScheduleInstanceListResult - from ._models_py3 import RoleEligibilityScheduleListResult - from ._models_py3 import RoleEligibilityScheduleRequest - from ._models_py3 import RoleEligibilityScheduleRequestFilter - from ._models_py3 import RoleEligibilityScheduleRequestListResult - from ._models_py3 import RoleEligibilityScheduleRequestPropertiesScheduleInfo - from ._models_py3 import RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration - from ._models_py3 import RoleEligibilityScheduleRequestPropertiesTicketInfo - from ._models_py3 import RoleManagementPolicy - from ._models_py3 import RoleManagementPolicyApprovalRule - from ._models_py3 import RoleManagementPolicyAssignment - from ._models_py3 import RoleManagementPolicyAssignmentListResult - from ._models_py3 import RoleManagementPolicyAuthenticationContextRule - from ._models_py3 import RoleManagementPolicyEnablementRule - from ._models_py3 import RoleManagementPolicyExpirationRule - from ._models_py3 import RoleManagementPolicyListResult - from ._models_py3 import RoleManagementPolicyNotificationRule - from ._models_py3 import RoleManagementPolicyRule - from ._models_py3 import RoleManagementPolicyRuleTarget - from ._models_py3 import UserSet - from ._models_py3 import ValidationResponse - from ._models_py3 import ValidationResponseErrorInfo -except (SyntaxError, ImportError): - from ._models import ApprovalSettings # type: ignore - from ._models import ApprovalStage # type: ignore - from ._models import CloudErrorBody # type: ignore - from ._models import EligibleChildResource # type: ignore - from ._models import EligibleChildResourcesListResult # type: ignore - from ._models import ErrorAdditionalInfo # type: ignore - from ._models import ErrorDetail # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import ExpandedProperties # type: ignore - from ._models import ExpandedPropertiesPrincipal # type: ignore - from ._models import ExpandedPropertiesRoleDefinition # type: ignore - from ._models import ExpandedPropertiesScope # type: ignore - from ._models import Permission # type: ignore - from ._models import PolicyAssignmentProperties # type: ignore - from ._models import PolicyAssignmentPropertiesPolicy # type: ignore - from ._models import PolicyAssignmentPropertiesRoleDefinition # type: ignore - from ._models import PolicyAssignmentPropertiesScope # type: ignore - from ._models import PolicyProperties # type: ignore - from ._models import PolicyPropertiesScope # type: ignore - from ._models import Principal # type: ignore - from ._models import RoleAssignment # type: ignore - from ._models import RoleAssignmentCreateParameters # type: ignore - from ._models import RoleAssignmentFilter # type: ignore - from ._models import RoleAssignmentListResult # type: ignore - from ._models import RoleAssignmentSchedule # type: ignore - from ._models import RoleAssignmentScheduleFilter # type: ignore - from ._models import RoleAssignmentScheduleInstance # type: ignore - from ._models import RoleAssignmentScheduleInstanceFilter # type: ignore - from ._models import RoleAssignmentScheduleInstanceListResult # type: ignore - from ._models import RoleAssignmentScheduleListResult # type: ignore - from ._models import RoleAssignmentScheduleRequest # type: ignore - from ._models import RoleAssignmentScheduleRequestFilter # type: ignore - from ._models import RoleAssignmentScheduleRequestListResult # type: ignore - from ._models import RoleAssignmentScheduleRequestPropertiesScheduleInfo # type: ignore - from ._models import RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration # type: ignore - from ._models import RoleAssignmentScheduleRequestPropertiesTicketInfo # type: ignore - from ._models import RoleEligibilitySchedule # type: ignore - from ._models import RoleEligibilityScheduleFilter # type: ignore - from ._models import RoleEligibilityScheduleInstance # type: ignore - from ._models import RoleEligibilityScheduleInstanceFilter # type: ignore - from ._models import RoleEligibilityScheduleInstanceListResult # type: ignore - from ._models import RoleEligibilityScheduleListResult # type: ignore - from ._models import RoleEligibilityScheduleRequest # type: ignore - from ._models import RoleEligibilityScheduleRequestFilter # type: ignore - from ._models import RoleEligibilityScheduleRequestListResult # type: ignore - from ._models import RoleEligibilityScheduleRequestPropertiesScheduleInfo # type: ignore - from ._models import RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration # type: ignore - from ._models import RoleEligibilityScheduleRequestPropertiesTicketInfo # type: ignore - from ._models import RoleManagementPolicy # type: ignore - from ._models import RoleManagementPolicyApprovalRule # type: ignore - from ._models import RoleManagementPolicyAssignment # type: ignore - from ._models import RoleManagementPolicyAssignmentListResult # type: ignore - from ._models import RoleManagementPolicyAuthenticationContextRule # type: ignore - from ._models import RoleManagementPolicyEnablementRule # type: ignore - from ._models import RoleManagementPolicyExpirationRule # type: ignore - from ._models import RoleManagementPolicyListResult # type: ignore - from ._models import RoleManagementPolicyNotificationRule # type: ignore - from ._models import RoleManagementPolicyRule # type: ignore - from ._models import RoleManagementPolicyRuleTarget # type: ignore - from ._models import UserSet # type: ignore - from ._models import ValidationResponse # type: ignore - from ._models import ValidationResponseErrorInfo # type: ignore +from ._models_py3 import ApprovalSettings +from ._models_py3 import ApprovalStage +from ._models_py3 import CloudErrorBody +from ._models_py3 import EligibleChildResource +from ._models_py3 import EligibleChildResourcesListResult +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import ExpandedProperties +from ._models_py3 import ExpandedPropertiesPrincipal +from ._models_py3 import ExpandedPropertiesRoleDefinition +from ._models_py3 import ExpandedPropertiesScope +from ._models_py3 import Permission +from ._models_py3 import PolicyAssignmentProperties +from ._models_py3 import PolicyAssignmentPropertiesPolicy +from ._models_py3 import PolicyAssignmentPropertiesRoleDefinition +from ._models_py3 import PolicyAssignmentPropertiesScope +from ._models_py3 import PolicyProperties +from ._models_py3 import PolicyPropertiesScope +from ._models_py3 import Principal +from ._models_py3 import RoleAssignment +from ._models_py3 import RoleAssignmentCreateParameters +from ._models_py3 import RoleAssignmentFilter +from ._models_py3 import RoleAssignmentListResult +from ._models_py3 import RoleAssignmentSchedule +from ._models_py3 import RoleAssignmentScheduleFilter +from ._models_py3 import RoleAssignmentScheduleInstance +from ._models_py3 import RoleAssignmentScheduleInstanceFilter +from ._models_py3 import RoleAssignmentScheduleInstanceListResult +from ._models_py3 import RoleAssignmentScheduleListResult +from ._models_py3 import RoleAssignmentScheduleRequest +from ._models_py3 import RoleAssignmentScheduleRequestFilter +from ._models_py3 import RoleAssignmentScheduleRequestListResult +from ._models_py3 import RoleAssignmentScheduleRequestPropertiesScheduleInfo +from ._models_py3 import RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration +from ._models_py3 import RoleAssignmentScheduleRequestPropertiesTicketInfo +from ._models_py3 import RoleEligibilitySchedule +from ._models_py3 import RoleEligibilityScheduleFilter +from ._models_py3 import RoleEligibilityScheduleInstance +from ._models_py3 import RoleEligibilityScheduleInstanceFilter +from ._models_py3 import RoleEligibilityScheduleInstanceListResult +from ._models_py3 import RoleEligibilityScheduleListResult +from ._models_py3 import RoleEligibilityScheduleRequest +from ._models_py3 import RoleEligibilityScheduleRequestFilter +from ._models_py3 import RoleEligibilityScheduleRequestListResult +from ._models_py3 import RoleEligibilityScheduleRequestPropertiesScheduleInfo +from ._models_py3 import RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration +from ._models_py3 import RoleEligibilityScheduleRequestPropertiesTicketInfo +from ._models_py3 import RoleManagementPolicy +from ._models_py3 import RoleManagementPolicyApprovalRule +from ._models_py3 import RoleManagementPolicyAssignment +from ._models_py3 import RoleManagementPolicyAssignmentListResult +from ._models_py3 import RoleManagementPolicyAuthenticationContextRule +from ._models_py3 import RoleManagementPolicyEnablementRule +from ._models_py3 import RoleManagementPolicyExpirationRule +from ._models_py3 import RoleManagementPolicyListResult +from ._models_py3 import RoleManagementPolicyNotificationRule +from ._models_py3 import RoleManagementPolicyRule +from ._models_py3 import RoleManagementPolicyRuleTarget +from ._models_py3 import UserSet +from ._models_py3 import ValidationResponse +from ._models_py3 import ValidationResponseErrorInfo -from ._authorization_management_client_enums import ( - ApprovalMode, - AssignmentType, - EnablementRules, - MemberType, - NotificationDeliveryMechanism, - NotificationLevel, - PrincipalType, - RecipientType, - RequestType, - RoleManagementPolicyRuleType, - Status, - Type, - UserType, -) +from ._authorization_management_client_enums import ApprovalMode +from ._authorization_management_client_enums import AssignmentType +from ._authorization_management_client_enums import EnablementRules +from ._authorization_management_client_enums import MemberType +from ._authorization_management_client_enums import NotificationDeliveryMechanism +from ._authorization_management_client_enums import NotificationLevel +from ._authorization_management_client_enums import PrincipalType +from ._authorization_management_client_enums import RecipientType +from ._authorization_management_client_enums import RequestType +from ._authorization_management_client_enums import RoleManagementPolicyRuleType +from ._authorization_management_client_enums import Status +from ._authorization_management_client_enums import Type +from ._authorization_management_client_enums import UserType +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ApprovalSettings', - 'ApprovalStage', - 'CloudErrorBody', - 'EligibleChildResource', - 'EligibleChildResourcesListResult', - 'ErrorAdditionalInfo', - 'ErrorDetail', - 'ErrorResponse', - 'ExpandedProperties', - 'ExpandedPropertiesPrincipal', - 'ExpandedPropertiesRoleDefinition', - 'ExpandedPropertiesScope', - 'Permission', - 'PolicyAssignmentProperties', - 'PolicyAssignmentPropertiesPolicy', - 'PolicyAssignmentPropertiesRoleDefinition', - 'PolicyAssignmentPropertiesScope', - 'PolicyProperties', - 'PolicyPropertiesScope', - 'Principal', - 'RoleAssignment', - 'RoleAssignmentCreateParameters', - 'RoleAssignmentFilter', - 'RoleAssignmentListResult', - 'RoleAssignmentSchedule', - 'RoleAssignmentScheduleFilter', - 'RoleAssignmentScheduleInstance', - 'RoleAssignmentScheduleInstanceFilter', - 'RoleAssignmentScheduleInstanceListResult', - 'RoleAssignmentScheduleListResult', - 'RoleAssignmentScheduleRequest', - 'RoleAssignmentScheduleRequestFilter', - 'RoleAssignmentScheduleRequestListResult', - 'RoleAssignmentScheduleRequestPropertiesScheduleInfo', - 'RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration', - 'RoleAssignmentScheduleRequestPropertiesTicketInfo', - 'RoleEligibilitySchedule', - 'RoleEligibilityScheduleFilter', - 'RoleEligibilityScheduleInstance', - 'RoleEligibilityScheduleInstanceFilter', - 'RoleEligibilityScheduleInstanceListResult', - 'RoleEligibilityScheduleListResult', - 'RoleEligibilityScheduleRequest', - 'RoleEligibilityScheduleRequestFilter', - 'RoleEligibilityScheduleRequestListResult', - 'RoleEligibilityScheduleRequestPropertiesScheduleInfo', - 'RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration', - 'RoleEligibilityScheduleRequestPropertiesTicketInfo', - 'RoleManagementPolicy', - 'RoleManagementPolicyApprovalRule', - 'RoleManagementPolicyAssignment', - 'RoleManagementPolicyAssignmentListResult', - 'RoleManagementPolicyAuthenticationContextRule', - 'RoleManagementPolicyEnablementRule', - 'RoleManagementPolicyExpirationRule', - 'RoleManagementPolicyListResult', - 'RoleManagementPolicyNotificationRule', - 'RoleManagementPolicyRule', - 'RoleManagementPolicyRuleTarget', - 'UserSet', - 'ValidationResponse', - 'ValidationResponseErrorInfo', - 'ApprovalMode', - 'AssignmentType', - 'EnablementRules', - 'MemberType', - 'NotificationDeliveryMechanism', - 'NotificationLevel', - 'PrincipalType', - 'RecipientType', - 'RequestType', - 'RoleManagementPolicyRuleType', - 'Status', - 'Type', - 'UserType', + "ApprovalSettings", + "ApprovalStage", + "CloudErrorBody", + "EligibleChildResource", + "EligibleChildResourcesListResult", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "ExpandedProperties", + "ExpandedPropertiesPrincipal", + "ExpandedPropertiesRoleDefinition", + "ExpandedPropertiesScope", + "Permission", + "PolicyAssignmentProperties", + "PolicyAssignmentPropertiesPolicy", + "PolicyAssignmentPropertiesRoleDefinition", + "PolicyAssignmentPropertiesScope", + "PolicyProperties", + "PolicyPropertiesScope", + "Principal", + "RoleAssignment", + "RoleAssignmentCreateParameters", + "RoleAssignmentFilter", + "RoleAssignmentListResult", + "RoleAssignmentSchedule", + "RoleAssignmentScheduleFilter", + "RoleAssignmentScheduleInstance", + "RoleAssignmentScheduleInstanceFilter", + "RoleAssignmentScheduleInstanceListResult", + "RoleAssignmentScheduleListResult", + "RoleAssignmentScheduleRequest", + "RoleAssignmentScheduleRequestFilter", + "RoleAssignmentScheduleRequestListResult", + "RoleAssignmentScheduleRequestPropertiesScheduleInfo", + "RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration", + "RoleAssignmentScheduleRequestPropertiesTicketInfo", + "RoleEligibilitySchedule", + "RoleEligibilityScheduleFilter", + "RoleEligibilityScheduleInstance", + "RoleEligibilityScheduleInstanceFilter", + "RoleEligibilityScheduleInstanceListResult", + "RoleEligibilityScheduleListResult", + "RoleEligibilityScheduleRequest", + "RoleEligibilityScheduleRequestFilter", + "RoleEligibilityScheduleRequestListResult", + "RoleEligibilityScheduleRequestPropertiesScheduleInfo", + "RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration", + "RoleEligibilityScheduleRequestPropertiesTicketInfo", + "RoleManagementPolicy", + "RoleManagementPolicyApprovalRule", + "RoleManagementPolicyAssignment", + "RoleManagementPolicyAssignmentListResult", + "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", + "RoleManagementPolicyExpirationRule", + "RoleManagementPolicyListResult", + "RoleManagementPolicyNotificationRule", + "RoleManagementPolicyRule", + "RoleManagementPolicyRuleTarget", + "UserSet", + "ValidationResponse", + "ValidationResponseErrorInfo", + "ApprovalMode", + "AssignmentType", + "EnablementRules", + "MemberType", + "NotificationDeliveryMechanism", + "NotificationLevel", + "PrincipalType", + "RecipientType", + "RequestType", + "RoleManagementPolicyRuleType", + "Status", + "Type", + "UserType", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_authorization_management_client_enums.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_authorization_management_client_enums.py index d6415a11e6d..511d0e7675c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_authorization_management_client_enums.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_authorization_management_client_enums.py @@ -6,75 +6,58 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass - -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class ApprovalMode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of rule - """ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ApprovalMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of rule.""" SINGLE_STAGE = "SingleStage" SERIAL = "Serial" PARALLEL = "Parallel" NO_APPROVAL = "NoApproval" -class AssignmentType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Assignment type of the role assignment schedule - """ + +class AssignmentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Assignment type of the role assignment schedule.""" ACTIVATED = "Activated" ASSIGNED = "Assigned" -class EnablementRules(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of enable rules - """ + +class EnablementRules(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of enable rules.""" MULTI_FACTOR_AUTHENTICATION = "MultiFactorAuthentication" JUSTIFICATION = "Justification" TICKETING = "Ticketing" -class MemberType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Membership type of the role assignment schedule - """ + +class MemberType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Membership type of the role assignment schedule.""" INHERITED = "Inherited" DIRECT = "Direct" GROUP = "Group" -class NotificationDeliveryMechanism(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of notification. - """ + +class NotificationDeliveryMechanism(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of notification.""" EMAIL = "Email" -class NotificationLevel(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The notification level. - """ + +class NotificationLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The notification level.""" NONE = "None" CRITICAL = "Critical" ALL = "All" -class PrincipalType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The principal type of the assigned principal ID. - """ + +class PrincipalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The principal type of the assigned principal ID.""" USER = "User" GROUP = "Group" @@ -82,17 +65,17 @@ class PrincipalType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): FOREIGN_GROUP = "ForeignGroup" DEVICE = "Device" -class RecipientType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The recipient type. - """ + +class RecipientType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The recipient type.""" REQUESTOR = "Requestor" APPROVER = "Approver" ADMIN = "Admin" -class RequestType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the role assignment schedule request. Eg: SelfActivate, AdminAssign etc - """ + +class RequestType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the role assignment schedule request. Eg: SelfActivate, AdminAssign etc.""" ADMIN_ASSIGN = "AdminAssign" ADMIN_REMOVE = "AdminRemove" @@ -104,9 +87,9 @@ class RequestType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): SELF_EXTEND = "SelfExtend" SELF_RENEW = "SelfRenew" -class RoleManagementPolicyRuleType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of rule - """ + +class RoleManagementPolicyRuleType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of rule.""" ROLE_MANAGEMENT_POLICY_APPROVAL_RULE = "RoleManagementPolicyApprovalRule" ROLE_MANAGEMENT_POLICY_AUTHENTICATION_CONTEXT_RULE = "RoleManagementPolicyAuthenticationContextRule" @@ -114,9 +97,9 @@ class RoleManagementPolicyRuleType(with_metaclass(_CaseInsensitiveEnumMeta, str, ROLE_MANAGEMENT_POLICY_EXPIRATION_RULE = "RoleManagementPolicyExpirationRule" ROLE_MANAGEMENT_POLICY_NOTIFICATION_RULE = "RoleManagementPolicyNotificationRule" -class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The status of the role assignment schedule. - """ + +class Status(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the role assignment schedule.""" ACCEPTED = "Accepted" PENDING_EVALUATION = "PendingEvaluation" @@ -141,17 +124,17 @@ class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): SCHEDULE_CREATED = "ScheduleCreated" PENDING_EXTERNAL_PROVISIONING = "PendingExternalProvisioning" -class Type(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Type of the role assignment schedule expiration - """ + +class Type(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the role assignment schedule expiration.""" AFTER_DURATION = "AfterDuration" AFTER_DATE_TIME = "AfterDateTime" NO_EXPIRATION = "NoExpiration" -class UserType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of user. - """ + +class UserType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of user.""" USER = "User" GROUP = "Group" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_models.py deleted file mode 100644 index b4ab4b9b7c4..00000000000 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_models.py +++ /dev/null @@ -1,2581 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class ApprovalSettings(msrest.serialization.Model): - """The approval settings. - - :param is_approval_required: Determine whether approval is required or not. - :type is_approval_required: bool - :param is_approval_required_for_extension: Determine whether approval is required for - assignment extension. - :type is_approval_required_for_extension: bool - :param is_requestor_justification_required: Determine whether requestor justification required. - :type is_requestor_justification_required: bool - :param approval_mode: The type of rule. Possible values include: "SingleStage", "Serial", - "Parallel", "NoApproval". - :type approval_mode: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalMode - :param approval_stages: The approval stages of the request. - :type approval_stages: list[~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalStage] - """ - - _attribute_map = { - 'is_approval_required': {'key': 'isApprovalRequired', 'type': 'bool'}, - 'is_approval_required_for_extension': {'key': 'isApprovalRequiredForExtension', 'type': 'bool'}, - 'is_requestor_justification_required': {'key': 'isRequestorJustificationRequired', 'type': 'bool'}, - 'approval_mode': {'key': 'approvalMode', 'type': 'str'}, - 'approval_stages': {'key': 'approvalStages', 'type': '[ApprovalStage]'}, - } - - def __init__( - self, - **kwargs - ): - super(ApprovalSettings, self).__init__(**kwargs) - self.is_approval_required = kwargs.get('is_approval_required', None) - self.is_approval_required_for_extension = kwargs.get('is_approval_required_for_extension', None) - self.is_requestor_justification_required = kwargs.get('is_requestor_justification_required', None) - self.approval_mode = kwargs.get('approval_mode', None) - self.approval_stages = kwargs.get('approval_stages', None) - - -class ApprovalStage(msrest.serialization.Model): - """The approval stage. - - :param approval_stage_time_out_in_days: The time in days when approval request would be timed - out. - :type approval_stage_time_out_in_days: int - :param is_approver_justification_required: Determine whether approver need to provide - justification for his decision. - :type is_approver_justification_required: bool - :param escalation_time_in_minutes: The time in minutes when the approval request would be - escalated if the primary approver does not approves. - :type escalation_time_in_minutes: int - :param primary_approvers: The primary approver of the request. - :type primary_approvers: list[~azure.mgmt.authorization.v2020_10_01_preview.models.UserSet] - :param is_escalation_enabled: The value determine whether escalation feature is enabled. - :type is_escalation_enabled: bool - :param escalation_approvers: The escalation approver of the request. - :type escalation_approvers: list[~azure.mgmt.authorization.v2020_10_01_preview.models.UserSet] - """ - - _attribute_map = { - 'approval_stage_time_out_in_days': {'key': 'approvalStageTimeOutInDays', 'type': 'int'}, - 'is_approver_justification_required': {'key': 'isApproverJustificationRequired', 'type': 'bool'}, - 'escalation_time_in_minutes': {'key': 'escalationTimeInMinutes', 'type': 'int'}, - 'primary_approvers': {'key': 'primaryApprovers', 'type': '[UserSet]'}, - 'is_escalation_enabled': {'key': 'isEscalationEnabled', 'type': 'bool'}, - 'escalation_approvers': {'key': 'escalationApprovers', 'type': '[UserSet]'}, - } - - def __init__( - self, - **kwargs - ): - super(ApprovalStage, self).__init__(**kwargs) - self.approval_stage_time_out_in_days = kwargs.get('approval_stage_time_out_in_days', None) - self.is_approver_justification_required = kwargs.get('is_approver_justification_required', None) - self.escalation_time_in_minutes = kwargs.get('escalation_time_in_minutes', None) - self.primary_approvers = kwargs.get('primary_approvers', None) - self.is_escalation_enabled = kwargs.get('is_escalation_enabled', None) - self.escalation_approvers = kwargs.get('escalation_approvers', None) - - -class CloudErrorBody(msrest.serialization.Model): - """An error response from the service. - - :param code: An identifier for the error. Codes are invariant and are intended to be consumed - programmatically. - :type code: str - :param message: A message describing the error, intended to be suitable for display in a user - interface. - :type message: str - """ - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CloudErrorBody, self).__init__(**kwargs) - self.code = kwargs.get('code', None) - self.message = kwargs.get('message', None) - - -class EligibleChildResource(msrest.serialization.Model): - """Eligible child resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The resource scope Id. - :vartype id: str - :ivar name: The resource name. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(EligibleChildResource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class EligibleChildResourcesListResult(msrest.serialization.Model): - """Eligible child resources list operation result. - - :param value: Eligible child resource list. - :type value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.EligibleChildResource] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[EligibleChildResource]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(EligibleChildResourcesListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class ErrorAdditionalInfo(msrest.serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: any - """ - - _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(msrest.serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.authorization.v2020_10_01_preview.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: - list[~azure.mgmt.authorization.v2020_10_01_preview.models.ErrorAdditionalInfo] - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(msrest.serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2020_10_01_preview.models.ErrorDetail - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ExpandedProperties(msrest.serialization.Model): - """ExpandedProperties. - - :param scope: Details of the resource scope. - :type scope: ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedPropertiesScope - :param role_definition: Details of role definition. - :type role_definition: - ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedPropertiesRoleDefinition - :param principal: Details of the principal. - :type principal: - ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedPropertiesPrincipal - """ - - _attribute_map = { - 'scope': {'key': 'scope', 'type': 'ExpandedPropertiesScope'}, - 'role_definition': {'key': 'roleDefinition', 'type': 'ExpandedPropertiesRoleDefinition'}, - 'principal': {'key': 'principal', 'type': 'ExpandedPropertiesPrincipal'}, - } - - def __init__( - self, - **kwargs - ): - super(ExpandedProperties, self).__init__(**kwargs) - self.scope = kwargs.get('scope', None) - self.role_definition = kwargs.get('role_definition', None) - self.principal = kwargs.get('principal', None) - - -class ExpandedPropertiesPrincipal(msrest.serialization.Model): - """Details of the principal. - - :param id: Id of the principal. - :type id: str - :param display_name: Display name of the principal. - :type display_name: str - :param email: Email id of the principal. - :type email: str - :param type: Type of the principal. - :type type: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ExpandedPropertiesPrincipal, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.display_name = kwargs.get('display_name', None) - self.email = kwargs.get('email', None) - self.type = kwargs.get('type', None) - - -class ExpandedPropertiesRoleDefinition(msrest.serialization.Model): - """Details of role definition. - - :param id: Id of the role definition. - :type id: str - :param display_name: Display name of the role definition. - :type display_name: str - :param type: Type of the role definition. - :type type: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ExpandedPropertiesRoleDefinition, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.display_name = kwargs.get('display_name', None) - self.type = kwargs.get('type', None) - - -class ExpandedPropertiesScope(msrest.serialization.Model): - """Details of the resource scope. - - :param id: Scope id of the resource. - :type id: str - :param display_name: Display name of the resource. - :type display_name: str - :param type: Type of the resource. - :type type: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ExpandedPropertiesScope, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.display_name = kwargs.get('display_name', None) - self.type = kwargs.get('type', None) - - -class Permission(msrest.serialization.Model): - """Role definition permissions. - - :param actions: Allowed actions. - :type actions: list[str] - :param not_actions: Denied actions. - :type not_actions: list[str] - :param data_actions: Allowed Data actions. - :type data_actions: list[str] - :param not_data_actions: Denied Data actions. - :type not_data_actions: list[str] - """ - - _attribute_map = { - 'actions': {'key': 'actions', 'type': '[str]'}, - 'not_actions': {'key': 'notActions', 'type': '[str]'}, - 'data_actions': {'key': 'dataActions', 'type': '[str]'}, - 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(Permission, self).__init__(**kwargs) - self.actions = kwargs.get('actions', None) - self.not_actions = kwargs.get('not_actions', None) - self.data_actions = kwargs.get('data_actions', None) - self.not_data_actions = kwargs.get('not_data_actions', None) - - -class PolicyAssignmentProperties(msrest.serialization.Model): - """PolicyAssignmentProperties. - - :param scope: Details of the resource scope. - :type scope: - ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyAssignmentPropertiesScope - :param role_definition: Details of role definition. - :type role_definition: - ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyAssignmentPropertiesRoleDefinition - :param policy: Details of the policy. - :type policy: - ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyAssignmentPropertiesPolicy - """ - - _attribute_map = { - 'scope': {'key': 'scope', 'type': 'PolicyAssignmentPropertiesScope'}, - 'role_definition': {'key': 'roleDefinition', 'type': 'PolicyAssignmentPropertiesRoleDefinition'}, - 'policy': {'key': 'policy', 'type': 'PolicyAssignmentPropertiesPolicy'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyAssignmentProperties, self).__init__(**kwargs) - self.scope = kwargs.get('scope', None) - self.role_definition = kwargs.get('role_definition', None) - self.policy = kwargs.get('policy', None) - - -class PolicyAssignmentPropertiesPolicy(msrest.serialization.Model): - """Details of the policy. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param id: Id of the policy. - :type id: str - :ivar last_modified_by: The name of the entity last modified it. - :vartype last_modified_by: ~azure.mgmt.authorization.v2020_10_01_preview.models.Principal - :param last_modified_date_time: The last modified date time. - :type last_modified_date_time: ~datetime.datetime - """ - - _validation = { - 'last_modified_by': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'Principal'}, - 'last_modified_date_time': {'key': 'lastModifiedDateTime', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyAssignmentPropertiesPolicy, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.last_modified_by = None - self.last_modified_date_time = kwargs.get('last_modified_date_time', None) - - -class PolicyAssignmentPropertiesRoleDefinition(msrest.serialization.Model): - """Details of role definition. - - :param id: Id of the role definition. - :type id: str - :param display_name: Display name of the role definition. - :type display_name: str - :param type: Type of the role definition. - :type type: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyAssignmentPropertiesRoleDefinition, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.display_name = kwargs.get('display_name', None) - self.type = kwargs.get('type', None) - - -class PolicyAssignmentPropertiesScope(msrest.serialization.Model): - """Details of the resource scope. - - :param id: Scope id of the resource. - :type id: str - :param display_name: Display name of the resource. - :type display_name: str - :param type: Type of the resource. - :type type: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyAssignmentPropertiesScope, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.display_name = kwargs.get('display_name', None) - self.type = kwargs.get('type', None) - - -class PolicyProperties(msrest.serialization.Model): - """PolicyProperties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar scope: Details of the resource scope. - :vartype scope: ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyPropertiesScope - """ - - _validation = { - 'scope': {'readonly': True}, - } - - _attribute_map = { - 'scope': {'key': 'scope', 'type': 'PolicyPropertiesScope'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyProperties, self).__init__(**kwargs) - self.scope = None - - -class PolicyPropertiesScope(msrest.serialization.Model): - """Details of the resource scope. - - :param id: Scope id of the resource. - :type id: str - :param display_name: Display name of the resource. - :type display_name: str - :param type: Type of the resource. - :type type: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyPropertiesScope, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.display_name = kwargs.get('display_name', None) - self.type = kwargs.get('type', None) - - -class Principal(msrest.serialization.Model): - """The name of the entity last modified it. - - :param id: The id of the principal made changes. - :type id: str - :param display_name: The name of the principal made changes. - :type display_name: str - :param type: Type of principal such as user , group etc. - :type type: str - :param email: Email of principal. - :type email: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Principal, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.display_name = kwargs.get('display_name', None) - self.type = kwargs.get('type', None) - self.email = kwargs.get('email', None) - - -class RoleAssignment(msrest.serialization.Model): - """Role Assignments. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role assignment ID. - :vartype id: str - :ivar name: The role assignment name. - :vartype name: str - :ivar type: The role assignment type. - :vartype type: str - :ivar scope: The role assignment scope. - :vartype scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param description: Description of role assignment. - :type description: str - :param condition: The conditions on the role assignment. This limits the resources it can be - assigned to. e.g.: - @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] - StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :ivar created_on: Time it was created. - :vartype created_on: ~datetime.datetime - :ivar updated_on: Time it was updated. - :vartype updated_on: ~datetime.datetime - :ivar created_by: Id of the user who created the assignment. - :vartype created_by: str - :ivar updated_by: Id of the user who updated the assignment. - :vartype updated_by: str - :param delegated_managed_identity_resource_id: Id of the delegated managed identity resource. - :type delegated_managed_identity_resource_id: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'scope': {'readonly': True}, - 'created_on': {'readonly': True}, - 'updated_on': {'readonly': True}, - 'created_by': {'readonly': True}, - 'updated_by': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'updated_on': {'key': 'properties.updatedOn', 'type': 'iso-8601'}, - 'created_by': {'key': 'properties.createdBy', 'type': 'str'}, - 'updated_by': {'key': 'properties.updatedBy', 'type': 'str'}, - 'delegated_managed_identity_resource_id': {'key': 'properties.delegatedManagedIdentityResourceId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignment, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = None - self.role_definition_id = kwargs.get('role_definition_id', None) - self.principal_id = kwargs.get('principal_id', None) - self.principal_type = kwargs.get('principal_type', None) - self.description = kwargs.get('description', None) - self.condition = kwargs.get('condition', None) - self.condition_version = kwargs.get('condition_version', None) - self.created_on = None - self.updated_on = None - self.created_by = None - self.updated_by = None - self.delegated_managed_identity_resource_id = kwargs.get('delegated_managed_identity_resource_id', None) - - -class RoleAssignmentCreateParameters(msrest.serialization.Model): - """Role assignment create parameters. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar scope: The role assignment scope. - :vartype scope: str - :param role_definition_id: Required. The role definition ID. - :type role_definition_id: str - :param principal_id: Required. The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param description: Description of role assignment. - :type description: str - :param condition: The conditions on the role assignment. This limits the resources it can be - assigned to. e.g.: - @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] - StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :ivar created_on: Time it was created. - :vartype created_on: ~datetime.datetime - :ivar updated_on: Time it was updated. - :vartype updated_on: ~datetime.datetime - :ivar created_by: Id of the user who created the assignment. - :vartype created_by: str - :ivar updated_by: Id of the user who updated the assignment. - :vartype updated_by: str - :param delegated_managed_identity_resource_id: Id of the delegated managed identity resource. - :type delegated_managed_identity_resource_id: str - """ - - _validation = { - 'scope': {'readonly': True}, - 'role_definition_id': {'required': True}, - 'principal_id': {'required': True}, - 'created_on': {'readonly': True}, - 'updated_on': {'readonly': True}, - 'created_by': {'readonly': True}, - 'updated_by': {'readonly': True}, - } - - _attribute_map = { - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'updated_on': {'key': 'properties.updatedOn', 'type': 'iso-8601'}, - 'created_by': {'key': 'properties.createdBy', 'type': 'str'}, - 'updated_by': {'key': 'properties.updatedBy', 'type': 'str'}, - 'delegated_managed_identity_resource_id': {'key': 'properties.delegatedManagedIdentityResourceId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentCreateParameters, self).__init__(**kwargs) - self.scope = None - self.role_definition_id = kwargs['role_definition_id'] - self.principal_id = kwargs['principal_id'] - self.principal_type = kwargs.get('principal_type', None) - self.description = kwargs.get('description', None) - self.condition = kwargs.get('condition', None) - self.condition_version = kwargs.get('condition_version', None) - self.created_on = None - self.updated_on = None - self.created_by = None - self.updated_by = None - self.delegated_managed_identity_resource_id = kwargs.get('delegated_managed_identity_resource_id', None) - - -class RoleAssignmentFilter(msrest.serialization.Model): - """Role Assignments filter. - - :param principal_id: Returns role assignment of the specific principal. - :type principal_id: str - """ - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentFilter, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - - -class RoleAssignmentListResult(msrest.serialization.Model): - """Role assignment list operation result. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param value: Role assignment list. - :type value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _validation = { - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = None - - -class RoleAssignmentSchedule(msrest.serialization.Model): - """Role Assignment schedule. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role assignment schedule Id. - :vartype id: str - :ivar name: The role assignment schedule name. - :vartype name: str - :ivar type: The role assignment schedule type. - :vartype type: str - :param scope: The role assignment schedule scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param role_assignment_schedule_request_id: The id of roleAssignmentScheduleRequest used to - create this roleAssignmentSchedule. - :type role_assignment_schedule_request_id: str - :param linked_role_eligibility_schedule_id: The id of roleEligibilitySchedule used to activated - this roleAssignmentSchedule. - :type linked_role_eligibility_schedule_id: str - :param assignment_type: Assignment type of the role assignment schedule. Possible values - include: "Activated", "Assigned". - :type assignment_type: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.AssignmentType - :param member_type: Membership type of the role assignment schedule. Possible values include: - "Inherited", "Direct", "Group". - :type member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType - :param status: The status of the role assignment schedule. Possible values include: "Accepted", - "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", - "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", - "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", - "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". - :type status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status - :param start_date_time: Start DateTime when role assignment schedule. - :type start_date_time: ~datetime.datetime - :param end_date_time: End DateTime when role assignment schedule. - :type end_date_time: ~datetime.datetime - :param condition: The conditions on the role assignment. This limits the resources it can be - assigned to. e.g.: - @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] - StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param created_on: DateTime when role assignment schedule was created. - :type created_on: ~datetime.datetime - :param updated_on: DateTime when role assignment schedule was modified. - :type updated_on: ~datetime.datetime - :param expanded_properties: Additional properties of principal, scope and role definition. - :type expanded_properties: - ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'role_assignment_schedule_request_id': {'key': 'properties.roleAssignmentScheduleRequestId', 'type': 'str'}, - 'linked_role_eligibility_schedule_id': {'key': 'properties.linkedRoleEligibilityScheduleId', 'type': 'str'}, - 'assignment_type': {'key': 'properties.assignmentType', 'type': 'str'}, - 'member_type': {'key': 'properties.memberType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'updated_on': {'key': 'properties.updatedOn', 'type': 'iso-8601'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentSchedule, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = kwargs.get('scope', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.principal_id = kwargs.get('principal_id', None) - self.principal_type = kwargs.get('principal_type', None) - self.role_assignment_schedule_request_id = kwargs.get('role_assignment_schedule_request_id', None) - self.linked_role_eligibility_schedule_id = kwargs.get('linked_role_eligibility_schedule_id', None) - self.assignment_type = kwargs.get('assignment_type', None) - self.member_type = kwargs.get('member_type', None) - self.status = kwargs.get('status', None) - self.start_date_time = kwargs.get('start_date_time', None) - self.end_date_time = kwargs.get('end_date_time', None) - self.condition = kwargs.get('condition', None) - self.condition_version = kwargs.get('condition_version', None) - self.created_on = kwargs.get('created_on', None) - self.updated_on = kwargs.get('updated_on', None) - self.expanded_properties = kwargs.get('expanded_properties', None) - - -class RoleAssignmentScheduleFilter(msrest.serialization.Model): - """Role assignment schedule filter. - - :param principal_id: Returns role assignment schedule of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role assignment schedule of the specific role definition. - :type role_definition_id: str - :param status: Returns role assignment schedule instances of the specific status. - :type status: str - """ - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentScheduleFilter, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.status = kwargs.get('status', None) - - -class RoleAssignmentScheduleInstance(msrest.serialization.Model): - """Information about current or upcoming role assignment schedule instance. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role assignment schedule instance ID. - :vartype id: str - :ivar name: The role assignment schedule instance name. - :vartype name: str - :ivar type: The role assignment schedule instance type. - :vartype type: str - :param scope: The role assignment schedule scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param role_assignment_schedule_id: Id of the master role assignment schedule. - :type role_assignment_schedule_id: str - :param origin_role_assignment_id: Role Assignment Id in external system. - :type origin_role_assignment_id: str - :param status: The status of the role assignment schedule instance. Possible values include: - "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", - "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", - "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", - "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". - :type status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status - :param start_date_time: The startDateTime of the role assignment schedule instance. - :type start_date_time: ~datetime.datetime - :param end_date_time: The endDateTime of the role assignment schedule instance. - :type end_date_time: ~datetime.datetime - :param linked_role_eligibility_schedule_id: roleEligibilityScheduleId used to activate. - :type linked_role_eligibility_schedule_id: str - :param linked_role_eligibility_schedule_instance_id: roleEligibilityScheduleInstanceId linked - to this roleAssignmentScheduleInstance. - :type linked_role_eligibility_schedule_instance_id: str - :param assignment_type: Assignment type of the role assignment schedule. Possible values - include: "Activated", "Assigned". - :type assignment_type: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.AssignmentType - :param member_type: Membership type of the role assignment schedule. Possible values include: - "Inherited", "Direct", "Group". - :type member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType - :param condition: The conditions on the role assignment. This limits the resources it can be - assigned to. e.g.: - @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] - StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param created_on: DateTime when role assignment schedule was created. - :type created_on: ~datetime.datetime - :param expanded_properties: Additional properties of principal, scope and role definition. - :type expanded_properties: - ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'role_assignment_schedule_id': {'key': 'properties.roleAssignmentScheduleId', 'type': 'str'}, - 'origin_role_assignment_id': {'key': 'properties.originRoleAssignmentId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, - 'linked_role_eligibility_schedule_id': {'key': 'properties.linkedRoleEligibilityScheduleId', 'type': 'str'}, - 'linked_role_eligibility_schedule_instance_id': {'key': 'properties.linkedRoleEligibilityScheduleInstanceId', 'type': 'str'}, - 'assignment_type': {'key': 'properties.assignmentType', 'type': 'str'}, - 'member_type': {'key': 'properties.memberType', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentScheduleInstance, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = kwargs.get('scope', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.principal_id = kwargs.get('principal_id', None) - self.principal_type = kwargs.get('principal_type', None) - self.role_assignment_schedule_id = kwargs.get('role_assignment_schedule_id', None) - self.origin_role_assignment_id = kwargs.get('origin_role_assignment_id', None) - self.status = kwargs.get('status', None) - self.start_date_time = kwargs.get('start_date_time', None) - self.end_date_time = kwargs.get('end_date_time', None) - self.linked_role_eligibility_schedule_id = kwargs.get('linked_role_eligibility_schedule_id', None) - self.linked_role_eligibility_schedule_instance_id = kwargs.get('linked_role_eligibility_schedule_instance_id', None) - self.assignment_type = kwargs.get('assignment_type', None) - self.member_type = kwargs.get('member_type', None) - self.condition = kwargs.get('condition', None) - self.condition_version = kwargs.get('condition_version', None) - self.created_on = kwargs.get('created_on', None) - self.expanded_properties = kwargs.get('expanded_properties', None) - - -class RoleAssignmentScheduleInstanceFilter(msrest.serialization.Model): - """Role assignment schedule instance filter. - - :param principal_id: Returns role assignment schedule instances of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role assignment schedule instances of the specific role - definition. - :type role_definition_id: str - :param status: Returns role assignment schedule instances of the specific status. - :type status: str - :param role_assignment_schedule_id: Returns role assignment schedule instances belonging to a - specific role assignment schedule. - :type role_assignment_schedule_id: str - """ - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'role_assignment_schedule_id': {'key': 'roleAssignmentScheduleId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentScheduleInstanceFilter, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.status = kwargs.get('status', None) - self.role_assignment_schedule_id = kwargs.get('role_assignment_schedule_id', None) - - -class RoleAssignmentScheduleInstanceListResult(msrest.serialization.Model): - """Role assignment schedule instance list operation result. - - :param value: Role assignment schedule instance list. - :type value: - list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleInstance] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignmentScheduleInstance]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentScheduleInstanceListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RoleAssignmentScheduleListResult(msrest.serialization.Model): - """Role assignment schedule list operation result. - - :param value: Role assignment schedule list. - :type value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentSchedule] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignmentSchedule]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentScheduleListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RoleAssignmentScheduleRequest(msrest.serialization.Model): - """Role Assignment schedule request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role assignment schedule request ID. - :vartype id: str - :ivar name: The role assignment schedule request name. - :vartype name: str - :ivar type: The role assignment schedule request type. - :vartype type: str - :ivar scope: The role assignment schedule request scope. - :vartype scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :ivar principal_type: The principal type of the assigned principal ID. Possible values include: - "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :vartype principal_type: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param request_type: The type of the role assignment schedule request. Eg: SelfActivate, - AdminAssign etc. Possible values include: "AdminAssign", "AdminRemove", "AdminUpdate", - "AdminExtend", "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", "SelfRenew". - :type request_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RequestType - :ivar status: The status of the role assignment schedule request. Possible values include: - "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", - "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", - "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", - "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". - :vartype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status - :ivar approval_id: The approvalId of the role assignment schedule request. - :vartype approval_id: str - :param target_role_assignment_schedule_id: The resultant role assignment schedule id or the - role assignment schedule id being updated. - :type target_role_assignment_schedule_id: str - :param target_role_assignment_schedule_instance_id: The role assignment schedule instance id - being updated. - :type target_role_assignment_schedule_instance_id: str - :param schedule_info: Schedule info of the role assignment schedule. - :type schedule_info: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequestPropertiesScheduleInfo - :param linked_role_eligibility_schedule_id: The linked role eligibility schedule id - to - activate an eligibility. - :type linked_role_eligibility_schedule_id: str - :param justification: Justification for the role assignment. - :type justification: str - :param ticket_info: Ticket Info of the role assignment. - :type ticket_info: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequestPropertiesTicketInfo - :param condition: The conditions on the role assignment. This limits the resources it can be - assigned to. e.g.: - @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] - StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :ivar created_on: DateTime when role assignment schedule request was created. - :vartype created_on: ~datetime.datetime - :ivar requestor_id: Id of the user who created this request. - :vartype requestor_id: str - :ivar expanded_properties: Additional properties of principal, scope and role definition. - :vartype expanded_properties: - ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'scope': {'readonly': True}, - 'principal_type': {'readonly': True}, - 'status': {'readonly': True}, - 'approval_id': {'readonly': True}, - 'created_on': {'readonly': True}, - 'requestor_id': {'readonly': True}, - 'expanded_properties': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'request_type': {'key': 'properties.requestType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'approval_id': {'key': 'properties.approvalId', 'type': 'str'}, - 'target_role_assignment_schedule_id': {'key': 'properties.targetRoleAssignmentScheduleId', 'type': 'str'}, - 'target_role_assignment_schedule_instance_id': {'key': 'properties.targetRoleAssignmentScheduleInstanceId', 'type': 'str'}, - 'schedule_info': {'key': 'properties.scheduleInfo', 'type': 'RoleAssignmentScheduleRequestPropertiesScheduleInfo'}, - 'linked_role_eligibility_schedule_id': {'key': 'properties.linkedRoleEligibilityScheduleId', 'type': 'str'}, - 'justification': {'key': 'properties.justification', 'type': 'str'}, - 'ticket_info': {'key': 'properties.ticketInfo', 'type': 'RoleAssignmentScheduleRequestPropertiesTicketInfo'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'requestor_id': {'key': 'properties.requestorId', 'type': 'str'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentScheduleRequest, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = None - self.role_definition_id = kwargs.get('role_definition_id', None) - self.principal_id = kwargs.get('principal_id', None) - self.principal_type = None - self.request_type = kwargs.get('request_type', None) - self.status = None - self.approval_id = None - self.target_role_assignment_schedule_id = kwargs.get('target_role_assignment_schedule_id', None) - self.target_role_assignment_schedule_instance_id = kwargs.get('target_role_assignment_schedule_instance_id', None) - self.schedule_info = kwargs.get('schedule_info', None) - self.linked_role_eligibility_schedule_id = kwargs.get('linked_role_eligibility_schedule_id', None) - self.justification = kwargs.get('justification', None) - self.ticket_info = kwargs.get('ticket_info', None) - self.condition = kwargs.get('condition', None) - self.condition_version = kwargs.get('condition_version', None) - self.created_on = None - self.requestor_id = None - self.expanded_properties = None - - -class RoleAssignmentScheduleRequestFilter(msrest.serialization.Model): - """Role assignment schedule request filter. - - :param principal_id: Returns role assignment requests of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role assignment requests of the specific role definition. - :type role_definition_id: str - :param requestor_id: Returns role assignment requests created by specific principal. - :type requestor_id: str - :param status: Returns role assignment requests of specific status. - :type status: str - """ - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'requestor_id': {'key': 'requestorId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentScheduleRequestFilter, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.requestor_id = kwargs.get('requestor_id', None) - self.status = kwargs.get('status', None) - - -class RoleAssignmentScheduleRequestListResult(msrest.serialization.Model): - """Role assignment schedule request list operation result. - - :param value: Role assignment schedule request list. - :type value: - list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignmentScheduleRequest]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentScheduleRequestListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RoleAssignmentScheduleRequestPropertiesScheduleInfo(msrest.serialization.Model): - """Schedule info of the role assignment schedule. - - :param start_date_time: Start DateTime of the role assignment schedule. - :type start_date_time: ~datetime.datetime - :param expiration: Expiration of the role assignment schedule. - :type expiration: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration - """ - - _attribute_map = { - 'start_date_time': {'key': 'startDateTime', 'type': 'iso-8601'}, - 'expiration': {'key': 'expiration', 'type': 'RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentScheduleRequestPropertiesScheduleInfo, self).__init__(**kwargs) - self.start_date_time = kwargs.get('start_date_time', None) - self.expiration = kwargs.get('expiration', None) - - -class RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration(msrest.serialization.Model): - """Expiration of the role assignment schedule. - - :param type: Type of the role assignment schedule expiration. Possible values include: - "AfterDuration", "AfterDateTime", "NoExpiration". - :type type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Type - :param end_date_time: End DateTime of the role assignment schedule. - :type end_date_time: ~datetime.datetime - :param duration: Duration of the role assignment schedule in TimeSpan. - :type duration: str - """ - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'end_date_time': {'key': 'endDateTime', 'type': 'iso-8601'}, - 'duration': {'key': 'duration', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration, self).__init__(**kwargs) - self.type = kwargs.get('type', None) - self.end_date_time = kwargs.get('end_date_time', None) - self.duration = kwargs.get('duration', None) - - -class RoleAssignmentScheduleRequestPropertiesTicketInfo(msrest.serialization.Model): - """Ticket Info of the role assignment. - - :param ticket_number: Ticket number for the role assignment. - :type ticket_number: str - :param ticket_system: Ticket system name for the role assignment. - :type ticket_system: str - """ - - _attribute_map = { - 'ticket_number': {'key': 'ticketNumber', 'type': 'str'}, - 'ticket_system': {'key': 'ticketSystem', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentScheduleRequestPropertiesTicketInfo, self).__init__(**kwargs) - self.ticket_number = kwargs.get('ticket_number', None) - self.ticket_system = kwargs.get('ticket_system', None) - - -class RoleEligibilitySchedule(msrest.serialization.Model): - """Role eligibility schedule. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role eligibility schedule Id. - :vartype id: str - :ivar name: The role eligibility schedule name. - :vartype name: str - :ivar type: The role eligibility schedule type. - :vartype type: str - :param scope: The role eligibility schedule scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param role_eligibility_schedule_request_id: The id of roleEligibilityScheduleRequest used to - create this roleAssignmentSchedule. - :type role_eligibility_schedule_request_id: str - :param member_type: Membership type of the role eligibility schedule. Possible values include: - "Inherited", "Direct", "Group". - :type member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType - :param status: The status of the role eligibility schedule. Possible values include: - "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", - "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", - "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", - "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". - :type status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status - :param start_date_time: Start DateTime when role eligibility schedule. - :type start_date_time: ~datetime.datetime - :param end_date_time: End DateTime when role eligibility schedule. - :type end_date_time: ~datetime.datetime - :param condition: The conditions on the role assignment. This limits the resources it can be - assigned to. e.g.: - @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] - StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param created_on: DateTime when role eligibility schedule was created. - :type created_on: ~datetime.datetime - :param updated_on: DateTime when role eligibility schedule was modified. - :type updated_on: ~datetime.datetime - :param expanded_properties: Additional properties of principal, scope and role definition. - :type expanded_properties: - ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'role_eligibility_schedule_request_id': {'key': 'properties.roleEligibilityScheduleRequestId', 'type': 'str'}, - 'member_type': {'key': 'properties.memberType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'updated_on': {'key': 'properties.updatedOn', 'type': 'iso-8601'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilitySchedule, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = kwargs.get('scope', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.principal_id = kwargs.get('principal_id', None) - self.principal_type = kwargs.get('principal_type', None) - self.role_eligibility_schedule_request_id = kwargs.get('role_eligibility_schedule_request_id', None) - self.member_type = kwargs.get('member_type', None) - self.status = kwargs.get('status', None) - self.start_date_time = kwargs.get('start_date_time', None) - self.end_date_time = kwargs.get('end_date_time', None) - self.condition = kwargs.get('condition', None) - self.condition_version = kwargs.get('condition_version', None) - self.created_on = kwargs.get('created_on', None) - self.updated_on = kwargs.get('updated_on', None) - self.expanded_properties = kwargs.get('expanded_properties', None) - - -class RoleEligibilityScheduleFilter(msrest.serialization.Model): - """Role eligibility schedule filter. - - :param principal_id: Returns role eligibility schedule of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role eligibility schedule of the specific role definition. - :type role_definition_id: str - :param status: Returns role eligibility schedule of the specific status. - :type status: str - """ - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilityScheduleFilter, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.status = kwargs.get('status', None) - - -class RoleEligibilityScheduleInstance(msrest.serialization.Model): - """Information about current or upcoming role eligibility schedule instance. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role eligibility schedule instance ID. - :vartype id: str - :ivar name: The role eligibility schedule instance name. - :vartype name: str - :ivar type: The role eligibility schedule instance type. - :vartype type: str - :param scope: The role eligibility schedule scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param role_eligibility_schedule_id: Id of the master role eligibility schedule. - :type role_eligibility_schedule_id: str - :param status: The status of the role eligibility schedule instance. Possible values include: - "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", - "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", - "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", - "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". - :type status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status - :param start_date_time: The startDateTime of the role eligibility schedule instance. - :type start_date_time: ~datetime.datetime - :param end_date_time: The endDateTime of the role eligibility schedule instance. - :type end_date_time: ~datetime.datetime - :param member_type: Membership type of the role eligibility schedule. Possible values include: - "Inherited", "Direct", "Group". - :type member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType - :param condition: The conditions on the role assignment. This limits the resources it can be - assigned to. e.g.: - @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] - StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param created_on: DateTime when role eligibility schedule was created. - :type created_on: ~datetime.datetime - :param expanded_properties: Additional properties of principal, scope and role definition. - :type expanded_properties: - ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'role_eligibility_schedule_id': {'key': 'properties.roleEligibilityScheduleId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, - 'member_type': {'key': 'properties.memberType', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilityScheduleInstance, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = kwargs.get('scope', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.principal_id = kwargs.get('principal_id', None) - self.principal_type = kwargs.get('principal_type', None) - self.role_eligibility_schedule_id = kwargs.get('role_eligibility_schedule_id', None) - self.status = kwargs.get('status', None) - self.start_date_time = kwargs.get('start_date_time', None) - self.end_date_time = kwargs.get('end_date_time', None) - self.member_type = kwargs.get('member_type', None) - self.condition = kwargs.get('condition', None) - self.condition_version = kwargs.get('condition_version', None) - self.created_on = kwargs.get('created_on', None) - self.expanded_properties = kwargs.get('expanded_properties', None) - - -class RoleEligibilityScheduleInstanceFilter(msrest.serialization.Model): - """Role eligibility schedule instance filter. - - :param principal_id: Returns role eligibility schedule instances of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role eligibility schedule instances of the specific role - definition. - :type role_definition_id: str - :param status: Returns role eligibility schedule instances of the specific status. - :type status: str - :param role_eligibility_schedule_id: Returns role eligibility schedule instances belonging to a - specific role eligibility schedule. - :type role_eligibility_schedule_id: str - """ - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'role_eligibility_schedule_id': {'key': 'roleEligibilityScheduleId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilityScheduleInstanceFilter, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.status = kwargs.get('status', None) - self.role_eligibility_schedule_id = kwargs.get('role_eligibility_schedule_id', None) - - -class RoleEligibilityScheduleInstanceListResult(msrest.serialization.Model): - """Role eligibility schedule instance list operation result. - - :param value: Role eligibility schedule instance list. - :type value: - list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleInstance] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleEligibilityScheduleInstance]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilityScheduleInstanceListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RoleEligibilityScheduleListResult(msrest.serialization.Model): - """role eligibility schedule list operation result. - - :param value: role eligibility schedule list. - :type value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilitySchedule] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleEligibilitySchedule]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilityScheduleListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RoleEligibilityScheduleRequest(msrest.serialization.Model): - """Role Eligibility schedule request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role eligibility schedule request ID. - :vartype id: str - :ivar name: The role eligibility schedule request name. - :vartype name: str - :ivar type: The role eligibility schedule request type. - :vartype type: str - :ivar scope: The role eligibility schedule request scope. - :vartype scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :ivar principal_type: The principal type of the assigned principal ID. Possible values include: - "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :vartype principal_type: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param request_type: The type of the role assignment schedule request. Eg: SelfActivate, - AdminAssign etc. Possible values include: "AdminAssign", "AdminRemove", "AdminUpdate", - "AdminExtend", "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", "SelfRenew". - :type request_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RequestType - :ivar status: The status of the role eligibility schedule request. Possible values include: - "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", - "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", - "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", - "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". - :vartype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status - :ivar approval_id: The approvalId of the role eligibility schedule request. - :vartype approval_id: str - :param schedule_info: Schedule info of the role eligibility schedule. - :type schedule_info: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequestPropertiesScheduleInfo - :param target_role_eligibility_schedule_id: The resultant role eligibility schedule id or the - role eligibility schedule id being updated. - :type target_role_eligibility_schedule_id: str - :param target_role_eligibility_schedule_instance_id: The role eligibility schedule instance id - being updated. - :type target_role_eligibility_schedule_instance_id: str - :param justification: Justification for the role eligibility. - :type justification: str - :param ticket_info: Ticket Info of the role eligibility. - :type ticket_info: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequestPropertiesTicketInfo - :param condition: The conditions on the role assignment. This limits the resources it can be - assigned to. e.g.: - @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] - StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :ivar created_on: DateTime when role eligibility schedule request was created. - :vartype created_on: ~datetime.datetime - :ivar requestor_id: Id of the user who created this request. - :vartype requestor_id: str - :ivar expanded_properties: Additional properties of principal, scope and role definition. - :vartype expanded_properties: - ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'scope': {'readonly': True}, - 'principal_type': {'readonly': True}, - 'status': {'readonly': True}, - 'approval_id': {'readonly': True}, - 'created_on': {'readonly': True}, - 'requestor_id': {'readonly': True}, - 'expanded_properties': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'request_type': {'key': 'properties.requestType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'approval_id': {'key': 'properties.approvalId', 'type': 'str'}, - 'schedule_info': {'key': 'properties.scheduleInfo', 'type': 'RoleEligibilityScheduleRequestPropertiesScheduleInfo'}, - 'target_role_eligibility_schedule_id': {'key': 'properties.targetRoleEligibilityScheduleId', 'type': 'str'}, - 'target_role_eligibility_schedule_instance_id': {'key': 'properties.targetRoleEligibilityScheduleInstanceId', 'type': 'str'}, - 'justification': {'key': 'properties.justification', 'type': 'str'}, - 'ticket_info': {'key': 'properties.ticketInfo', 'type': 'RoleEligibilityScheduleRequestPropertiesTicketInfo'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'requestor_id': {'key': 'properties.requestorId', 'type': 'str'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilityScheduleRequest, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = None - self.role_definition_id = kwargs.get('role_definition_id', None) - self.principal_id = kwargs.get('principal_id', None) - self.principal_type = None - self.request_type = kwargs.get('request_type', None) - self.status = None - self.approval_id = None - self.schedule_info = kwargs.get('schedule_info', None) - self.target_role_eligibility_schedule_id = kwargs.get('target_role_eligibility_schedule_id', None) - self.target_role_eligibility_schedule_instance_id = kwargs.get('target_role_eligibility_schedule_instance_id', None) - self.justification = kwargs.get('justification', None) - self.ticket_info = kwargs.get('ticket_info', None) - self.condition = kwargs.get('condition', None) - self.condition_version = kwargs.get('condition_version', None) - self.created_on = None - self.requestor_id = None - self.expanded_properties = None - - -class RoleEligibilityScheduleRequestFilter(msrest.serialization.Model): - """Role eligibility schedule request filter. - - :param principal_id: Returns role eligibility requests of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role eligibility requests of the specific role definition. - :type role_definition_id: str - :param requestor_id: Returns role eligibility requests created by specific principal. - :type requestor_id: str - :param status: Returns role eligibility requests of specific status. - :type status: str - """ - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'requestor_id': {'key': 'requestorId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilityScheduleRequestFilter, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.requestor_id = kwargs.get('requestor_id', None) - self.status = kwargs.get('status', None) - - -class RoleEligibilityScheduleRequestListResult(msrest.serialization.Model): - """Role eligibility schedule request list operation result. - - :param value: Role eligibility schedule request list. - :type value: - list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleEligibilityScheduleRequest]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilityScheduleRequestListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RoleEligibilityScheduleRequestPropertiesScheduleInfo(msrest.serialization.Model): - """Schedule info of the role eligibility schedule. - - :param start_date_time: Start DateTime of the role eligibility schedule. - :type start_date_time: ~datetime.datetime - :param expiration: Expiration of the role eligibility schedule. - :type expiration: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration - """ - - _attribute_map = { - 'start_date_time': {'key': 'startDateTime', 'type': 'iso-8601'}, - 'expiration': {'key': 'expiration', 'type': 'RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilityScheduleRequestPropertiesScheduleInfo, self).__init__(**kwargs) - self.start_date_time = kwargs.get('start_date_time', None) - self.expiration = kwargs.get('expiration', None) - - -class RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration(msrest.serialization.Model): - """Expiration of the role eligibility schedule. - - :param type: Type of the role eligibility schedule expiration. Possible values include: - "AfterDuration", "AfterDateTime", "NoExpiration". - :type type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Type - :param end_date_time: End DateTime of the role eligibility schedule. - :type end_date_time: ~datetime.datetime - :param duration: Duration of the role eligibility schedule in TimeSpan. - :type duration: str - """ - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'end_date_time': {'key': 'endDateTime', 'type': 'iso-8601'}, - 'duration': {'key': 'duration', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration, self).__init__(**kwargs) - self.type = kwargs.get('type', None) - self.end_date_time = kwargs.get('end_date_time', None) - self.duration = kwargs.get('duration', None) - - -class RoleEligibilityScheduleRequestPropertiesTicketInfo(msrest.serialization.Model): - """Ticket Info of the role eligibility. - - :param ticket_number: Ticket number for the role eligibility. - :type ticket_number: str - :param ticket_system: Ticket system name for the role eligibility. - :type ticket_system: str - """ - - _attribute_map = { - 'ticket_number': {'key': 'ticketNumber', 'type': 'str'}, - 'ticket_system': {'key': 'ticketSystem', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleEligibilityScheduleRequestPropertiesTicketInfo, self).__init__(**kwargs) - self.ticket_number = kwargs.get('ticket_number', None) - self.ticket_system = kwargs.get('ticket_system', None) - - -class RoleManagementPolicy(msrest.serialization.Model): - """Role management policy. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role management policy Id. - :vartype id: str - :ivar name: The role management policy name. - :vartype name: str - :ivar type: The role management policy type. - :vartype type: str - :param scope: The role management policy scope. - :type scope: str - :param display_name: The role management policy display name. - :type display_name: str - :param description: The role management policy description. - :type description: str - :param is_organization_default: The role management policy is default policy. - :type is_organization_default: bool - :ivar last_modified_by: The name of the entity last modified it. - :vartype last_modified_by: ~azure.mgmt.authorization.v2020_10_01_preview.models.Principal - :ivar last_modified_date_time: The last modified date time. - :vartype last_modified_date_time: ~datetime.datetime - :param rules: The rule applied to the policy. - :type rules: - list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRule] - :ivar effective_rules: The readonly computed rule applied to the policy. - :vartype effective_rules: - list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRule] - :ivar policy_properties: Additional properties of scope. - :vartype policy_properties: - ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyProperties - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'last_modified_by': {'readonly': True}, - 'last_modified_date_time': {'readonly': True}, - 'effective_rules': {'readonly': True}, - 'policy_properties': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'is_organization_default': {'key': 'properties.isOrganizationDefault', 'type': 'bool'}, - 'last_modified_by': {'key': 'properties.lastModifiedBy', 'type': 'Principal'}, - 'last_modified_date_time': {'key': 'properties.lastModifiedDateTime', 'type': 'iso-8601'}, - 'rules': {'key': 'properties.rules', 'type': '[RoleManagementPolicyRule]'}, - 'effective_rules': {'key': 'properties.effectiveRules', 'type': '[RoleManagementPolicyRule]'}, - 'policy_properties': {'key': 'properties.policyProperties', 'type': 'PolicyProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleManagementPolicy, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = kwargs.get('scope', None) - self.display_name = kwargs.get('display_name', None) - self.description = kwargs.get('description', None) - self.is_organization_default = kwargs.get('is_organization_default', None) - self.last_modified_by = None - self.last_modified_date_time = None - self.rules = kwargs.get('rules', None) - self.effective_rules = None - self.policy_properties = None - - -class RoleManagementPolicyRule(msrest.serialization.Model): - """The role management policy rule. - - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: RoleManagementPolicyApprovalRule, RoleManagementPolicyAuthenticationContextRule, RoleManagementPolicyEnablementRule, RoleManagementPolicyExpirationRule, RoleManagementPolicyNotificationRule. - - All required parameters must be populated in order to send to Azure. - - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", - "RoleManagementPolicyNotificationRule". - :type rule_type: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget - """ - - _validation = { - 'rule_type': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, - } - - _subtype_map = { - 'rule_type': {'RoleManagementPolicyApprovalRule': 'RoleManagementPolicyApprovalRule', 'RoleManagementPolicyAuthenticationContextRule': 'RoleManagementPolicyAuthenticationContextRule', 'RoleManagementPolicyEnablementRule': 'RoleManagementPolicyEnablementRule', 'RoleManagementPolicyExpirationRule': 'RoleManagementPolicyExpirationRule', 'RoleManagementPolicyNotificationRule': 'RoleManagementPolicyNotificationRule'} - } - - def __init__( - self, - **kwargs - ): - super(RoleManagementPolicyRule, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.rule_type = None # type: Optional[str] - self.target = kwargs.get('target', None) - - -class RoleManagementPolicyApprovalRule(RoleManagementPolicyRule): - """The role management policy rule. - - All required parameters must be populated in order to send to Azure. - - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", - "RoleManagementPolicyNotificationRule". - :type rule_type: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget - :param setting: The approval setting. - :type setting: ~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalSettings - """ - - _validation = { - 'rule_type': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, - 'setting': {'key': 'setting', 'type': 'ApprovalSettings'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleManagementPolicyApprovalRule, self).__init__(**kwargs) - self.rule_type = 'RoleManagementPolicyApprovalRule' # type: str - self.setting = kwargs.get('setting', None) - - -class RoleManagementPolicyAssignment(msrest.serialization.Model): - """Role management policy. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role management policy Id. - :vartype id: str - :ivar name: The role management policy name. - :vartype name: str - :ivar type: The role management policy type. - :vartype type: str - :param scope: The role management policy scope. - :type scope: str - :param role_definition_id: The role definition of management policy assignment. - :type role_definition_id: str - :param policy_id: The policy id role management policy assignment. - :type policy_id: str - :ivar policy_assignment_properties: Additional properties of scope, role definition and policy. - :vartype policy_assignment_properties: - ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyAssignmentProperties - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'policy_assignment_properties': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'policy_id': {'key': 'properties.policyId', 'type': 'str'}, - 'policy_assignment_properties': {'key': 'properties.policyAssignmentProperties', 'type': 'PolicyAssignmentProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleManagementPolicyAssignment, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.scope = kwargs.get('scope', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.policy_id = kwargs.get('policy_id', None) - self.policy_assignment_properties = None - - -class RoleManagementPolicyAssignmentListResult(msrest.serialization.Model): - """Role management policy assignment list operation result. - - :param value: Role management policy assignment list. - :type value: - list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleManagementPolicyAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleManagementPolicyAssignmentListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RoleManagementPolicyAuthenticationContextRule(RoleManagementPolicyRule): - """The role management policy rule. - - All required parameters must be populated in order to send to Azure. - - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", - "RoleManagementPolicyNotificationRule". - :type rule_type: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget - :param is_enabled: The value indicating if rule is enabled. - :type is_enabled: bool - :param claim_value: The claim value. - :type claim_value: str - """ - - _validation = { - 'rule_type': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, - 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, - 'claim_value': {'key': 'claimValue', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleManagementPolicyAuthenticationContextRule, self).__init__(**kwargs) - self.rule_type = 'RoleManagementPolicyAuthenticationContextRule' # type: str - self.is_enabled = kwargs.get('is_enabled', None) - self.claim_value = kwargs.get('claim_value', None) - - -class RoleManagementPolicyEnablementRule(RoleManagementPolicyRule): - """The role management policy rule. - - All required parameters must be populated in order to send to Azure. - - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", - "RoleManagementPolicyNotificationRule". - :type rule_type: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget - :param enabled_rules: The list of enabled rules. - :type enabled_rules: list[str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.EnablementRules] - """ - - _validation = { - 'rule_type': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, - 'enabled_rules': {'key': 'enabledRules', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleManagementPolicyEnablementRule, self).__init__(**kwargs) - self.rule_type = 'RoleManagementPolicyEnablementRule' # type: str - self.enabled_rules = kwargs.get('enabled_rules', None) - - -class RoleManagementPolicyExpirationRule(RoleManagementPolicyRule): - """The role management policy rule. - - All required parameters must be populated in order to send to Azure. - - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", - "RoleManagementPolicyNotificationRule". - :type rule_type: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget - :param is_expiration_required: The value indicating whether expiration is required. - :type is_expiration_required: bool - :param maximum_duration: The maximum duration of expiration in timespan. - :type maximum_duration: str - """ - - _validation = { - 'rule_type': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, - 'is_expiration_required': {'key': 'isExpirationRequired', 'type': 'bool'}, - 'maximum_duration': {'key': 'maximumDuration', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleManagementPolicyExpirationRule, self).__init__(**kwargs) - self.rule_type = 'RoleManagementPolicyExpirationRule' # type: str - self.is_expiration_required = kwargs.get('is_expiration_required', None) - self.maximum_duration = kwargs.get('maximum_duration', None) - - -class RoleManagementPolicyListResult(msrest.serialization.Model): - """Role management policy list operation result. - - :param value: Role management policy list. - :type value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleManagementPolicy]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleManagementPolicyListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RoleManagementPolicyNotificationRule(RoleManagementPolicyRule): - """The role management policy rule. - - All required parameters must be populated in order to send to Azure. - - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", - "RoleManagementPolicyNotificationRule". - :type rule_type: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: - ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget - :param notification_type: The type of notification. Possible values include: "Email". - :type notification_type: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.NotificationDeliveryMechanism - :param notification_level: The notification level. Possible values include: "None", "Critical", - "All". - :type notification_level: str or - ~azure.mgmt.authorization.v2020_10_01_preview.models.NotificationLevel - :param recipient_type: The recipient type. Possible values include: "Requestor", "Approver", - "Admin". - :type recipient_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RecipientType - :param notification_recipients: The list notification recipients. - :type notification_recipients: list[str] - :param is_default_recipients_enabled: Its value determine if the notification need to be sent - to the recipient type specified in policy rule. - :type is_default_recipients_enabled: bool - """ - - _validation = { - 'rule_type': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, - 'notification_type': {'key': 'notificationType', 'type': 'str'}, - 'notification_level': {'key': 'notificationLevel', 'type': 'str'}, - 'recipient_type': {'key': 'recipientType', 'type': 'str'}, - 'notification_recipients': {'key': 'notificationRecipients', 'type': '[str]'}, - 'is_default_recipients_enabled': {'key': 'isDefaultRecipientsEnabled', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleManagementPolicyNotificationRule, self).__init__(**kwargs) - self.rule_type = 'RoleManagementPolicyNotificationRule' # type: str - self.notification_type = kwargs.get('notification_type', None) - self.notification_level = kwargs.get('notification_level', None) - self.recipient_type = kwargs.get('recipient_type', None) - self.notification_recipients = kwargs.get('notification_recipients', None) - self.is_default_recipients_enabled = kwargs.get('is_default_recipients_enabled', None) - - -class RoleManagementPolicyRuleTarget(msrest.serialization.Model): - """The role management policy rule target. - - :param caller: The caller of the setting. - :type caller: str - :param operations: The type of operation. - :type operations: list[str] - :param level: The assignment level to which it is applied. - :type level: str - :param target_objects: The list of target objects. - :type target_objects: list[str] - :param inheritable_settings: The list of inheritable settings. - :type inheritable_settings: list[str] - :param enforced_settings: The list of enforced settings. - :type enforced_settings: list[str] - """ - - _attribute_map = { - 'caller': {'key': 'caller', 'type': 'str'}, - 'operations': {'key': 'operations', 'type': '[str]'}, - 'level': {'key': 'level', 'type': 'str'}, - 'target_objects': {'key': 'targetObjects', 'type': '[str]'}, - 'inheritable_settings': {'key': 'inheritableSettings', 'type': '[str]'}, - 'enforced_settings': {'key': 'enforcedSettings', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleManagementPolicyRuleTarget, self).__init__(**kwargs) - self.caller = kwargs.get('caller', None) - self.operations = kwargs.get('operations', None) - self.level = kwargs.get('level', None) - self.target_objects = kwargs.get('target_objects', None) - self.inheritable_settings = kwargs.get('inheritable_settings', None) - self.enforced_settings = kwargs.get('enforced_settings', None) - - -class UserSet(msrest.serialization.Model): - """The detail of a user. - - :param user_type: The type of user. Possible values include: "User", "Group". - :type user_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.UserType - :param is_backup: The value indicating whether the user is a backup fallback approver. - :type is_backup: bool - :param id: The object id of the user. - :type id: str - :param description: The description of the user. - :type description: str - """ - - _attribute_map = { - 'user_type': {'key': 'userType', 'type': 'str'}, - 'is_backup': {'key': 'isBackup', 'type': 'bool'}, - 'id': {'key': 'id', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(UserSet, self).__init__(**kwargs) - self.user_type = kwargs.get('user_type', None) - self.is_backup = kwargs.get('is_backup', None) - self.id = kwargs.get('id', None) - self.description = kwargs.get('description', None) - - -class ValidationResponse(msrest.serialization.Model): - """Validation response. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar is_valid: Whether or not validation succeeded. - :vartype is_valid: bool - :param error_info: Failed validation result details. - :type error_info: - ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponseErrorInfo - """ - - _validation = { - 'is_valid': {'readonly': True}, - } - - _attribute_map = { - 'is_valid': {'key': 'isValid', 'type': 'bool'}, - 'error_info': {'key': 'errorInfo', 'type': 'ValidationResponseErrorInfo'}, - } - - def __init__( - self, - **kwargs - ): - super(ValidationResponse, self).__init__(**kwargs) - self.is_valid = None - self.error_info = kwargs.get('error_info', None) - - -class ValidationResponseErrorInfo(msrest.serialization.Model): - """Failed validation result details. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Error code indicating why validation failed. - :vartype code: str - :ivar message: Message indicating why validation failed. - :vartype message: str - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ValidationResponseErrorInfo, self).__init__(**kwargs) - self.code = None - self.message = None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_models_py3.py index f56a5d95927..aca5adf0008 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_models_py3.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,37 +8,40 @@ # -------------------------------------------------------------------------- import datetime -from typing import List, Optional, Union +from typing import List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization -from ._authorization_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class ApprovalSettings(msrest.serialization.Model): +class ApprovalSettings(_serialization.Model): """The approval settings. - :param is_approval_required: Determine whether approval is required or not. - :type is_approval_required: bool - :param is_approval_required_for_extension: Determine whether approval is required for - assignment extension. - :type is_approval_required_for_extension: bool - :param is_requestor_justification_required: Determine whether requestor justification required. - :type is_requestor_justification_required: bool - :param approval_mode: The type of rule. Possible values include: "SingleStage", "Serial", - "Parallel", "NoApproval". - :type approval_mode: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalMode - :param approval_stages: The approval stages of the request. - :type approval_stages: list[~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalStage] + :ivar is_approval_required: Determine whether approval is required or not. + :vartype is_approval_required: bool + :ivar is_approval_required_for_extension: Determine whether approval is required for assignment + extension. + :vartype is_approval_required_for_extension: bool + :ivar is_requestor_justification_required: Determine whether requestor justification required. + :vartype is_requestor_justification_required: bool + :ivar approval_mode: The type of rule. Known values are: "SingleStage", "Serial", "Parallel", + and "NoApproval". + :vartype approval_mode: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalMode + :ivar approval_stages: The approval stages of the request. + :vartype approval_stages: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalStage] """ _attribute_map = { - 'is_approval_required': {'key': 'isApprovalRequired', 'type': 'bool'}, - 'is_approval_required_for_extension': {'key': 'isApprovalRequiredForExtension', 'type': 'bool'}, - 'is_requestor_justification_required': {'key': 'isRequestorJustificationRequired', 'type': 'bool'}, - 'approval_mode': {'key': 'approvalMode', 'type': 'str'}, - 'approval_stages': {'key': 'approvalStages', 'type': '[ApprovalStage]'}, + "is_approval_required": {"key": "isApprovalRequired", "type": "bool"}, + "is_approval_required_for_extension": {"key": "isApprovalRequiredForExtension", "type": "bool"}, + "is_requestor_justification_required": {"key": "isRequestorJustificationRequired", "type": "bool"}, + "approval_mode": {"key": "approvalMode", "type": "str"}, + "approval_stages": {"key": "approvalStages", "type": "[ApprovalStage]"}, } def __init__( @@ -46,11 +50,28 @@ def __init__( is_approval_required: Optional[bool] = None, is_approval_required_for_extension: Optional[bool] = None, is_requestor_justification_required: Optional[bool] = None, - approval_mode: Optional[Union[str, "ApprovalMode"]] = None, - approval_stages: Optional[List["ApprovalStage"]] = None, + approval_mode: Optional[Union[str, "_models.ApprovalMode"]] = None, + approval_stages: Optional[List["_models.ApprovalStage"]] = None, **kwargs ): - super(ApprovalSettings, self).__init__(**kwargs) + """ + :keyword is_approval_required: Determine whether approval is required or not. + :paramtype is_approval_required: bool + :keyword is_approval_required_for_extension: Determine whether approval is required for + assignment extension. + :paramtype is_approval_required_for_extension: bool + :keyword is_requestor_justification_required: Determine whether requestor justification + required. + :paramtype is_requestor_justification_required: bool + :keyword approval_mode: The type of rule. Known values are: "SingleStage", "Serial", + "Parallel", and "NoApproval". + :paramtype approval_mode: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalMode + :keyword approval_stages: The approval stages of the request. + :paramtype approval_stages: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalStage] + """ + super().__init__(**kwargs) self.is_approval_required = is_approval_required self.is_approval_required_for_extension = is_approval_required_for_extension self.is_requestor_justification_required = is_requestor_justification_required @@ -58,33 +79,34 @@ def __init__( self.approval_stages = approval_stages -class ApprovalStage(msrest.serialization.Model): +class ApprovalStage(_serialization.Model): """The approval stage. - :param approval_stage_time_out_in_days: The time in days when approval request would be timed + :ivar approval_stage_time_out_in_days: The time in days when approval request would be timed out. - :type approval_stage_time_out_in_days: int - :param is_approver_justification_required: Determine whether approver need to provide + :vartype approval_stage_time_out_in_days: int + :ivar is_approver_justification_required: Determine whether approver need to provide justification for his decision. - :type is_approver_justification_required: bool - :param escalation_time_in_minutes: The time in minutes when the approval request would be + :vartype is_approver_justification_required: bool + :ivar escalation_time_in_minutes: The time in minutes when the approval request would be escalated if the primary approver does not approves. - :type escalation_time_in_minutes: int - :param primary_approvers: The primary approver of the request. - :type primary_approvers: list[~azure.mgmt.authorization.v2020_10_01_preview.models.UserSet] - :param is_escalation_enabled: The value determine whether escalation feature is enabled. - :type is_escalation_enabled: bool - :param escalation_approvers: The escalation approver of the request. - :type escalation_approvers: list[~azure.mgmt.authorization.v2020_10_01_preview.models.UserSet] + :vartype escalation_time_in_minutes: int + :ivar primary_approvers: The primary approver of the request. + :vartype primary_approvers: list[~azure.mgmt.authorization.v2020_10_01_preview.models.UserSet] + :ivar is_escalation_enabled: The value determine whether escalation feature is enabled. + :vartype is_escalation_enabled: bool + :ivar escalation_approvers: The escalation approver of the request. + :vartype escalation_approvers: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.UserSet] """ _attribute_map = { - 'approval_stage_time_out_in_days': {'key': 'approvalStageTimeOutInDays', 'type': 'int'}, - 'is_approver_justification_required': {'key': 'isApproverJustificationRequired', 'type': 'bool'}, - 'escalation_time_in_minutes': {'key': 'escalationTimeInMinutes', 'type': 'int'}, - 'primary_approvers': {'key': 'primaryApprovers', 'type': '[UserSet]'}, - 'is_escalation_enabled': {'key': 'isEscalationEnabled', 'type': 'bool'}, - 'escalation_approvers': {'key': 'escalationApprovers', 'type': '[UserSet]'}, + "approval_stage_time_out_in_days": {"key": "approvalStageTimeOutInDays", "type": "int"}, + "is_approver_justification_required": {"key": "isApproverJustificationRequired", "type": "bool"}, + "escalation_time_in_minutes": {"key": "escalationTimeInMinutes", "type": "int"}, + "primary_approvers": {"key": "primaryApprovers", "type": "[UserSet]"}, + "is_escalation_enabled": {"key": "isEscalationEnabled", "type": "bool"}, + "escalation_approvers": {"key": "escalationApprovers", "type": "[UserSet]"}, } def __init__( @@ -93,12 +115,31 @@ def __init__( approval_stage_time_out_in_days: Optional[int] = None, is_approver_justification_required: Optional[bool] = None, escalation_time_in_minutes: Optional[int] = None, - primary_approvers: Optional[List["UserSet"]] = None, + primary_approvers: Optional[List["_models.UserSet"]] = None, is_escalation_enabled: Optional[bool] = None, - escalation_approvers: Optional[List["UserSet"]] = None, + escalation_approvers: Optional[List["_models.UserSet"]] = None, **kwargs ): - super(ApprovalStage, self).__init__(**kwargs) + """ + :keyword approval_stage_time_out_in_days: The time in days when approval request would be timed + out. + :paramtype approval_stage_time_out_in_days: int + :keyword is_approver_justification_required: Determine whether approver need to provide + justification for his decision. + :paramtype is_approver_justification_required: bool + :keyword escalation_time_in_minutes: The time in minutes when the approval request would be + escalated if the primary approver does not approves. + :paramtype escalation_time_in_minutes: int + :keyword primary_approvers: The primary approver of the request. + :paramtype primary_approvers: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.UserSet] + :keyword is_escalation_enabled: The value determine whether escalation feature is enabled. + :paramtype is_escalation_enabled: bool + :keyword escalation_approvers: The escalation approver of the request. + :paramtype escalation_approvers: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.UserSet] + """ + super().__init__(**kwargs) self.approval_stage_time_out_in_days = approval_stage_time_out_in_days self.is_approver_justification_required = is_approver_justification_required self.escalation_time_in_minutes = escalation_time_in_minutes @@ -107,35 +148,37 @@ def __init__( self.escalation_approvers = escalation_approvers -class CloudErrorBody(msrest.serialization.Model): +class CloudErrorBody(_serialization.Model): """An error response from the service. - :param code: An identifier for the error. Codes are invariant and are intended to be consumed + :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. - :type code: str - :param message: A message describing the error, intended to be suitable for display in a user + :vartype code: str + :ivar message: A message describing the error, intended to be suitable for display in a user interface. - :type message: str + :vartype message: str """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - } - - def __init__( - self, - *, - code: Optional[str] = None, - message: Optional[str] = None, - **kwargs - ): - super(CloudErrorBody, self).__init__(**kwargs) + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs): + """ + :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. + :paramtype code: str + :keyword message: A message describing the error, intended to be suitable for display in a user + interface. + :paramtype message: str + """ + super().__init__(**kwargs) self.code = code self.message = message -class EligibleChildResource(msrest.serialization.Model): +class EligibleChildResource(_serialization.Model): """Eligible child resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -149,54 +192,60 @@ class EligibleChildResource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(EligibleChildResource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None -class EligibleChildResourcesListResult(msrest.serialization.Model): +class EligibleChildResourcesListResult(_serialization.Model): """Eligible child resources list operation result. - :param value: Eligible child resource list. - :type value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.EligibleChildResource] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Eligible child resource list. + :vartype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.EligibleChildResource] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[EligibleChildResource]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[EligibleChildResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["EligibleChildResource"]] = None, + value: Optional[List["_models.EligibleChildResource"]] = None, next_link: Optional[str] = None, **kwargs ): - super(EligibleChildResourcesListResult, self).__init__(**kwargs) + """ + :keyword value: Eligible child resource list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.EligibleChildResource] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ErrorAdditionalInfo(msrest.serialization.Model): +class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. @@ -204,29 +253,27 @@ class ErrorAdditionalInfo(msrest.serialization.Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: any + :vartype info: JSON """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - super(ErrorAdditionalInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None -class ErrorDetail(msrest.serialization.Model): +class ErrorDetail(_serialization.Model): """The error detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -245,26 +292,24 @@ class ErrorDetail(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -272,176 +317,211 @@ def __init__( self.additional_info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - :param error: The error object. - :type error: ~azure.mgmt.authorization.v2020_10_01_preview.models.ErrorDetail + :ivar error: The error object. + :vartype error: ~azure.mgmt.authorization.v2020_10_01_preview.models.ErrorDetail """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, + "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__( - self, - *, - error: Optional["ErrorDetail"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.authorization.v2020_10_01_preview.models.ErrorDetail + """ + super().__init__(**kwargs) self.error = error -class ExpandedProperties(msrest.serialization.Model): +class ExpandedProperties(_serialization.Model): """ExpandedProperties. - :param scope: Details of the resource scope. - :type scope: ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedPropertiesScope - :param role_definition: Details of role definition. - :type role_definition: + :ivar scope: Details of the resource scope. + :vartype scope: ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedPropertiesScope + :ivar role_definition: Details of role definition. + :vartype role_definition: ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedPropertiesRoleDefinition - :param principal: Details of the principal. - :type principal: + :ivar principal: Details of the principal. + :vartype principal: ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedPropertiesPrincipal """ _attribute_map = { - 'scope': {'key': 'scope', 'type': 'ExpandedPropertiesScope'}, - 'role_definition': {'key': 'roleDefinition', 'type': 'ExpandedPropertiesRoleDefinition'}, - 'principal': {'key': 'principal', 'type': 'ExpandedPropertiesPrincipal'}, + "scope": {"key": "scope", "type": "ExpandedPropertiesScope"}, + "role_definition": {"key": "roleDefinition", "type": "ExpandedPropertiesRoleDefinition"}, + "principal": {"key": "principal", "type": "ExpandedPropertiesPrincipal"}, } def __init__( self, *, - scope: Optional["ExpandedPropertiesScope"] = None, - role_definition: Optional["ExpandedPropertiesRoleDefinition"] = None, - principal: Optional["ExpandedPropertiesPrincipal"] = None, + scope: Optional["_models.ExpandedPropertiesScope"] = None, + role_definition: Optional["_models.ExpandedPropertiesRoleDefinition"] = None, + principal: Optional["_models.ExpandedPropertiesPrincipal"] = None, **kwargs ): - super(ExpandedProperties, self).__init__(**kwargs) + """ + :keyword scope: Details of the resource scope. + :paramtype scope: ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedPropertiesScope + :keyword role_definition: Details of role definition. + :paramtype role_definition: + ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedPropertiesRoleDefinition + :keyword principal: Details of the principal. + :paramtype principal: + ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedPropertiesPrincipal + """ + super().__init__(**kwargs) self.scope = scope self.role_definition = role_definition self.principal = principal -class ExpandedPropertiesPrincipal(msrest.serialization.Model): +class ExpandedPropertiesPrincipal(_serialization.Model): """Details of the principal. - :param id: Id of the principal. - :type id: str - :param display_name: Display name of the principal. - :type display_name: str - :param email: Email id of the principal. - :type email: str - :param type: Type of the principal. - :type type: str + :ivar id: Id of the principal. + :vartype id: str + :ivar display_name: Display name of the principal. + :vartype display_name: str + :ivar email: Email id of the principal. + :vartype email: str + :ivar type: Type of the principal. + :vartype type: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "email": {"key": "email", "type": "str"}, + "type": {"key": "type", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin display_name: Optional[str] = None, email: Optional[str] = None, type: Optional[str] = None, **kwargs ): - super(ExpandedPropertiesPrincipal, self).__init__(**kwargs) + """ + :keyword id: Id of the principal. + :paramtype id: str + :keyword display_name: Display name of the principal. + :paramtype display_name: str + :keyword email: Email id of the principal. + :paramtype email: str + :keyword type: Type of the principal. + :paramtype type: str + """ + super().__init__(**kwargs) self.id = id self.display_name = display_name self.email = email self.type = type -class ExpandedPropertiesRoleDefinition(msrest.serialization.Model): +class ExpandedPropertiesRoleDefinition(_serialization.Model): """Details of role definition. - :param id: Id of the role definition. - :type id: str - :param display_name: Display name of the role definition. - :type display_name: str - :param type: Type of the role definition. - :type type: str + :ivar id: Id of the role definition. + :vartype id: str + :ivar display_name: Display name of the role definition. + :vartype display_name: str + :ivar type: Type of the role definition. + :vartype type: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin display_name: Optional[str] = None, type: Optional[str] = None, **kwargs ): - super(ExpandedPropertiesRoleDefinition, self).__init__(**kwargs) + """ + :keyword id: Id of the role definition. + :paramtype id: str + :keyword display_name: Display name of the role definition. + :paramtype display_name: str + :keyword type: Type of the role definition. + :paramtype type: str + """ + super().__init__(**kwargs) self.id = id self.display_name = display_name self.type = type -class ExpandedPropertiesScope(msrest.serialization.Model): +class ExpandedPropertiesScope(_serialization.Model): """Details of the resource scope. - :param id: Scope id of the resource. - :type id: str - :param display_name: Display name of the resource. - :type display_name: str - :param type: Type of the resource. - :type type: str + :ivar id: Scope id of the resource. + :vartype id: str + :ivar display_name: Display name of the resource. + :vartype display_name: str + :ivar type: Type of the resource. + :vartype type: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin display_name: Optional[str] = None, type: Optional[str] = None, **kwargs ): - super(ExpandedPropertiesScope, self).__init__(**kwargs) + """ + :keyword id: Scope id of the resource. + :paramtype id: str + :keyword display_name: Display name of the resource. + :paramtype display_name: str + :keyword type: Type of the resource. + :paramtype type: str + """ + super().__init__(**kwargs) self.id = id self.display_name = display_name self.type = type -class Permission(msrest.serialization.Model): +class Permission(_serialization.Model): """Role definition permissions. - :param actions: Allowed actions. - :type actions: list[str] - :param not_actions: Denied actions. - :type not_actions: list[str] - :param data_actions: Allowed Data actions. - :type data_actions: list[str] - :param not_data_actions: Denied Data actions. - :type not_data_actions: list[str] + :ivar actions: Allowed actions. + :vartype actions: list[str] + :ivar not_actions: Denied actions. + :vartype not_actions: list[str] + :ivar data_actions: Allowed Data actions. + :vartype data_actions: list[str] + :ivar not_data_actions: Denied Data actions. + :vartype not_data_actions: list[str] """ _attribute_map = { - 'actions': {'key': 'actions', 'type': '[str]'}, - 'not_actions': {'key': 'notActions', 'type': '[str]'}, - 'data_actions': {'key': 'dataActions', 'type': '[str]'}, - 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, + "actions": {"key": "actions", "type": "[str]"}, + "not_actions": {"key": "notActions", "type": "[str]"}, + "data_actions": {"key": "dataActions", "type": "[str]"}, + "not_data_actions": {"key": "notDataActions", "type": "[str]"}, } def __init__( @@ -453,146 +533,189 @@ def __init__( not_data_actions: Optional[List[str]] = None, **kwargs ): - super(Permission, self).__init__(**kwargs) + """ + :keyword actions: Allowed actions. + :paramtype actions: list[str] + :keyword not_actions: Denied actions. + :paramtype not_actions: list[str] + :keyword data_actions: Allowed Data actions. + :paramtype data_actions: list[str] + :keyword not_data_actions: Denied Data actions. + :paramtype not_data_actions: list[str] + """ + super().__init__(**kwargs) self.actions = actions self.not_actions = not_actions self.data_actions = data_actions self.not_data_actions = not_data_actions -class PolicyAssignmentProperties(msrest.serialization.Model): +class PolicyAssignmentProperties(_serialization.Model): """PolicyAssignmentProperties. - :param scope: Details of the resource scope. - :type scope: + :ivar scope: Details of the resource scope. + :vartype scope: ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyAssignmentPropertiesScope - :param role_definition: Details of role definition. - :type role_definition: + :ivar role_definition: Details of role definition. + :vartype role_definition: ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyAssignmentPropertiesRoleDefinition - :param policy: Details of the policy. - :type policy: + :ivar policy: Details of the policy. + :vartype policy: ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyAssignmentPropertiesPolicy """ _attribute_map = { - 'scope': {'key': 'scope', 'type': 'PolicyAssignmentPropertiesScope'}, - 'role_definition': {'key': 'roleDefinition', 'type': 'PolicyAssignmentPropertiesRoleDefinition'}, - 'policy': {'key': 'policy', 'type': 'PolicyAssignmentPropertiesPolicy'}, + "scope": {"key": "scope", "type": "PolicyAssignmentPropertiesScope"}, + "role_definition": {"key": "roleDefinition", "type": "PolicyAssignmentPropertiesRoleDefinition"}, + "policy": {"key": "policy", "type": "PolicyAssignmentPropertiesPolicy"}, } def __init__( self, *, - scope: Optional["PolicyAssignmentPropertiesScope"] = None, - role_definition: Optional["PolicyAssignmentPropertiesRoleDefinition"] = None, - policy: Optional["PolicyAssignmentPropertiesPolicy"] = None, + scope: Optional["_models.PolicyAssignmentPropertiesScope"] = None, + role_definition: Optional["_models.PolicyAssignmentPropertiesRoleDefinition"] = None, + policy: Optional["_models.PolicyAssignmentPropertiesPolicy"] = None, **kwargs ): - super(PolicyAssignmentProperties, self).__init__(**kwargs) + """ + :keyword scope: Details of the resource scope. + :paramtype scope: + ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyAssignmentPropertiesScope + :keyword role_definition: Details of role definition. + :paramtype role_definition: + ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyAssignmentPropertiesRoleDefinition + :keyword policy: Details of the policy. + :paramtype policy: + ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyAssignmentPropertiesPolicy + """ + super().__init__(**kwargs) self.scope = scope self.role_definition = role_definition self.policy = policy -class PolicyAssignmentPropertiesPolicy(msrest.serialization.Model): +class PolicyAssignmentPropertiesPolicy(_serialization.Model): """Details of the policy. Variables are only populated by the server, and will be ignored when sending a request. - :param id: Id of the policy. - :type id: str + :ivar id: Id of the policy. + :vartype id: str :ivar last_modified_by: The name of the entity last modified it. :vartype last_modified_by: ~azure.mgmt.authorization.v2020_10_01_preview.models.Principal - :param last_modified_date_time: The last modified date time. - :type last_modified_date_time: ~datetime.datetime + :ivar last_modified_date_time: The last modified date time. + :vartype last_modified_date_time: ~datetime.datetime """ _validation = { - 'last_modified_by': {'readonly': True}, + "last_modified_by": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'Principal'}, - 'last_modified_date_time': {'key': 'lastModifiedDateTime', 'type': 'iso-8601'}, + "id": {"key": "id", "type": "str"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "Principal"}, + "last_modified_date_time": {"key": "lastModifiedDateTime", "type": "iso-8601"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin last_modified_date_time: Optional[datetime.datetime] = None, **kwargs ): - super(PolicyAssignmentPropertiesPolicy, self).__init__(**kwargs) + """ + :keyword id: Id of the policy. + :paramtype id: str + :keyword last_modified_date_time: The last modified date time. + :paramtype last_modified_date_time: ~datetime.datetime + """ + super().__init__(**kwargs) self.id = id self.last_modified_by = None self.last_modified_date_time = last_modified_date_time -class PolicyAssignmentPropertiesRoleDefinition(msrest.serialization.Model): +class PolicyAssignmentPropertiesRoleDefinition(_serialization.Model): """Details of role definition. - :param id: Id of the role definition. - :type id: str - :param display_name: Display name of the role definition. - :type display_name: str - :param type: Type of the role definition. - :type type: str + :ivar id: Id of the role definition. + :vartype id: str + :ivar display_name: Display name of the role definition. + :vartype display_name: str + :ivar type: Type of the role definition. + :vartype type: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin display_name: Optional[str] = None, type: Optional[str] = None, **kwargs ): - super(PolicyAssignmentPropertiesRoleDefinition, self).__init__(**kwargs) + """ + :keyword id: Id of the role definition. + :paramtype id: str + :keyword display_name: Display name of the role definition. + :paramtype display_name: str + :keyword type: Type of the role definition. + :paramtype type: str + """ + super().__init__(**kwargs) self.id = id self.display_name = display_name self.type = type -class PolicyAssignmentPropertiesScope(msrest.serialization.Model): +class PolicyAssignmentPropertiesScope(_serialization.Model): """Details of the resource scope. - :param id: Scope id of the resource. - :type id: str - :param display_name: Display name of the resource. - :type display_name: str - :param type: Type of the resource. - :type type: str + :ivar id: Scope id of the resource. + :vartype id: str + :ivar display_name: Display name of the resource. + :vartype display_name: str + :ivar type: Type of the resource. + :vartype type: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin display_name: Optional[str] = None, type: Optional[str] = None, **kwargs ): - super(PolicyAssignmentPropertiesScope, self).__init__(**kwargs) + """ + :keyword id: Scope id of the resource. + :paramtype id: str + :keyword display_name: Display name of the resource. + :paramtype display_name: str + :keyword type: Type of the resource. + :paramtype type: str + """ + super().__init__(**kwargs) self.id = id self.display_name = display_name self.type = type -class PolicyProperties(msrest.serialization.Model): +class PolicyProperties(_serialization.Model): """PolicyProperties. Variables are only populated by the server, and will be ignored when sending a request. @@ -602,89 +725,105 @@ class PolicyProperties(msrest.serialization.Model): """ _validation = { - 'scope': {'readonly': True}, + "scope": {"readonly": True}, } _attribute_map = { - 'scope': {'key': 'scope', 'type': 'PolicyPropertiesScope'}, + "scope": {"key": "scope", "type": "PolicyPropertiesScope"}, } - def __init__( - self, - **kwargs - ): - super(PolicyProperties, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.scope = None -class PolicyPropertiesScope(msrest.serialization.Model): +class PolicyPropertiesScope(_serialization.Model): """Details of the resource scope. - :param id: Scope id of the resource. - :type id: str - :param display_name: Display name of the resource. - :type display_name: str - :param type: Type of the resource. - :type type: str + :ivar id: Scope id of the resource. + :vartype id: str + :ivar display_name: Display name of the resource. + :vartype display_name: str + :ivar type: Type of the resource. + :vartype type: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin display_name: Optional[str] = None, type: Optional[str] = None, **kwargs ): - super(PolicyPropertiesScope, self).__init__(**kwargs) + """ + :keyword id: Scope id of the resource. + :paramtype id: str + :keyword display_name: Display name of the resource. + :paramtype display_name: str + :keyword type: Type of the resource. + :paramtype type: str + """ + super().__init__(**kwargs) self.id = id self.display_name = display_name self.type = type -class Principal(msrest.serialization.Model): +class Principal(_serialization.Model): """The name of the entity last modified it. - :param id: The id of the principal made changes. - :type id: str - :param display_name: The name of the principal made changes. - :type display_name: str - :param type: Type of principal such as user , group etc. - :type type: str - :param email: Email of principal. - :type email: str + :ivar id: The id of the principal made changes. + :vartype id: str + :ivar display_name: The name of the principal made changes. + :vartype display_name: str + :ivar type: Type of principal such as user , group etc. + :vartype type: str + :ivar email: Email of principal. + :vartype email: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "email": {"key": "email", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin display_name: Optional[str] = None, type: Optional[str] = None, email: Optional[str] = None, **kwargs ): - super(Principal, self).__init__(**kwargs) + """ + :keyword id: The id of the principal made changes. + :paramtype id: str + :keyword display_name: The name of the principal made changes. + :paramtype display_name: str + :keyword type: Type of principal such as user , group etc. + :paramtype type: str + :keyword email: Email of principal. + :paramtype email: str + """ + super().__init__(**kwargs) self.id = id self.display_name = display_name self.type = type self.email = email -class RoleAssignment(msrest.serialization.Model): +class RoleAssignment(_serialization.Model): # pylint: disable=too-many-instance-attributes """Role Assignments. Variables are only populated by the server, and will be ignored when sending a request. @@ -697,22 +836,23 @@ class RoleAssignment(msrest.serialization.Model): :vartype type: str :ivar scope: The role assignment scope. :vartype scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param description: Description of role assignment. - :type description: str - :param condition: The conditions on the role assignment. This limits the resources it can be + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :ivar description: Description of role assignment. + :vartype description: str + :ivar condition: The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str :ivar created_on: Time it was created. :vartype created_on: ~datetime.datetime :ivar updated_on: Time it was updated. @@ -721,37 +861,40 @@ class RoleAssignment(msrest.serialization.Model): :vartype created_by: str :ivar updated_by: Id of the user who updated the assignment. :vartype updated_by: str - :param delegated_managed_identity_resource_id: Id of the delegated managed identity resource. - :type delegated_managed_identity_resource_id: str + :ivar delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :vartype delegated_managed_identity_resource_id: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'scope': {'readonly': True}, - 'created_on': {'readonly': True}, - 'updated_on': {'readonly': True}, - 'created_by': {'readonly': True}, - 'updated_by': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "scope": {"readonly": True}, + "created_on": {"readonly": True}, + "updated_on": {"readonly": True}, + "created_by": {"readonly": True}, + "updated_by": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'updated_on': {'key': 'properties.updatedOn', 'type': 'iso-8601'}, - 'created_by': {'key': 'properties.createdBy', 'type': 'str'}, - 'updated_by': {'key': 'properties.updatedBy', 'type': 'str'}, - 'delegated_managed_identity_resource_id': {'key': 'properties.delegatedManagedIdentityResourceId', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "updated_on": {"key": "properties.updatedOn", "type": "iso-8601"}, + "created_by": {"key": "properties.createdBy", "type": "str"}, + "updated_by": {"key": "properties.updatedBy", "type": "str"}, + "delegated_managed_identity_resource_id": { + "key": "properties.delegatedManagedIdentityResourceId", + "type": "str", + }, } def __init__( @@ -759,14 +902,35 @@ def __init__( *, role_definition_id: Optional[str] = None, principal_id: Optional[str] = None, - principal_type: Optional[Union[str, "PrincipalType"]] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, description: Optional[str] = None, condition: Optional[str] = None, condition_version: Optional[str] = None, delegated_managed_identity_resource_id: Optional[str] = None, **kwargs ): - super(RoleAssignment, self).__init__(**kwargs) + """ + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :keyword description: Description of role assignment. + :paramtype description: str + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :paramtype delegated_managed_identity_resource_id: str + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -784,7 +948,7 @@ def __init__( self.delegated_managed_identity_resource_id = delegated_managed_identity_resource_id -class RoleAssignmentCreateParameters(msrest.serialization.Model): +class RoleAssignmentCreateParameters(_serialization.Model): # pylint: disable=too-many-instance-attributes """Role assignment create parameters. Variables are only populated by the server, and will be ignored when sending a request. @@ -793,22 +957,23 @@ class RoleAssignmentCreateParameters(msrest.serialization.Model): :ivar scope: The role assignment scope. :vartype scope: str - :param role_definition_id: Required. The role definition ID. - :type role_definition_id: str - :param principal_id: Required. The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param description: Description of role assignment. - :type description: str - :param condition: The conditions on the role assignment. This limits the resources it can be + :ivar role_definition_id: The role definition ID. Required. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. Required. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :ivar description: Description of role assignment. + :vartype description: str + :ivar condition: The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str :ivar created_on: Time it was created. :vartype created_on: ~datetime.datetime :ivar updated_on: Time it was updated. @@ -817,33 +982,36 @@ class RoleAssignmentCreateParameters(msrest.serialization.Model): :vartype created_by: str :ivar updated_by: Id of the user who updated the assignment. :vartype updated_by: str - :param delegated_managed_identity_resource_id: Id of the delegated managed identity resource. - :type delegated_managed_identity_resource_id: str + :ivar delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :vartype delegated_managed_identity_resource_id: str """ _validation = { - 'scope': {'readonly': True}, - 'role_definition_id': {'required': True}, - 'principal_id': {'required': True}, - 'created_on': {'readonly': True}, - 'updated_on': {'readonly': True}, - 'created_by': {'readonly': True}, - 'updated_by': {'readonly': True}, + "scope": {"readonly": True}, + "role_definition_id": {"required": True}, + "principal_id": {"required": True}, + "created_on": {"readonly": True}, + "updated_on": {"readonly": True}, + "created_by": {"readonly": True}, + "updated_by": {"readonly": True}, } _attribute_map = { - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'updated_on': {'key': 'properties.updatedOn', 'type': 'iso-8601'}, - 'created_by': {'key': 'properties.createdBy', 'type': 'str'}, - 'updated_by': {'key': 'properties.updatedBy', 'type': 'str'}, - 'delegated_managed_identity_resource_id': {'key': 'properties.delegatedManagedIdentityResourceId', 'type': 'str'}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "updated_on": {"key": "properties.updatedOn", "type": "iso-8601"}, + "created_by": {"key": "properties.createdBy", "type": "str"}, + "updated_by": {"key": "properties.updatedBy", "type": "str"}, + "delegated_managed_identity_resource_id": { + "key": "properties.delegatedManagedIdentityResourceId", + "type": "str", + }, } def __init__( @@ -851,14 +1019,35 @@ def __init__( *, role_definition_id: str, principal_id: str, - principal_type: Optional[Union[str, "PrincipalType"]] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, description: Optional[str] = None, condition: Optional[str] = None, condition_version: Optional[str] = None, delegated_managed_identity_resource_id: Optional[str] = None, **kwargs ): - super(RoleAssignmentCreateParameters, self).__init__(**kwargs) + """ + :keyword role_definition_id: The role definition ID. Required. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. Required. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :keyword description: Description of role assignment. + :paramtype description: str + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :paramtype delegated_managed_identity_resource_id: str + """ + super().__init__(**kwargs) self.scope = None self.role_definition_id = role_definition_id self.principal_id = principal_id @@ -873,59 +1062,57 @@ def __init__( self.delegated_managed_identity_resource_id = delegated_managed_identity_resource_id -class RoleAssignmentFilter(msrest.serialization.Model): +class RoleAssignmentFilter(_serialization.Model): """Role Assignments filter. - :param principal_id: Returns role assignment of the specific principal. - :type principal_id: str + :ivar principal_id: Returns role assignment of the specific principal. + :vartype principal_id: str """ _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, } - def __init__( - self, - *, - principal_id: Optional[str] = None, - **kwargs - ): - super(RoleAssignmentFilter, self).__init__(**kwargs) + def __init__(self, *, principal_id: Optional[str] = None, **kwargs): + """ + :keyword principal_id: Returns role assignment of the specific principal. + :paramtype principal_id: str + """ + super().__init__(**kwargs) self.principal_id = principal_id -class RoleAssignmentListResult(msrest.serialization.Model): +class RoleAssignmentListResult(_serialization.Model): """Role assignment list operation result. Variables are only populated by the server, and will be ignored when sending a request. - :param value: Role assignment list. - :type value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] + :ivar value: Role assignment list. + :vartype value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] :ivar next_link: The URL to use for getting the next set of results. :vartype next_link: str """ _validation = { - 'next_link': {'readonly': True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["RoleAssignment"]] = None, - **kwargs - ): - super(RoleAssignmentListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.RoleAssignment"]] = None, **kwargs): + """ + :keyword value: Role assignment list. + :paramtype value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] + """ + super().__init__(**kwargs) self.value = value self.next_link = None -class RoleAssignmentSchedule(msrest.serialization.Model): +class RoleAssignmentSchedule(_serialization.Model): # pylint: disable=too-many-instance-attributes """Role Assignment schedule. Variables are only populated by the server, and will be ignored when sending a request. @@ -936,81 +1123,82 @@ class RoleAssignmentSchedule(msrest.serialization.Model): :vartype name: str :ivar type: The role assignment schedule type. :vartype type: str - :param scope: The role assignment schedule scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param role_assignment_schedule_request_id: The id of roleAssignmentScheduleRequest used to + :ivar scope: The role assignment schedule scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :ivar role_assignment_schedule_request_id: The id of roleAssignmentScheduleRequest used to create this roleAssignmentSchedule. - :type role_assignment_schedule_request_id: str - :param linked_role_eligibility_schedule_id: The id of roleEligibilitySchedule used to activated + :vartype role_assignment_schedule_request_id: str + :ivar linked_role_eligibility_schedule_id: The id of roleEligibilitySchedule used to activated this roleAssignmentSchedule. - :type linked_role_eligibility_schedule_id: str - :param assignment_type: Assignment type of the role assignment schedule. Possible values - include: "Activated", "Assigned". - :type assignment_type: str or + :vartype linked_role_eligibility_schedule_id: str + :ivar assignment_type: Assignment type of the role assignment schedule. Known values are: + "Activated" and "Assigned". + :vartype assignment_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.AssignmentType - :param member_type: Membership type of the role assignment schedule. Possible values include: - "Inherited", "Direct", "Group". - :type member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType - :param status: The status of the role assignment schedule. Possible values include: "Accepted", + :ivar member_type: Membership type of the role assignment schedule. Known values are: + "Inherited", "Direct", and "Group". + :vartype member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType + :ivar status: The status of the role assignment schedule. Known values are: "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". - :type status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status - :param start_date_time: Start DateTime when role assignment schedule. - :type start_date_time: ~datetime.datetime - :param end_date_time: End DateTime when role assignment schedule. - :type end_date_time: ~datetime.datetime - :param condition: The conditions on the role assignment. This limits the resources it can be + "ScheduleCreated", and "PendingExternalProvisioning". + :vartype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status + :ivar start_date_time: Start DateTime when role assignment schedule. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: End DateTime when role assignment schedule. + :vartype end_date_time: ~datetime.datetime + :ivar condition: The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param created_on: DateTime when role assignment schedule was created. - :type created_on: ~datetime.datetime - :param updated_on: DateTime when role assignment schedule was modified. - :type updated_on: ~datetime.datetime - :param expanded_properties: Additional properties of principal, scope and role definition. - :type expanded_properties: + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: DateTime when role assignment schedule was created. + :vartype created_on: ~datetime.datetime + :ivar updated_on: DateTime when role assignment schedule was modified. + :vartype updated_on: ~datetime.datetime + :ivar expanded_properties: Additional properties of principal, scope and role definition. + :vartype expanded_properties: ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'role_assignment_schedule_request_id': {'key': 'properties.roleAssignmentScheduleRequestId', 'type': 'str'}, - 'linked_role_eligibility_schedule_id': {'key': 'properties.linkedRoleEligibilityScheduleId', 'type': 'str'}, - 'assignment_type': {'key': 'properties.assignmentType', 'type': 'str'}, - 'member_type': {'key': 'properties.memberType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'updated_on': {'key': 'properties.updatedOn', 'type': 'iso-8601'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "role_assignment_schedule_request_id": {"key": "properties.roleAssignmentScheduleRequestId", "type": "str"}, + "linked_role_eligibility_schedule_id": {"key": "properties.linkedRoleEligibilityScheduleId", "type": "str"}, + "assignment_type": {"key": "properties.assignmentType", "type": "str"}, + "member_type": {"key": "properties.memberType", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "updated_on": {"key": "properties.updatedOn", "type": "iso-8601"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, } def __init__( @@ -1019,22 +1207,72 @@ def __init__( scope: Optional[str] = None, role_definition_id: Optional[str] = None, principal_id: Optional[str] = None, - principal_type: Optional[Union[str, "PrincipalType"]] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, role_assignment_schedule_request_id: Optional[str] = None, linked_role_eligibility_schedule_id: Optional[str] = None, - assignment_type: Optional[Union[str, "AssignmentType"]] = None, - member_type: Optional[Union[str, "MemberType"]] = None, - status: Optional[Union[str, "Status"]] = None, + assignment_type: Optional[Union[str, "_models.AssignmentType"]] = None, + member_type: Optional[Union[str, "_models.MemberType"]] = None, + status: Optional[Union[str, "_models.Status"]] = None, start_date_time: Optional[datetime.datetime] = None, end_date_time: Optional[datetime.datetime] = None, condition: Optional[str] = None, condition_version: Optional[str] = None, created_on: Optional[datetime.datetime] = None, updated_on: Optional[datetime.datetime] = None, - expanded_properties: Optional["ExpandedProperties"] = None, + expanded_properties: Optional["_models.ExpandedProperties"] = None, **kwargs ): - super(RoleAssignmentSchedule, self).__init__(**kwargs) + """ + :keyword scope: The role assignment schedule scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :keyword role_assignment_schedule_request_id: The id of roleAssignmentScheduleRequest used to + create this roleAssignmentSchedule. + :paramtype role_assignment_schedule_request_id: str + :keyword linked_role_eligibility_schedule_id: The id of roleEligibilitySchedule used to + activated this roleAssignmentSchedule. + :paramtype linked_role_eligibility_schedule_id: str + :keyword assignment_type: Assignment type of the role assignment schedule. Known values are: + "Activated" and "Assigned". + :paramtype assignment_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.AssignmentType + :keyword member_type: Membership type of the role assignment schedule. Known values are: + "Inherited", "Direct", and "Group". + :paramtype member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType + :keyword status: The status of the role assignment schedule. Known values are: "Accepted", + "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :paramtype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status + :keyword start_date_time: Start DateTime when role assignment schedule. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: End DateTime when role assignment schedule. + :paramtype end_date_time: ~datetime.datetime + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword created_on: DateTime when role assignment schedule was created. + :paramtype created_on: ~datetime.datetime + :keyword updated_on: DateTime when role assignment schedule was modified. + :paramtype updated_on: ~datetime.datetime + :keyword expanded_properties: Additional properties of principal, scope and role definition. + :paramtype expanded_properties: + ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -1056,21 +1294,21 @@ def __init__( self.expanded_properties = expanded_properties -class RoleAssignmentScheduleFilter(msrest.serialization.Model): +class RoleAssignmentScheduleFilter(_serialization.Model): """Role assignment schedule filter. - :param principal_id: Returns role assignment schedule of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role assignment schedule of the specific role definition. - :type role_definition_id: str - :param status: Returns role assignment schedule instances of the specific status. - :type status: str + :ivar principal_id: Returns role assignment schedule of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role assignment schedule of the specific role definition. + :vartype role_definition_id: str + :ivar status: Returns role assignment schedule instances of the specific status. + :vartype status: str """ _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "status": {"key": "status", "type": "str"}, } def __init__( @@ -1081,13 +1319,21 @@ def __init__( status: Optional[str] = None, **kwargs ): - super(RoleAssignmentScheduleFilter, self).__init__(**kwargs) + """ + :keyword principal_id: Returns role assignment schedule of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role assignment schedule of the specific role definition. + :paramtype role_definition_id: str + :keyword status: Returns role assignment schedule instances of the specific status. + :paramtype status: str + """ + super().__init__(**kwargs) self.principal_id = principal_id self.role_definition_id = role_definition_id self.status = status -class RoleAssignmentScheduleInstance(msrest.serialization.Model): +class RoleAssignmentScheduleInstance(_serialization.Model): # pylint: disable=too-many-instance-attributes """Information about current or upcoming role assignment schedule instance. Variables are only populated by the server, and will be ignored when sending a request. @@ -1098,83 +1344,87 @@ class RoleAssignmentScheduleInstance(msrest.serialization.Model): :vartype name: str :ivar type: The role assignment schedule instance type. :vartype type: str - :param scope: The role assignment schedule scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param role_assignment_schedule_id: Id of the master role assignment schedule. - :type role_assignment_schedule_id: str - :param origin_role_assignment_id: Role Assignment Id in external system. - :type origin_role_assignment_id: str - :param status: The status of the role assignment schedule instance. Possible values include: + :ivar scope: The role assignment schedule scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :ivar role_assignment_schedule_id: Id of the master role assignment schedule. + :vartype role_assignment_schedule_id: str + :ivar origin_role_assignment_id: Role Assignment Id in external system. + :vartype origin_role_assignment_id: str + :ivar status: The status of the role assignment schedule instance. Known values are: "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". - :type status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status - :param start_date_time: The startDateTime of the role assignment schedule instance. - :type start_date_time: ~datetime.datetime - :param end_date_time: The endDateTime of the role assignment schedule instance. - :type end_date_time: ~datetime.datetime - :param linked_role_eligibility_schedule_id: roleEligibilityScheduleId used to activate. - :type linked_role_eligibility_schedule_id: str - :param linked_role_eligibility_schedule_instance_id: roleEligibilityScheduleInstanceId linked - to this roleAssignmentScheduleInstance. - :type linked_role_eligibility_schedule_instance_id: str - :param assignment_type: Assignment type of the role assignment schedule. Possible values - include: "Activated", "Assigned". - :type assignment_type: str or + "ScheduleCreated", and "PendingExternalProvisioning". + :vartype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status + :ivar start_date_time: The startDateTime of the role assignment schedule instance. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: The endDateTime of the role assignment schedule instance. + :vartype end_date_time: ~datetime.datetime + :ivar linked_role_eligibility_schedule_id: roleEligibilityScheduleId used to activate. + :vartype linked_role_eligibility_schedule_id: str + :ivar linked_role_eligibility_schedule_instance_id: roleEligibilityScheduleInstanceId linked to + this roleAssignmentScheduleInstance. + :vartype linked_role_eligibility_schedule_instance_id: str + :ivar assignment_type: Assignment type of the role assignment schedule. Known values are: + "Activated" and "Assigned". + :vartype assignment_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.AssignmentType - :param member_type: Membership type of the role assignment schedule. Possible values include: - "Inherited", "Direct", "Group". - :type member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType - :param condition: The conditions on the role assignment. This limits the resources it can be + :ivar member_type: Membership type of the role assignment schedule. Known values are: + "Inherited", "Direct", and "Group". + :vartype member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType + :ivar condition: The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param created_on: DateTime when role assignment schedule was created. - :type created_on: ~datetime.datetime - :param expanded_properties: Additional properties of principal, scope and role definition. - :type expanded_properties: + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: DateTime when role assignment schedule was created. + :vartype created_on: ~datetime.datetime + :ivar expanded_properties: Additional properties of principal, scope and role definition. + :vartype expanded_properties: ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'role_assignment_schedule_id': {'key': 'properties.roleAssignmentScheduleId', 'type': 'str'}, - 'origin_role_assignment_id': {'key': 'properties.originRoleAssignmentId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, - 'linked_role_eligibility_schedule_id': {'key': 'properties.linkedRoleEligibilityScheduleId', 'type': 'str'}, - 'linked_role_eligibility_schedule_instance_id': {'key': 'properties.linkedRoleEligibilityScheduleInstanceId', 'type': 'str'}, - 'assignment_type': {'key': 'properties.assignmentType', 'type': 'str'}, - 'member_type': {'key': 'properties.memberType', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "role_assignment_schedule_id": {"key": "properties.roleAssignmentScheduleId", "type": "str"}, + "origin_role_assignment_id": {"key": "properties.originRoleAssignmentId", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, + "linked_role_eligibility_schedule_id": {"key": "properties.linkedRoleEligibilityScheduleId", "type": "str"}, + "linked_role_eligibility_schedule_instance_id": { + "key": "properties.linkedRoleEligibilityScheduleInstanceId", + "type": "str", + }, + "assignment_type": {"key": "properties.assignmentType", "type": "str"}, + "member_type": {"key": "properties.memberType", "type": "str"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, } def __init__( @@ -1183,23 +1433,74 @@ def __init__( scope: Optional[str] = None, role_definition_id: Optional[str] = None, principal_id: Optional[str] = None, - principal_type: Optional[Union[str, "PrincipalType"]] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, role_assignment_schedule_id: Optional[str] = None, origin_role_assignment_id: Optional[str] = None, - status: Optional[Union[str, "Status"]] = None, + status: Optional[Union[str, "_models.Status"]] = None, start_date_time: Optional[datetime.datetime] = None, end_date_time: Optional[datetime.datetime] = None, linked_role_eligibility_schedule_id: Optional[str] = None, linked_role_eligibility_schedule_instance_id: Optional[str] = None, - assignment_type: Optional[Union[str, "AssignmentType"]] = None, - member_type: Optional[Union[str, "MemberType"]] = None, + assignment_type: Optional[Union[str, "_models.AssignmentType"]] = None, + member_type: Optional[Union[str, "_models.MemberType"]] = None, condition: Optional[str] = None, condition_version: Optional[str] = None, created_on: Optional[datetime.datetime] = None, - expanded_properties: Optional["ExpandedProperties"] = None, + expanded_properties: Optional["_models.ExpandedProperties"] = None, **kwargs ): - super(RoleAssignmentScheduleInstance, self).__init__(**kwargs) + """ + :keyword scope: The role assignment schedule scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :keyword role_assignment_schedule_id: Id of the master role assignment schedule. + :paramtype role_assignment_schedule_id: str + :keyword origin_role_assignment_id: Role Assignment Id in external system. + :paramtype origin_role_assignment_id: str + :keyword status: The status of the role assignment schedule instance. Known values are: + "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :paramtype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status + :keyword start_date_time: The startDateTime of the role assignment schedule instance. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: The endDateTime of the role assignment schedule instance. + :paramtype end_date_time: ~datetime.datetime + :keyword linked_role_eligibility_schedule_id: roleEligibilityScheduleId used to activate. + :paramtype linked_role_eligibility_schedule_id: str + :keyword linked_role_eligibility_schedule_instance_id: roleEligibilityScheduleInstanceId linked + to this roleAssignmentScheduleInstance. + :paramtype linked_role_eligibility_schedule_instance_id: str + :keyword assignment_type: Assignment type of the role assignment schedule. Known values are: + "Activated" and "Assigned". + :paramtype assignment_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.AssignmentType + :keyword member_type: Membership type of the role assignment schedule. Known values are: + "Inherited", "Direct", and "Group". + :paramtype member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword created_on: DateTime when role assignment schedule was created. + :paramtype created_on: ~datetime.datetime + :keyword expanded_properties: Additional properties of principal, scope and role definition. + :paramtype expanded_properties: + ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -1222,26 +1523,26 @@ def __init__( self.expanded_properties = expanded_properties -class RoleAssignmentScheduleInstanceFilter(msrest.serialization.Model): +class RoleAssignmentScheduleInstanceFilter(_serialization.Model): """Role assignment schedule instance filter. - :param principal_id: Returns role assignment schedule instances of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role assignment schedule instances of the specific role + :ivar principal_id: Returns role assignment schedule instances of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role assignment schedule instances of the specific role definition. - :type role_definition_id: str - :param status: Returns role assignment schedule instances of the specific status. - :type status: str - :param role_assignment_schedule_id: Returns role assignment schedule instances belonging to a + :vartype role_definition_id: str + :ivar status: Returns role assignment schedule instances of the specific status. + :vartype status: str + :ivar role_assignment_schedule_id: Returns role assignment schedule instances belonging to a specific role assignment schedule. - :type role_assignment_schedule_id: str + :vartype role_assignment_schedule_id: str """ _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'role_assignment_schedule_id': {'key': 'roleAssignmentScheduleId', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "role_assignment_schedule_id": {"key": "roleAssignmentScheduleId", "type": "str"}, } def __init__( @@ -1253,67 +1554,94 @@ def __init__( role_assignment_schedule_id: Optional[str] = None, **kwargs ): - super(RoleAssignmentScheduleInstanceFilter, self).__init__(**kwargs) + """ + :keyword principal_id: Returns role assignment schedule instances of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role assignment schedule instances of the specific role + definition. + :paramtype role_definition_id: str + :keyword status: Returns role assignment schedule instances of the specific status. + :paramtype status: str + :keyword role_assignment_schedule_id: Returns role assignment schedule instances belonging to a + specific role assignment schedule. + :paramtype role_assignment_schedule_id: str + """ + super().__init__(**kwargs) self.principal_id = principal_id self.role_definition_id = role_definition_id self.status = status self.role_assignment_schedule_id = role_assignment_schedule_id -class RoleAssignmentScheduleInstanceListResult(msrest.serialization.Model): +class RoleAssignmentScheduleInstanceListResult(_serialization.Model): """Role assignment schedule instance list operation result. - :param value: Role assignment schedule instance list. - :type value: + :ivar value: Role assignment schedule instance list. + :vartype value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleInstance] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignmentScheduleInstance]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleAssignmentScheduleInstance]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["RoleAssignmentScheduleInstance"]] = None, + value: Optional[List["_models.RoleAssignmentScheduleInstance"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleAssignmentScheduleInstanceListResult, self).__init__(**kwargs) + """ + :keyword value: Role assignment schedule instance list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleInstance] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class RoleAssignmentScheduleListResult(msrest.serialization.Model): +class RoleAssignmentScheduleListResult(_serialization.Model): """Role assignment schedule list operation result. - :param value: Role assignment schedule list. - :type value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentSchedule] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Role assignment schedule list. + :vartype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentSchedule] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignmentSchedule]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleAssignmentSchedule]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["RoleAssignmentSchedule"]] = None, + value: Optional[List["_models.RoleAssignmentSchedule"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleAssignmentScheduleListResult, self).__init__(**kwargs) + """ + :keyword value: Role assignment schedule list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentSchedule] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class RoleAssignmentScheduleRequest(msrest.serialization.Model): +class RoleAssignmentScheduleRequest(_serialization.Model): # pylint: disable=too-many-instance-attributes """Role Assignment schedule request. Variables are only populated by the server, and will be ignored when sending a request. @@ -1326,51 +1654,51 @@ class RoleAssignmentScheduleRequest(msrest.serialization.Model): :vartype type: str :ivar scope: The role assignment schedule request scope. :vartype scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :ivar principal_type: The principal type of the assigned principal ID. Possible values include: - "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". :vartype principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param request_type: The type of the role assignment schedule request. Eg: SelfActivate, - AdminAssign etc. Possible values include: "AdminAssign", "AdminRemove", "AdminUpdate", - "AdminExtend", "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", "SelfRenew". - :type request_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RequestType - :ivar status: The status of the role assignment schedule request. Possible values include: - "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + :ivar request_type: The type of the role assignment schedule request. Eg: SelfActivate, + AdminAssign etc. Known values are: "AdminAssign", "AdminRemove", "AdminUpdate", "AdminExtend", + "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", and "SelfRenew". + :vartype request_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RequestType + :ivar status: The status of the role assignment schedule request. Known values are: "Accepted", + "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". + "ScheduleCreated", and "PendingExternalProvisioning". :vartype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status :ivar approval_id: The approvalId of the role assignment schedule request. :vartype approval_id: str - :param target_role_assignment_schedule_id: The resultant role assignment schedule id or the - role assignment schedule id being updated. - :type target_role_assignment_schedule_id: str - :param target_role_assignment_schedule_instance_id: The role assignment schedule instance id + :ivar target_role_assignment_schedule_id: The resultant role assignment schedule id or the role + assignment schedule id being updated. + :vartype target_role_assignment_schedule_id: str + :ivar target_role_assignment_schedule_instance_id: The role assignment schedule instance id being updated. - :type target_role_assignment_schedule_instance_id: str - :param schedule_info: Schedule info of the role assignment schedule. - :type schedule_info: + :vartype target_role_assignment_schedule_instance_id: str + :ivar schedule_info: Schedule info of the role assignment schedule. + :vartype schedule_info: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequestPropertiesScheduleInfo - :param linked_role_eligibility_schedule_id: The linked role eligibility schedule id - to + :ivar linked_role_eligibility_schedule_id: The linked role eligibility schedule id - to activate an eligibility. - :type linked_role_eligibility_schedule_id: str - :param justification: Justification for the role assignment. - :type justification: str - :param ticket_info: Ticket Info of the role assignment. - :type ticket_info: + :vartype linked_role_eligibility_schedule_id: str + :ivar justification: Justification for the role assignment. + :vartype justification: str + :ivar ticket_info: Ticket Info of the role assignment. + :vartype ticket_info: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequestPropertiesTicketInfo - :param condition: The conditions on the role assignment. This limits the resources it can be + :ivar condition: The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str :ivar created_on: DateTime when role assignment schedule request was created. :vartype created_on: ~datetime.datetime :ivar requestor_id: Id of the user who created this request. @@ -1381,40 +1709,46 @@ class RoleAssignmentScheduleRequest(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'scope': {'readonly': True}, - 'principal_type': {'readonly': True}, - 'status': {'readonly': True}, - 'approval_id': {'readonly': True}, - 'created_on': {'readonly': True}, - 'requestor_id': {'readonly': True}, - 'expanded_properties': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "scope": {"readonly": True}, + "principal_type": {"readonly": True}, + "status": {"readonly": True}, + "approval_id": {"readonly": True}, + "created_on": {"readonly": True}, + "requestor_id": {"readonly": True}, + "expanded_properties": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'request_type': {'key': 'properties.requestType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'approval_id': {'key': 'properties.approvalId', 'type': 'str'}, - 'target_role_assignment_schedule_id': {'key': 'properties.targetRoleAssignmentScheduleId', 'type': 'str'}, - 'target_role_assignment_schedule_instance_id': {'key': 'properties.targetRoleAssignmentScheduleInstanceId', 'type': 'str'}, - 'schedule_info': {'key': 'properties.scheduleInfo', 'type': 'RoleAssignmentScheduleRequestPropertiesScheduleInfo'}, - 'linked_role_eligibility_schedule_id': {'key': 'properties.linkedRoleEligibilityScheduleId', 'type': 'str'}, - 'justification': {'key': 'properties.justification', 'type': 'str'}, - 'ticket_info': {'key': 'properties.ticketInfo', 'type': 'RoleAssignmentScheduleRequestPropertiesTicketInfo'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'requestor_id': {'key': 'properties.requestorId', 'type': 'str'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "request_type": {"key": "properties.requestType", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "approval_id": {"key": "properties.approvalId", "type": "str"}, + "target_role_assignment_schedule_id": {"key": "properties.targetRoleAssignmentScheduleId", "type": "str"}, + "target_role_assignment_schedule_instance_id": { + "key": "properties.targetRoleAssignmentScheduleInstanceId", + "type": "str", + }, + "schedule_info": { + "key": "properties.scheduleInfo", + "type": "RoleAssignmentScheduleRequestPropertiesScheduleInfo", + }, + "linked_role_eligibility_schedule_id": {"key": "properties.linkedRoleEligibilityScheduleId", "type": "str"}, + "justification": {"key": "properties.justification", "type": "str"}, + "ticket_info": {"key": "properties.ticketInfo", "type": "RoleAssignmentScheduleRequestPropertiesTicketInfo"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "requestor_id": {"key": "properties.requestorId", "type": "str"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, } def __init__( @@ -1422,18 +1756,53 @@ def __init__( *, role_definition_id: Optional[str] = None, principal_id: Optional[str] = None, - request_type: Optional[Union[str, "RequestType"]] = None, + request_type: Optional[Union[str, "_models.RequestType"]] = None, target_role_assignment_schedule_id: Optional[str] = None, target_role_assignment_schedule_instance_id: Optional[str] = None, - schedule_info: Optional["RoleAssignmentScheduleRequestPropertiesScheduleInfo"] = None, + schedule_info: Optional["_models.RoleAssignmentScheduleRequestPropertiesScheduleInfo"] = None, linked_role_eligibility_schedule_id: Optional[str] = None, justification: Optional[str] = None, - ticket_info: Optional["RoleAssignmentScheduleRequestPropertiesTicketInfo"] = None, + ticket_info: Optional["_models.RoleAssignmentScheduleRequestPropertiesTicketInfo"] = None, condition: Optional[str] = None, condition_version: Optional[str] = None, **kwargs ): - super(RoleAssignmentScheduleRequest, self).__init__(**kwargs) + """ + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword request_type: The type of the role assignment schedule request. Eg: SelfActivate, + AdminAssign etc. Known values are: "AdminAssign", "AdminRemove", "AdminUpdate", "AdminExtend", + "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", and "SelfRenew". + :paramtype request_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.RequestType + :keyword target_role_assignment_schedule_id: The resultant role assignment schedule id or the + role assignment schedule id being updated. + :paramtype target_role_assignment_schedule_id: str + :keyword target_role_assignment_schedule_instance_id: The role assignment schedule instance id + being updated. + :paramtype target_role_assignment_schedule_instance_id: str + :keyword schedule_info: Schedule info of the role assignment schedule. + :paramtype schedule_info: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequestPropertiesScheduleInfo + :keyword linked_role_eligibility_schedule_id: The linked role eligibility schedule id - to + activate an eligibility. + :paramtype linked_role_eligibility_schedule_id: str + :keyword justification: Justification for the role assignment. + :paramtype justification: str + :keyword ticket_info: Ticket Info of the role assignment. + :paramtype ticket_info: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequestPropertiesTicketInfo + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -1457,24 +1826,24 @@ def __init__( self.expanded_properties = None -class RoleAssignmentScheduleRequestFilter(msrest.serialization.Model): +class RoleAssignmentScheduleRequestFilter(_serialization.Model): """Role assignment schedule request filter. - :param principal_id: Returns role assignment requests of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role assignment requests of the specific role definition. - :type role_definition_id: str - :param requestor_id: Returns role assignment requests created by specific principal. - :type requestor_id: str - :param status: Returns role assignment requests of specific status. - :type status: str + :ivar principal_id: Returns role assignment requests of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role assignment requests of the specific role definition. + :vartype role_definition_id: str + :ivar requestor_id: Returns role assignment requests created by specific principal. + :vartype requestor_id: str + :ivar status: Returns role assignment requests of specific status. + :vartype status: str """ _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'requestor_id': {'key': 'requestorId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "requestor_id": {"key": "requestorId", "type": "str"}, + "status": {"key": "status", "type": "str"}, } def __init__( @@ -1486,126 +1855,159 @@ def __init__( status: Optional[str] = None, **kwargs ): - super(RoleAssignmentScheduleRequestFilter, self).__init__(**kwargs) + """ + :keyword principal_id: Returns role assignment requests of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role assignment requests of the specific role definition. + :paramtype role_definition_id: str + :keyword requestor_id: Returns role assignment requests created by specific principal. + :paramtype requestor_id: str + :keyword status: Returns role assignment requests of specific status. + :paramtype status: str + """ + super().__init__(**kwargs) self.principal_id = principal_id self.role_definition_id = role_definition_id self.requestor_id = requestor_id self.status = status -class RoleAssignmentScheduleRequestListResult(msrest.serialization.Model): +class RoleAssignmentScheduleRequestListResult(_serialization.Model): """Role assignment schedule request list operation result. - :param value: Role assignment schedule request list. - :type value: + :ivar value: Role assignment schedule request list. + :vartype value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignmentScheduleRequest]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleAssignmentScheduleRequest]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["RoleAssignmentScheduleRequest"]] = None, + value: Optional[List["_models.RoleAssignmentScheduleRequest"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleAssignmentScheduleRequestListResult, self).__init__(**kwargs) + """ + :keyword value: Role assignment schedule request list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class RoleAssignmentScheduleRequestPropertiesScheduleInfo(msrest.serialization.Model): +class RoleAssignmentScheduleRequestPropertiesScheduleInfo(_serialization.Model): """Schedule info of the role assignment schedule. - :param start_date_time: Start DateTime of the role assignment schedule. - :type start_date_time: ~datetime.datetime - :param expiration: Expiration of the role assignment schedule. - :type expiration: + :ivar start_date_time: Start DateTime of the role assignment schedule. + :vartype start_date_time: ~datetime.datetime + :ivar expiration: Expiration of the role assignment schedule. + :vartype expiration: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration """ _attribute_map = { - 'start_date_time': {'key': 'startDateTime', 'type': 'iso-8601'}, - 'expiration': {'key': 'expiration', 'type': 'RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration'}, + "start_date_time": {"key": "startDateTime", "type": "iso-8601"}, + "expiration": {"key": "expiration", "type": "RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration"}, } def __init__( self, *, start_date_time: Optional[datetime.datetime] = None, - expiration: Optional["RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration"] = None, + expiration: Optional["_models.RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration"] = None, **kwargs ): - super(RoleAssignmentScheduleRequestPropertiesScheduleInfo, self).__init__(**kwargs) + """ + :keyword start_date_time: Start DateTime of the role assignment schedule. + :paramtype start_date_time: ~datetime.datetime + :keyword expiration: Expiration of the role assignment schedule. + :paramtype expiration: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration + """ + super().__init__(**kwargs) self.start_date_time = start_date_time self.expiration = expiration -class RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration(msrest.serialization.Model): +class RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration(_serialization.Model): """Expiration of the role assignment schedule. - :param type: Type of the role assignment schedule expiration. Possible values include: - "AfterDuration", "AfterDateTime", "NoExpiration". - :type type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Type - :param end_date_time: End DateTime of the role assignment schedule. - :type end_date_time: ~datetime.datetime - :param duration: Duration of the role assignment schedule in TimeSpan. - :type duration: str + :ivar type: Type of the role assignment schedule expiration. Known values are: "AfterDuration", + "AfterDateTime", and "NoExpiration". + :vartype type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Type + :ivar end_date_time: End DateTime of the role assignment schedule. + :vartype end_date_time: ~datetime.datetime + :ivar duration: Duration of the role assignment schedule in TimeSpan. + :vartype duration: str """ _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'end_date_time': {'key': 'endDateTime', 'type': 'iso-8601'}, - 'duration': {'key': 'duration', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "end_date_time": {"key": "endDateTime", "type": "iso-8601"}, + "duration": {"key": "duration", "type": "str"}, } def __init__( self, *, - type: Optional[Union[str, "Type"]] = None, + type: Optional[Union[str, "_models.Type"]] = None, end_date_time: Optional[datetime.datetime] = None, duration: Optional[str] = None, **kwargs ): - super(RoleAssignmentScheduleRequestPropertiesScheduleInfoExpiration, self).__init__(**kwargs) + """ + :keyword type: Type of the role assignment schedule expiration. Known values are: + "AfterDuration", "AfterDateTime", and "NoExpiration". + :paramtype type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Type + :keyword end_date_time: End DateTime of the role assignment schedule. + :paramtype end_date_time: ~datetime.datetime + :keyword duration: Duration of the role assignment schedule in TimeSpan. + :paramtype duration: str + """ + super().__init__(**kwargs) self.type = type self.end_date_time = end_date_time self.duration = duration -class RoleAssignmentScheduleRequestPropertiesTicketInfo(msrest.serialization.Model): +class RoleAssignmentScheduleRequestPropertiesTicketInfo(_serialization.Model): """Ticket Info of the role assignment. - :param ticket_number: Ticket number for the role assignment. - :type ticket_number: str - :param ticket_system: Ticket system name for the role assignment. - :type ticket_system: str + :ivar ticket_number: Ticket number for the role assignment. + :vartype ticket_number: str + :ivar ticket_system: Ticket system name for the role assignment. + :vartype ticket_system: str """ _attribute_map = { - 'ticket_number': {'key': 'ticketNumber', 'type': 'str'}, - 'ticket_system': {'key': 'ticketSystem', 'type': 'str'}, - } - - def __init__( - self, - *, - ticket_number: Optional[str] = None, - ticket_system: Optional[str] = None, - **kwargs - ): - super(RoleAssignmentScheduleRequestPropertiesTicketInfo, self).__init__(**kwargs) + "ticket_number": {"key": "ticketNumber", "type": "str"}, + "ticket_system": {"key": "ticketSystem", "type": "str"}, + } + + def __init__(self, *, ticket_number: Optional[str] = None, ticket_system: Optional[str] = None, **kwargs): + """ + :keyword ticket_number: Ticket number for the role assignment. + :paramtype ticket_number: str + :keyword ticket_system: Ticket system name for the role assignment. + :paramtype ticket_system: str + """ + super().__init__(**kwargs) self.ticket_number = ticket_number self.ticket_system = ticket_system -class RoleEligibilitySchedule(msrest.serialization.Model): +class RoleEligibilitySchedule(_serialization.Model): # pylint: disable=too-many-instance-attributes """Role eligibility schedule. Variables are only populated by the server, and will be ignored when sending a request. @@ -1616,72 +2018,73 @@ class RoleEligibilitySchedule(msrest.serialization.Model): :vartype name: str :ivar type: The role eligibility schedule type. :vartype type: str - :param scope: The role eligibility schedule scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param role_eligibility_schedule_request_id: The id of roleEligibilityScheduleRequest used to + :ivar scope: The role eligibility schedule scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :ivar role_eligibility_schedule_request_id: The id of roleEligibilityScheduleRequest used to create this roleAssignmentSchedule. - :type role_eligibility_schedule_request_id: str - :param member_type: Membership type of the role eligibility schedule. Possible values include: - "Inherited", "Direct", "Group". - :type member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType - :param status: The status of the role eligibility schedule. Possible values include: - "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + :vartype role_eligibility_schedule_request_id: str + :ivar member_type: Membership type of the role eligibility schedule. Known values are: + "Inherited", "Direct", and "Group". + :vartype member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType + :ivar status: The status of the role eligibility schedule. Known values are: "Accepted", + "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". - :type status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status - :param start_date_time: Start DateTime when role eligibility schedule. - :type start_date_time: ~datetime.datetime - :param end_date_time: End DateTime when role eligibility schedule. - :type end_date_time: ~datetime.datetime - :param condition: The conditions on the role assignment. This limits the resources it can be + "ScheduleCreated", and "PendingExternalProvisioning". + :vartype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status + :ivar start_date_time: Start DateTime when role eligibility schedule. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: End DateTime when role eligibility schedule. + :vartype end_date_time: ~datetime.datetime + :ivar condition: The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param created_on: DateTime when role eligibility schedule was created. - :type created_on: ~datetime.datetime - :param updated_on: DateTime when role eligibility schedule was modified. - :type updated_on: ~datetime.datetime - :param expanded_properties: Additional properties of principal, scope and role definition. - :type expanded_properties: + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: DateTime when role eligibility schedule was created. + :vartype created_on: ~datetime.datetime + :ivar updated_on: DateTime when role eligibility schedule was modified. + :vartype updated_on: ~datetime.datetime + :ivar expanded_properties: Additional properties of principal, scope and role definition. + :vartype expanded_properties: ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'role_eligibility_schedule_request_id': {'key': 'properties.roleEligibilityScheduleRequestId', 'type': 'str'}, - 'member_type': {'key': 'properties.memberType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'updated_on': {'key': 'properties.updatedOn', 'type': 'iso-8601'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "role_eligibility_schedule_request_id": {"key": "properties.roleEligibilityScheduleRequestId", "type": "str"}, + "member_type": {"key": "properties.memberType", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "updated_on": {"key": "properties.updatedOn", "type": "iso-8601"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, } def __init__( @@ -1690,20 +2093,63 @@ def __init__( scope: Optional[str] = None, role_definition_id: Optional[str] = None, principal_id: Optional[str] = None, - principal_type: Optional[Union[str, "PrincipalType"]] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, role_eligibility_schedule_request_id: Optional[str] = None, - member_type: Optional[Union[str, "MemberType"]] = None, - status: Optional[Union[str, "Status"]] = None, + member_type: Optional[Union[str, "_models.MemberType"]] = None, + status: Optional[Union[str, "_models.Status"]] = None, start_date_time: Optional[datetime.datetime] = None, end_date_time: Optional[datetime.datetime] = None, condition: Optional[str] = None, condition_version: Optional[str] = None, created_on: Optional[datetime.datetime] = None, updated_on: Optional[datetime.datetime] = None, - expanded_properties: Optional["ExpandedProperties"] = None, + expanded_properties: Optional["_models.ExpandedProperties"] = None, **kwargs ): - super(RoleEligibilitySchedule, self).__init__(**kwargs) + """ + :keyword scope: The role eligibility schedule scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :keyword role_eligibility_schedule_request_id: The id of roleEligibilityScheduleRequest used to + create this roleAssignmentSchedule. + :paramtype role_eligibility_schedule_request_id: str + :keyword member_type: Membership type of the role eligibility schedule. Known values are: + "Inherited", "Direct", and "Group". + :paramtype member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType + :keyword status: The status of the role eligibility schedule. Known values are: "Accepted", + "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :paramtype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status + :keyword start_date_time: Start DateTime when role eligibility schedule. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: End DateTime when role eligibility schedule. + :paramtype end_date_time: ~datetime.datetime + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword created_on: DateTime when role eligibility schedule was created. + :paramtype created_on: ~datetime.datetime + :keyword updated_on: DateTime when role eligibility schedule was modified. + :paramtype updated_on: ~datetime.datetime + :keyword expanded_properties: Additional properties of principal, scope and role definition. + :paramtype expanded_properties: + ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -1723,21 +2169,21 @@ def __init__( self.expanded_properties = expanded_properties -class RoleEligibilityScheduleFilter(msrest.serialization.Model): +class RoleEligibilityScheduleFilter(_serialization.Model): """Role eligibility schedule filter. - :param principal_id: Returns role eligibility schedule of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role eligibility schedule of the specific role definition. - :type role_definition_id: str - :param status: Returns role eligibility schedule of the specific status. - :type status: str + :ivar principal_id: Returns role eligibility schedule of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role eligibility schedule of the specific role definition. + :vartype role_definition_id: str + :ivar status: Returns role eligibility schedule of the specific status. + :vartype status: str """ _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "status": {"key": "status", "type": "str"}, } def __init__( @@ -1748,13 +2194,21 @@ def __init__( status: Optional[str] = None, **kwargs ): - super(RoleEligibilityScheduleFilter, self).__init__(**kwargs) + """ + :keyword principal_id: Returns role eligibility schedule of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role eligibility schedule of the specific role definition. + :paramtype role_definition_id: str + :keyword status: Returns role eligibility schedule of the specific status. + :paramtype status: str + """ + super().__init__(**kwargs) self.principal_id = principal_id self.role_definition_id = role_definition_id self.status = status -class RoleEligibilityScheduleInstance(msrest.serialization.Model): +class RoleEligibilityScheduleInstance(_serialization.Model): # pylint: disable=too-many-instance-attributes """Information about current or upcoming role eligibility schedule instance. Variables are only populated by the server, and will be ignored when sending a request. @@ -1765,68 +2219,69 @@ class RoleEligibilityScheduleInstance(msrest.serialization.Model): :vartype name: str :ivar type: The role eligibility schedule instance type. :vartype type: str - :param scope: The role eligibility schedule scope. - :type scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :param principal_type: The principal type of the assigned principal ID. Possible values - include: "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". - :type principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param role_eligibility_schedule_id: Id of the master role eligibility schedule. - :type role_eligibility_schedule_id: str - :param status: The status of the role eligibility schedule instance. Possible values include: + :ivar scope: The role eligibility schedule scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :ivar role_eligibility_schedule_id: Id of the master role eligibility schedule. + :vartype role_eligibility_schedule_id: str + :ivar status: The status of the role eligibility schedule instance. Known values are: "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". - :type status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status - :param start_date_time: The startDateTime of the role eligibility schedule instance. - :type start_date_time: ~datetime.datetime - :param end_date_time: The endDateTime of the role eligibility schedule instance. - :type end_date_time: ~datetime.datetime - :param member_type: Membership type of the role eligibility schedule. Possible values include: - "Inherited", "Direct", "Group". - :type member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType - :param condition: The conditions on the role assignment. This limits the resources it can be + "ScheduleCreated", and "PendingExternalProvisioning". + :vartype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status + :ivar start_date_time: The startDateTime of the role eligibility schedule instance. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: The endDateTime of the role eligibility schedule instance. + :vartype end_date_time: ~datetime.datetime + :ivar member_type: Membership type of the role eligibility schedule. Known values are: + "Inherited", "Direct", and "Group". + :vartype member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType + :ivar condition: The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str - :param created_on: DateTime when role eligibility schedule was created. - :type created_on: ~datetime.datetime - :param expanded_properties: Additional properties of principal, scope and role definition. - :type expanded_properties: + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: DateTime when role eligibility schedule was created. + :vartype created_on: ~datetime.datetime + :ivar expanded_properties: Additional properties of principal, scope and role definition. + :vartype expanded_properties: ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'role_eligibility_schedule_id': {'key': 'properties.roleEligibilityScheduleId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, - 'member_type': {'key': 'properties.memberType', 'type': 'str'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "role_eligibility_schedule_id": {"key": "properties.roleEligibilityScheduleId", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, + "member_type": {"key": "properties.memberType", "type": "str"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, } def __init__( @@ -1835,19 +2290,59 @@ def __init__( scope: Optional[str] = None, role_definition_id: Optional[str] = None, principal_id: Optional[str] = None, - principal_type: Optional[Union[str, "PrincipalType"]] = None, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, role_eligibility_schedule_id: Optional[str] = None, - status: Optional[Union[str, "Status"]] = None, + status: Optional[Union[str, "_models.Status"]] = None, start_date_time: Optional[datetime.datetime] = None, end_date_time: Optional[datetime.datetime] = None, - member_type: Optional[Union[str, "MemberType"]] = None, + member_type: Optional[Union[str, "_models.MemberType"]] = None, condition: Optional[str] = None, condition_version: Optional[str] = None, created_on: Optional[datetime.datetime] = None, - expanded_properties: Optional["ExpandedProperties"] = None, + expanded_properties: Optional["_models.ExpandedProperties"] = None, **kwargs ): - super(RoleEligibilityScheduleInstance, self).__init__(**kwargs) + """ + :keyword scope: The role eligibility schedule scope. + :paramtype scope: str + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType + :keyword role_eligibility_schedule_id: Id of the master role eligibility schedule. + :paramtype role_eligibility_schedule_id: str + :keyword status: The status of the role eligibility schedule instance. Known values are: + "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", + "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", + "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", + "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", + "ScheduleCreated", and "PendingExternalProvisioning". + :paramtype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status + :keyword start_date_time: The startDateTime of the role eligibility schedule instance. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: The endDateTime of the role eligibility schedule instance. + :paramtype end_date_time: ~datetime.datetime + :keyword member_type: Membership type of the role eligibility schedule. Known values are: + "Inherited", "Direct", and "Group". + :paramtype member_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.MemberType + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + :keyword created_on: DateTime when role eligibility schedule was created. + :paramtype created_on: ~datetime.datetime + :keyword expanded_properties: Additional properties of principal, scope and role definition. + :paramtype expanded_properties: + ~azure.mgmt.authorization.v2020_10_01_preview.models.ExpandedProperties + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -1866,26 +2361,26 @@ def __init__( self.expanded_properties = expanded_properties -class RoleEligibilityScheduleInstanceFilter(msrest.serialization.Model): +class RoleEligibilityScheduleInstanceFilter(_serialization.Model): """Role eligibility schedule instance filter. - :param principal_id: Returns role eligibility schedule instances of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role eligibility schedule instances of the specific role + :ivar principal_id: Returns role eligibility schedule instances of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role eligibility schedule instances of the specific role definition. - :type role_definition_id: str - :param status: Returns role eligibility schedule instances of the specific status. - :type status: str - :param role_eligibility_schedule_id: Returns role eligibility schedule instances belonging to a + :vartype role_definition_id: str + :ivar status: Returns role eligibility schedule instances of the specific status. + :vartype status: str + :ivar role_eligibility_schedule_id: Returns role eligibility schedule instances belonging to a specific role eligibility schedule. - :type role_eligibility_schedule_id: str + :vartype role_eligibility_schedule_id: str """ _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'role_eligibility_schedule_id': {'key': 'roleEligibilityScheduleId', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "role_eligibility_schedule_id": {"key": "roleEligibilityScheduleId", "type": "str"}, } def __init__( @@ -1897,67 +2392,94 @@ def __init__( role_eligibility_schedule_id: Optional[str] = None, **kwargs ): - super(RoleEligibilityScheduleInstanceFilter, self).__init__(**kwargs) + """ + :keyword principal_id: Returns role eligibility schedule instances of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role eligibility schedule instances of the specific role + definition. + :paramtype role_definition_id: str + :keyword status: Returns role eligibility schedule instances of the specific status. + :paramtype status: str + :keyword role_eligibility_schedule_id: Returns role eligibility schedule instances belonging to + a specific role eligibility schedule. + :paramtype role_eligibility_schedule_id: str + """ + super().__init__(**kwargs) self.principal_id = principal_id self.role_definition_id = role_definition_id self.status = status self.role_eligibility_schedule_id = role_eligibility_schedule_id -class RoleEligibilityScheduleInstanceListResult(msrest.serialization.Model): +class RoleEligibilityScheduleInstanceListResult(_serialization.Model): """Role eligibility schedule instance list operation result. - :param value: Role eligibility schedule instance list. - :type value: + :ivar value: Role eligibility schedule instance list. + :vartype value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleInstance] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleEligibilityScheduleInstance]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleEligibilityScheduleInstance]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["RoleEligibilityScheduleInstance"]] = None, + value: Optional[List["_models.RoleEligibilityScheduleInstance"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleEligibilityScheduleInstanceListResult, self).__init__(**kwargs) + """ + :keyword value: Role eligibility schedule instance list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleInstance] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class RoleEligibilityScheduleListResult(msrest.serialization.Model): +class RoleEligibilityScheduleListResult(_serialization.Model): """role eligibility schedule list operation result. - :param value: role eligibility schedule list. - :type value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilitySchedule] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: role eligibility schedule list. + :vartype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilitySchedule] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleEligibilitySchedule]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleEligibilitySchedule]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["RoleEligibilitySchedule"]] = None, + value: Optional[List["_models.RoleEligibilitySchedule"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleEligibilityScheduleListResult, self).__init__(**kwargs) + """ + :keyword value: role eligibility schedule list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilitySchedule] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class RoleEligibilityScheduleRequest(msrest.serialization.Model): +class RoleEligibilityScheduleRequest(_serialization.Model): # pylint: disable=too-many-instance-attributes """Role Eligibility schedule request. Variables are only populated by the server, and will be ignored when sending a request. @@ -1970,48 +2492,48 @@ class RoleEligibilityScheduleRequest(msrest.serialization.Model): :vartype type: str :ivar scope: The role eligibility schedule request scope. :vartype scope: str - :param role_definition_id: The role definition ID. - :type role_definition_id: str - :param principal_id: The principal ID. - :type principal_id: str - :ivar principal_type: The principal type of the assigned principal ID. Possible values include: - "User", "Group", "ServicePrincipal", "ForeignGroup", "Device". + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". :vartype principal_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.PrincipalType - :param request_type: The type of the role assignment schedule request. Eg: SelfActivate, - AdminAssign etc. Possible values include: "AdminAssign", "AdminRemove", "AdminUpdate", - "AdminExtend", "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", "SelfRenew". - :type request_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RequestType - :ivar status: The status of the role eligibility schedule request. Possible values include: + :ivar request_type: The type of the role assignment schedule request. Eg: SelfActivate, + AdminAssign etc. Known values are: "AdminAssign", "AdminRemove", "AdminUpdate", "AdminExtend", + "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", and "SelfRenew". + :vartype request_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RequestType + :ivar status: The status of the role eligibility schedule request. Known values are: "Accepted", "PendingEvaluation", "Granted", "Denied", "PendingProvisioning", "Provisioned", "PendingRevocation", "Revoked", "Canceled", "Failed", "PendingApprovalProvisioning", "PendingApproval", "FailedAsResourceIsLocked", "PendingAdminDecision", "AdminApproved", "AdminDenied", "TimedOut", "ProvisioningStarted", "Invalid", "PendingScheduleCreation", - "ScheduleCreated", "PendingExternalProvisioning". + "ScheduleCreated", and "PendingExternalProvisioning". :vartype status: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Status :ivar approval_id: The approvalId of the role eligibility schedule request. :vartype approval_id: str - :param schedule_info: Schedule info of the role eligibility schedule. - :type schedule_info: + :ivar schedule_info: Schedule info of the role eligibility schedule. + :vartype schedule_info: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequestPropertiesScheduleInfo - :param target_role_eligibility_schedule_id: The resultant role eligibility schedule id or the + :ivar target_role_eligibility_schedule_id: The resultant role eligibility schedule id or the role eligibility schedule id being updated. - :type target_role_eligibility_schedule_id: str - :param target_role_eligibility_schedule_instance_id: The role eligibility schedule instance id + :vartype target_role_eligibility_schedule_id: str + :ivar target_role_eligibility_schedule_instance_id: The role eligibility schedule instance id being updated. - :type target_role_eligibility_schedule_instance_id: str - :param justification: Justification for the role eligibility. - :type justification: str - :param ticket_info: Ticket Info of the role eligibility. - :type ticket_info: + :vartype target_role_eligibility_schedule_instance_id: str + :ivar justification: Justification for the role eligibility. + :vartype justification: str + :ivar ticket_info: Ticket Info of the role eligibility. + :vartype ticket_info: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequestPropertiesTicketInfo - :param condition: The conditions on the role assignment. This limits the resources it can be + :ivar condition: The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. - :type condition: str - :param condition_version: Version of the condition. Currently accepted value is '2.0'. - :type condition_version: str + :vartype condition: str + :ivar condition_version: Version of the condition. Currently accepted value is '2.0'. + :vartype condition_version: str :ivar created_on: DateTime when role eligibility schedule request was created. :vartype created_on: ~datetime.datetime :ivar requestor_id: Id of the user who created this request. @@ -2022,39 +2544,45 @@ class RoleEligibilityScheduleRequest(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'scope': {'readonly': True}, - 'principal_type': {'readonly': True}, - 'status': {'readonly': True}, - 'approval_id': {'readonly': True}, - 'created_on': {'readonly': True}, - 'requestor_id': {'readonly': True}, - 'expanded_properties': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "scope": {"readonly": True}, + "principal_type": {"readonly": True}, + "status": {"readonly": True}, + "approval_id": {"readonly": True}, + "created_on": {"readonly": True}, + "requestor_id": {"readonly": True}, + "expanded_properties": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.principalType', 'type': 'str'}, - 'request_type': {'key': 'properties.requestType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'approval_id': {'key': 'properties.approvalId', 'type': 'str'}, - 'schedule_info': {'key': 'properties.scheduleInfo', 'type': 'RoleEligibilityScheduleRequestPropertiesScheduleInfo'}, - 'target_role_eligibility_schedule_id': {'key': 'properties.targetRoleEligibilityScheduleId', 'type': 'str'}, - 'target_role_eligibility_schedule_instance_id': {'key': 'properties.targetRoleEligibilityScheduleInstanceId', 'type': 'str'}, - 'justification': {'key': 'properties.justification', 'type': 'str'}, - 'ticket_info': {'key': 'properties.ticketInfo', 'type': 'RoleEligibilityScheduleRequestPropertiesTicketInfo'}, - 'condition': {'key': 'properties.condition', 'type': 'str'}, - 'condition_version': {'key': 'properties.conditionVersion', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'requestor_id': {'key': 'properties.requestorId', 'type': 'str'}, - 'expanded_properties': {'key': 'properties.expandedProperties', 'type': 'ExpandedProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "request_type": {"key": "properties.requestType", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "approval_id": {"key": "properties.approvalId", "type": "str"}, + "schedule_info": { + "key": "properties.scheduleInfo", + "type": "RoleEligibilityScheduleRequestPropertiesScheduleInfo", + }, + "target_role_eligibility_schedule_id": {"key": "properties.targetRoleEligibilityScheduleId", "type": "str"}, + "target_role_eligibility_schedule_instance_id": { + "key": "properties.targetRoleEligibilityScheduleInstanceId", + "type": "str", + }, + "justification": {"key": "properties.justification", "type": "str"}, + "ticket_info": {"key": "properties.ticketInfo", "type": "RoleEligibilityScheduleRequestPropertiesTicketInfo"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "requestor_id": {"key": "properties.requestorId", "type": "str"}, + "expanded_properties": {"key": "properties.expandedProperties", "type": "ExpandedProperties"}, } def __init__( @@ -2062,17 +2590,49 @@ def __init__( *, role_definition_id: Optional[str] = None, principal_id: Optional[str] = None, - request_type: Optional[Union[str, "RequestType"]] = None, - schedule_info: Optional["RoleEligibilityScheduleRequestPropertiesScheduleInfo"] = None, + request_type: Optional[Union[str, "_models.RequestType"]] = None, + schedule_info: Optional["_models.RoleEligibilityScheduleRequestPropertiesScheduleInfo"] = None, target_role_eligibility_schedule_id: Optional[str] = None, target_role_eligibility_schedule_instance_id: Optional[str] = None, justification: Optional[str] = None, - ticket_info: Optional["RoleEligibilityScheduleRequestPropertiesTicketInfo"] = None, + ticket_info: Optional["_models.RoleEligibilityScheduleRequestPropertiesTicketInfo"] = None, condition: Optional[str] = None, condition_version: Optional[str] = None, **kwargs ): - super(RoleEligibilityScheduleRequest, self).__init__(**kwargs) + """ + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword request_type: The type of the role assignment schedule request. Eg: SelfActivate, + AdminAssign etc. Known values are: "AdminAssign", "AdminRemove", "AdminUpdate", "AdminExtend", + "AdminRenew", "SelfActivate", "SelfDeactivate", "SelfExtend", and "SelfRenew". + :paramtype request_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.RequestType + :keyword schedule_info: Schedule info of the role eligibility schedule. + :paramtype schedule_info: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequestPropertiesScheduleInfo + :keyword target_role_eligibility_schedule_id: The resultant role eligibility schedule id or the + role eligibility schedule id being updated. + :paramtype target_role_eligibility_schedule_id: str + :keyword target_role_eligibility_schedule_instance_id: The role eligibility schedule instance + id being updated. + :paramtype target_role_eligibility_schedule_instance_id: str + :keyword justification: Justification for the role eligibility. + :paramtype justification: str + :keyword ticket_info: Ticket Info of the role eligibility. + :paramtype ticket_info: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequestPropertiesTicketInfo + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently accepted value is '2.0'. + :paramtype condition_version: str + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -2095,24 +2655,24 @@ def __init__( self.expanded_properties = None -class RoleEligibilityScheduleRequestFilter(msrest.serialization.Model): +class RoleEligibilityScheduleRequestFilter(_serialization.Model): """Role eligibility schedule request filter. - :param principal_id: Returns role eligibility requests of the specific principal. - :type principal_id: str - :param role_definition_id: Returns role eligibility requests of the specific role definition. - :type role_definition_id: str - :param requestor_id: Returns role eligibility requests created by specific principal. - :type requestor_id: str - :param status: Returns role eligibility requests of specific status. - :type status: str + :ivar principal_id: Returns role eligibility requests of the specific principal. + :vartype principal_id: str + :ivar role_definition_id: Returns role eligibility requests of the specific role definition. + :vartype role_definition_id: str + :ivar requestor_id: Returns role eligibility requests created by specific principal. + :vartype requestor_id: str + :ivar status: Returns role eligibility requests of specific status. + :vartype status: str """ _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, - 'requestor_id': {'key': 'requestorId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "requestor_id": {"key": "requestorId", "type": "str"}, + "status": {"key": "status", "type": "str"}, } def __init__( @@ -2124,126 +2684,159 @@ def __init__( status: Optional[str] = None, **kwargs ): - super(RoleEligibilityScheduleRequestFilter, self).__init__(**kwargs) + """ + :keyword principal_id: Returns role eligibility requests of the specific principal. + :paramtype principal_id: str + :keyword role_definition_id: Returns role eligibility requests of the specific role definition. + :paramtype role_definition_id: str + :keyword requestor_id: Returns role eligibility requests created by specific principal. + :paramtype requestor_id: str + :keyword status: Returns role eligibility requests of specific status. + :paramtype status: str + """ + super().__init__(**kwargs) self.principal_id = principal_id self.role_definition_id = role_definition_id self.requestor_id = requestor_id self.status = status -class RoleEligibilityScheduleRequestListResult(msrest.serialization.Model): +class RoleEligibilityScheduleRequestListResult(_serialization.Model): """Role eligibility schedule request list operation result. - :param value: Role eligibility schedule request list. - :type value: + :ivar value: Role eligibility schedule request list. + :vartype value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleEligibilityScheduleRequest]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleEligibilityScheduleRequest]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["RoleEligibilityScheduleRequest"]] = None, + value: Optional[List["_models.RoleEligibilityScheduleRequest"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleEligibilityScheduleRequestListResult, self).__init__(**kwargs) + """ + :keyword value: Role eligibility schedule request list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class RoleEligibilityScheduleRequestPropertiesScheduleInfo(msrest.serialization.Model): +class RoleEligibilityScheduleRequestPropertiesScheduleInfo(_serialization.Model): """Schedule info of the role eligibility schedule. - :param start_date_time: Start DateTime of the role eligibility schedule. - :type start_date_time: ~datetime.datetime - :param expiration: Expiration of the role eligibility schedule. - :type expiration: + :ivar start_date_time: Start DateTime of the role eligibility schedule. + :vartype start_date_time: ~datetime.datetime + :ivar expiration: Expiration of the role eligibility schedule. + :vartype expiration: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration """ _attribute_map = { - 'start_date_time': {'key': 'startDateTime', 'type': 'iso-8601'}, - 'expiration': {'key': 'expiration', 'type': 'RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration'}, + "start_date_time": {"key": "startDateTime", "type": "iso-8601"}, + "expiration": {"key": "expiration", "type": "RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration"}, } def __init__( self, *, start_date_time: Optional[datetime.datetime] = None, - expiration: Optional["RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration"] = None, + expiration: Optional["_models.RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration"] = None, **kwargs ): - super(RoleEligibilityScheduleRequestPropertiesScheduleInfo, self).__init__(**kwargs) + """ + :keyword start_date_time: Start DateTime of the role eligibility schedule. + :paramtype start_date_time: ~datetime.datetime + :keyword expiration: Expiration of the role eligibility schedule. + :paramtype expiration: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration + """ + super().__init__(**kwargs) self.start_date_time = start_date_time self.expiration = expiration -class RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration(msrest.serialization.Model): +class RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration(_serialization.Model): """Expiration of the role eligibility schedule. - :param type: Type of the role eligibility schedule expiration. Possible values include: - "AfterDuration", "AfterDateTime", "NoExpiration". - :type type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Type - :param end_date_time: End DateTime of the role eligibility schedule. - :type end_date_time: ~datetime.datetime - :param duration: Duration of the role eligibility schedule in TimeSpan. - :type duration: str + :ivar type: Type of the role eligibility schedule expiration. Known values are: + "AfterDuration", "AfterDateTime", and "NoExpiration". + :vartype type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Type + :ivar end_date_time: End DateTime of the role eligibility schedule. + :vartype end_date_time: ~datetime.datetime + :ivar duration: Duration of the role eligibility schedule in TimeSpan. + :vartype duration: str """ _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'end_date_time': {'key': 'endDateTime', 'type': 'iso-8601'}, - 'duration': {'key': 'duration', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "end_date_time": {"key": "endDateTime", "type": "iso-8601"}, + "duration": {"key": "duration", "type": "str"}, } def __init__( self, *, - type: Optional[Union[str, "Type"]] = None, + type: Optional[Union[str, "_models.Type"]] = None, end_date_time: Optional[datetime.datetime] = None, duration: Optional[str] = None, **kwargs ): - super(RoleEligibilityScheduleRequestPropertiesScheduleInfoExpiration, self).__init__(**kwargs) + """ + :keyword type: Type of the role eligibility schedule expiration. Known values are: + "AfterDuration", "AfterDateTime", and "NoExpiration". + :paramtype type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.Type + :keyword end_date_time: End DateTime of the role eligibility schedule. + :paramtype end_date_time: ~datetime.datetime + :keyword duration: Duration of the role eligibility schedule in TimeSpan. + :paramtype duration: str + """ + super().__init__(**kwargs) self.type = type self.end_date_time = end_date_time self.duration = duration -class RoleEligibilityScheduleRequestPropertiesTicketInfo(msrest.serialization.Model): +class RoleEligibilityScheduleRequestPropertiesTicketInfo(_serialization.Model): """Ticket Info of the role eligibility. - :param ticket_number: Ticket number for the role eligibility. - :type ticket_number: str - :param ticket_system: Ticket system name for the role eligibility. - :type ticket_system: str + :ivar ticket_number: Ticket number for the role eligibility. + :vartype ticket_number: str + :ivar ticket_system: Ticket system name for the role eligibility. + :vartype ticket_system: str """ _attribute_map = { - 'ticket_number': {'key': 'ticketNumber', 'type': 'str'}, - 'ticket_system': {'key': 'ticketSystem', 'type': 'str'}, - } - - def __init__( - self, - *, - ticket_number: Optional[str] = None, - ticket_system: Optional[str] = None, - **kwargs - ): - super(RoleEligibilityScheduleRequestPropertiesTicketInfo, self).__init__(**kwargs) + "ticket_number": {"key": "ticketNumber", "type": "str"}, + "ticket_system": {"key": "ticketSystem", "type": "str"}, + } + + def __init__(self, *, ticket_number: Optional[str] = None, ticket_system: Optional[str] = None, **kwargs): + """ + :keyword ticket_number: Ticket number for the role eligibility. + :paramtype ticket_number: str + :keyword ticket_system: Ticket system name for the role eligibility. + :paramtype ticket_system: str + """ + super().__init__(**kwargs) self.ticket_number = ticket_number self.ticket_system = ticket_system -class RoleManagementPolicy(msrest.serialization.Model): +class RoleManagementPolicy(_serialization.Model): # pylint: disable=too-many-instance-attributes """Role management policy. Variables are only populated by the server, and will be ignored when sending a request. @@ -2254,20 +2847,20 @@ class RoleManagementPolicy(msrest.serialization.Model): :vartype name: str :ivar type: The role management policy type. :vartype type: str - :param scope: The role management policy scope. - :type scope: str - :param display_name: The role management policy display name. - :type display_name: str - :param description: The role management policy description. - :type description: str - :param is_organization_default: The role management policy is default policy. - :type is_organization_default: bool + :ivar scope: The role management policy scope. + :vartype scope: str + :ivar display_name: The role management policy display name. + :vartype display_name: str + :ivar description: The role management policy description. + :vartype description: str + :ivar is_organization_default: The role management policy is default policy. + :vartype is_organization_default: bool :ivar last_modified_by: The name of the entity last modified it. :vartype last_modified_by: ~azure.mgmt.authorization.v2020_10_01_preview.models.Principal :ivar last_modified_date_time: The last modified date time. :vartype last_modified_date_time: ~datetime.datetime - :param rules: The rule applied to the policy. - :type rules: + :ivar rules: The rule applied to the policy. + :vartype rules: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRule] :ivar effective_rules: The readonly computed rule applied to the policy. :vartype effective_rules: @@ -2278,28 +2871,28 @@ class RoleManagementPolicy(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'last_modified_by': {'readonly': True}, - 'last_modified_date_time': {'readonly': True}, - 'effective_rules': {'readonly': True}, - 'policy_properties': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "last_modified_by": {"readonly": True}, + "last_modified_date_time": {"readonly": True}, + "effective_rules": {"readonly": True}, + "policy_properties": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'is_organization_default': {'key': 'properties.isOrganizationDefault', 'type': 'bool'}, - 'last_modified_by': {'key': 'properties.lastModifiedBy', 'type': 'Principal'}, - 'last_modified_date_time': {'key': 'properties.lastModifiedDateTime', 'type': 'iso-8601'}, - 'rules': {'key': 'properties.rules', 'type': '[RoleManagementPolicyRule]'}, - 'effective_rules': {'key': 'properties.effectiveRules', 'type': '[RoleManagementPolicyRule]'}, - 'policy_properties': {'key': 'properties.policyProperties', 'type': 'PolicyProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "is_organization_default": {"key": "properties.isOrganizationDefault", "type": "bool"}, + "last_modified_by": {"key": "properties.lastModifiedBy", "type": "Principal"}, + "last_modified_date_time": {"key": "properties.lastModifiedDateTime", "type": "iso-8601"}, + "rules": {"key": "properties.rules", "type": "[RoleManagementPolicyRule]"}, + "effective_rules": {"key": "properties.effectiveRules", "type": "[RoleManagementPolicyRule]"}, + "policy_properties": {"key": "properties.policyProperties", "type": "PolicyProperties"}, } def __init__( @@ -2309,10 +2902,23 @@ def __init__( display_name: Optional[str] = None, description: Optional[str] = None, is_organization_default: Optional[bool] = None, - rules: Optional[List["RoleManagementPolicyRule"]] = None, + rules: Optional[List["_models.RoleManagementPolicyRule"]] = None, **kwargs ): - super(RoleManagementPolicy, self).__init__(**kwargs) + """ + :keyword scope: The role management policy scope. + :paramtype scope: str + :keyword display_name: The role management policy display name. + :paramtype display_name: str + :keyword description: The role management policy description. + :paramtype description: str + :keyword is_organization_default: The role management policy is default policy. + :paramtype is_organization_default: bool + :keyword rules: The rule applied to the policy. + :paramtype rules: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRule] + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -2327,49 +2933,64 @@ def __init__( self.policy_properties = None -class RoleManagementPolicyRule(msrest.serialization.Model): +class RoleManagementPolicyRule(_serialization.Model): """The role management policy rule. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: RoleManagementPolicyApprovalRule, RoleManagementPolicyAuthenticationContextRule, RoleManagementPolicyEnablementRule, RoleManagementPolicyExpirationRule, RoleManagementPolicyNotificationRule. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + RoleManagementPolicyApprovalRule, RoleManagementPolicyAuthenticationContextRule, + RoleManagementPolicyEnablementRule, RoleManagementPolicyExpirationRule, + RoleManagementPolicyNotificationRule All required parameters must be populated in order to send to Azure. - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and "RoleManagementPolicyNotificationRule". - :type rule_type: str or + :vartype rule_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget """ _validation = { - 'rule_type': {'required': True}, + "rule_type": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, } _subtype_map = { - 'rule_type': {'RoleManagementPolicyApprovalRule': 'RoleManagementPolicyApprovalRule', 'RoleManagementPolicyAuthenticationContextRule': 'RoleManagementPolicyAuthenticationContextRule', 'RoleManagementPolicyEnablementRule': 'RoleManagementPolicyEnablementRule', 'RoleManagementPolicyExpirationRule': 'RoleManagementPolicyExpirationRule', 'RoleManagementPolicyNotificationRule': 'RoleManagementPolicyNotificationRule'} + "rule_type": { + "RoleManagementPolicyApprovalRule": "RoleManagementPolicyApprovalRule", + "RoleManagementPolicyAuthenticationContextRule": "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule": "RoleManagementPolicyEnablementRule", + "RoleManagementPolicyExpirationRule": "RoleManagementPolicyExpirationRule", + "RoleManagementPolicyNotificationRule": "RoleManagementPolicyNotificationRule", + } } def __init__( self, *, - id: Optional[str] = None, - target: Optional["RoleManagementPolicyRuleTarget"] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, **kwargs ): - super(RoleManagementPolicyRule, self).__init__(**kwargs) + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget + """ + super().__init__(**kwargs) self.id = id self.rule_type = None # type: Optional[str] self.target = target @@ -2380,46 +3001,55 @@ class RoleManagementPolicyApprovalRule(RoleManagementPolicyRule): All required parameters must be populated in order to send to Azure. - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and "RoleManagementPolicyNotificationRule". - :type rule_type: str or + :vartype rule_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget - :param setting: The approval setting. - :type setting: ~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalSettings + :ivar setting: The approval setting. + :vartype setting: ~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalSettings """ _validation = { - 'rule_type': {'required': True}, + "rule_type": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, - 'setting': {'key': 'setting', 'type': 'ApprovalSettings'}, + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "setting": {"key": "setting", "type": "ApprovalSettings"}, } def __init__( self, *, - id: Optional[str] = None, - target: Optional["RoleManagementPolicyRuleTarget"] = None, - setting: Optional["ApprovalSettings"] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + setting: Optional["_models.ApprovalSettings"] = None, **kwargs ): - super(RoleManagementPolicyApprovalRule, self).__init__(id=id, target=target, **kwargs) - self.rule_type = 'RoleManagementPolicyApprovalRule' # type: str + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget + :keyword setting: The approval setting. + :paramtype setting: ~azure.mgmt.authorization.v2020_10_01_preview.models.ApprovalSettings + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyApprovalRule" # type: str self.setting = setting -class RoleManagementPolicyAssignment(msrest.serialization.Model): +class RoleManagementPolicyAssignment(_serialization.Model): """Role management policy. Variables are only populated by the server, and will be ignored when sending a request. @@ -2430,32 +3060,35 @@ class RoleManagementPolicyAssignment(msrest.serialization.Model): :vartype name: str :ivar type: The role management policy type. :vartype type: str - :param scope: The role management policy scope. - :type scope: str - :param role_definition_id: The role definition of management policy assignment. - :type role_definition_id: str - :param policy_id: The policy id role management policy assignment. - :type policy_id: str + :ivar scope: The role management policy scope. + :vartype scope: str + :ivar role_definition_id: The role definition of management policy assignment. + :vartype role_definition_id: str + :ivar policy_id: The policy id role management policy assignment. + :vartype policy_id: str :ivar policy_assignment_properties: Additional properties of scope, role definition and policy. :vartype policy_assignment_properties: ~azure.mgmt.authorization.v2020_10_01_preview.models.PolicyAssignmentProperties """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'policy_assignment_properties': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "policy_assignment_properties": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'policy_id': {'key': 'properties.policyId', 'type': 'str'}, - 'policy_assignment_properties': {'key': 'properties.policyAssignmentProperties', 'type': 'PolicyAssignmentProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "policy_id": {"key": "properties.policyId", "type": "str"}, + "policy_assignment_properties": { + "key": "properties.policyAssignmentProperties", + "type": "PolicyAssignmentProperties", + }, } def __init__( @@ -2466,7 +3099,15 @@ def __init__( policy_id: Optional[str] = None, **kwargs ): - super(RoleManagementPolicyAssignment, self).__init__(**kwargs) + """ + :keyword scope: The role management policy scope. + :paramtype scope: str + :keyword role_definition_id: The role definition of management policy assignment. + :paramtype role_definition_id: str + :keyword policy_id: The policy id role management policy assignment. + :paramtype policy_id: str + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -2476,29 +3117,36 @@ def __init__( self.policy_assignment_properties = None -class RoleManagementPolicyAssignmentListResult(msrest.serialization.Model): +class RoleManagementPolicyAssignmentListResult(_serialization.Model): """Role management policy assignment list operation result. - :param value: Role management policy assignment list. - :type value: + :ivar value: Role management policy assignment list. + :vartype value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleManagementPolicyAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleManagementPolicyAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["RoleManagementPolicyAssignment"]] = None, + value: Optional[List["_models.RoleManagementPolicyAssignment"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleManagementPolicyAssignmentListResult, self).__init__(**kwargs) + """ + :keyword value: Role management policy assignment list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link @@ -2508,46 +3156,57 @@ class RoleManagementPolicyAuthenticationContextRule(RoleManagementPolicyRule): All required parameters must be populated in order to send to Azure. - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and "RoleManagementPolicyNotificationRule". - :type rule_type: str or + :vartype rule_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget - :param is_enabled: The value indicating if rule is enabled. - :type is_enabled: bool - :param claim_value: The claim value. - :type claim_value: str + :ivar is_enabled: The value indicating if rule is enabled. + :vartype is_enabled: bool + :ivar claim_value: The claim value. + :vartype claim_value: str """ _validation = { - 'rule_type': {'required': True}, + "rule_type": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, - 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, - 'claim_value': {'key': 'claimValue', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "is_enabled": {"key": "isEnabled", "type": "bool"}, + "claim_value": {"key": "claimValue", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, - target: Optional["RoleManagementPolicyRuleTarget"] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, is_enabled: Optional[bool] = None, claim_value: Optional[str] = None, **kwargs ): - super(RoleManagementPolicyAuthenticationContextRule, self).__init__(id=id, target=target, **kwargs) - self.rule_type = 'RoleManagementPolicyAuthenticationContextRule' # type: str + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget + :keyword is_enabled: The value indicating if rule is enabled. + :paramtype is_enabled: bool + :keyword claim_value: The claim value. + :paramtype claim_value: str + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyAuthenticationContextRule" # type: str self.is_enabled = is_enabled self.claim_value = claim_value @@ -2557,43 +3216,53 @@ class RoleManagementPolicyEnablementRule(RoleManagementPolicyRule): All required parameters must be populated in order to send to Azure. - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and "RoleManagementPolicyNotificationRule". - :type rule_type: str or + :vartype rule_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget - :param enabled_rules: The list of enabled rules. - :type enabled_rules: list[str or + :ivar enabled_rules: The list of enabled rules. + :vartype enabled_rules: list[str or ~azure.mgmt.authorization.v2020_10_01_preview.models.EnablementRules] """ _validation = { - 'rule_type': {'required': True}, + "rule_type": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, - 'enabled_rules': {'key': 'enabledRules', 'type': '[str]'}, + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "enabled_rules": {"key": "enabledRules", "type": "[str]"}, } def __init__( self, *, - id: Optional[str] = None, - target: Optional["RoleManagementPolicyRuleTarget"] = None, - enabled_rules: Optional[List[Union[str, "EnablementRules"]]] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + enabled_rules: Optional[List[Union[str, "_models.EnablementRules"]]] = None, **kwargs ): - super(RoleManagementPolicyEnablementRule, self).__init__(id=id, target=target, **kwargs) - self.rule_type = 'RoleManagementPolicyEnablementRule' # type: str + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget + :keyword enabled_rules: The list of enabled rules. + :paramtype enabled_rules: list[str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.EnablementRules] + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyEnablementRule" # type: str self.enabled_rules = enabled_rules @@ -2602,72 +3271,86 @@ class RoleManagementPolicyExpirationRule(RoleManagementPolicyRule): All required parameters must be populated in order to send to Azure. - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and "RoleManagementPolicyNotificationRule". - :type rule_type: str or + :vartype rule_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget - :param is_expiration_required: The value indicating whether expiration is required. - :type is_expiration_required: bool - :param maximum_duration: The maximum duration of expiration in timespan. - :type maximum_duration: str + :ivar is_expiration_required: The value indicating whether expiration is required. + :vartype is_expiration_required: bool + :ivar maximum_duration: The maximum duration of expiration in timespan. + :vartype maximum_duration: str """ _validation = { - 'rule_type': {'required': True}, + "rule_type": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, - 'is_expiration_required': {'key': 'isExpirationRequired', 'type': 'bool'}, - 'maximum_duration': {'key': 'maximumDuration', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "is_expiration_required": {"key": "isExpirationRequired", "type": "bool"}, + "maximum_duration": {"key": "maximumDuration", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, - target: Optional["RoleManagementPolicyRuleTarget"] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, is_expiration_required: Optional[bool] = None, maximum_duration: Optional[str] = None, **kwargs ): - super(RoleManagementPolicyExpirationRule, self).__init__(id=id, target=target, **kwargs) - self.rule_type = 'RoleManagementPolicyExpirationRule' # type: str + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget + :keyword is_expiration_required: The value indicating whether expiration is required. + :paramtype is_expiration_required: bool + :keyword maximum_duration: The maximum duration of expiration in timespan. + :paramtype maximum_duration: str + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyExpirationRule" # type: str self.is_expiration_required = is_expiration_required self.maximum_duration = maximum_duration -class RoleManagementPolicyListResult(msrest.serialization.Model): +class RoleManagementPolicyListResult(_serialization.Model): """Role management policy list operation result. - :param value: Role management policy list. - :type value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Role management policy list. + :vartype value: list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleManagementPolicy]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleManagementPolicy]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["RoleManagementPolicy"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.RoleManagementPolicy"]] = None, next_link: Optional[str] = None, **kwargs ): - super(RoleManagementPolicyListResult, self).__init__(**kwargs) + """ + :keyword value: Role management policy list. + :paramtype value: + list[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link @@ -2677,63 +3360,87 @@ class RoleManagementPolicyNotificationRule(RoleManagementPolicyRule): All required parameters must be populated in order to send to Azure. - :param id: The id of the rule. - :type id: str - :param rule_type: Required. The type of rule.Constant filled by server. Possible values - include: "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", - "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and "RoleManagementPolicyNotificationRule". - :type rule_type: str or + :vartype rule_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleType - :param target: The target of the current rule. - :type target: + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget - :param notification_type: The type of notification. Possible values include: "Email". - :type notification_type: str or + :ivar notification_type: The type of notification. "Email" + :vartype notification_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.NotificationDeliveryMechanism - :param notification_level: The notification level. Possible values include: "None", "Critical", + :ivar notification_level: The notification level. Known values are: "None", "Critical", and "All". - :type notification_level: str or + :vartype notification_level: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.NotificationLevel - :param recipient_type: The recipient type. Possible values include: "Requestor", "Approver", + :ivar recipient_type: The recipient type. Known values are: "Requestor", "Approver", and "Admin". - :type recipient_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.RecipientType - :param notification_recipients: The list notification recipients. - :type notification_recipients: list[str] - :param is_default_recipients_enabled: Its value determine if the notification need to be sent - to the recipient type specified in policy rule. - :type is_default_recipients_enabled: bool + :vartype recipient_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.RecipientType + :ivar notification_recipients: The list notification recipients. + :vartype notification_recipients: list[str] + :ivar is_default_recipients_enabled: Its value determine if the notification need to be sent to + the recipient type specified in policy rule. + :vartype is_default_recipients_enabled: bool """ _validation = { - 'rule_type': {'required': True}, + "rule_type": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'rule_type': {'key': 'ruleType', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'RoleManagementPolicyRuleTarget'}, - 'notification_type': {'key': 'notificationType', 'type': 'str'}, - 'notification_level': {'key': 'notificationLevel', 'type': 'str'}, - 'recipient_type': {'key': 'recipientType', 'type': 'str'}, - 'notification_recipients': {'key': 'notificationRecipients', 'type': '[str]'}, - 'is_default_recipients_enabled': {'key': 'isDefaultRecipientsEnabled', 'type': 'bool'}, + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "notification_type": {"key": "notificationType", "type": "str"}, + "notification_level": {"key": "notificationLevel", "type": "str"}, + "recipient_type": {"key": "recipientType", "type": "str"}, + "notification_recipients": {"key": "notificationRecipients", "type": "[str]"}, + "is_default_recipients_enabled": {"key": "isDefaultRecipientsEnabled", "type": "bool"}, } def __init__( self, *, - id: Optional[str] = None, - target: Optional["RoleManagementPolicyRuleTarget"] = None, - notification_type: Optional[Union[str, "NotificationDeliveryMechanism"]] = None, - notification_level: Optional[Union[str, "NotificationLevel"]] = None, - recipient_type: Optional[Union[str, "RecipientType"]] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + notification_type: Optional[Union[str, "_models.NotificationDeliveryMechanism"]] = None, + notification_level: Optional[Union[str, "_models.NotificationLevel"]] = None, + recipient_type: Optional[Union[str, "_models.RecipientType"]] = None, notification_recipients: Optional[List[str]] = None, is_default_recipients_enabled: Optional[bool] = None, **kwargs ): - super(RoleManagementPolicyNotificationRule, self).__init__(id=id, target=target, **kwargs) - self.rule_type = 'RoleManagementPolicyNotificationRule' # type: str + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyRuleTarget + :keyword notification_type: The type of notification. "Email" + :paramtype notification_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.NotificationDeliveryMechanism + :keyword notification_level: The notification level. Known values are: "None", "Critical", and + "All". + :paramtype notification_level: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.NotificationLevel + :keyword recipient_type: The recipient type. Known values are: "Requestor", "Approver", and + "Admin". + :paramtype recipient_type: str or + ~azure.mgmt.authorization.v2020_10_01_preview.models.RecipientType + :keyword notification_recipients: The list notification recipients. + :paramtype notification_recipients: list[str] + :keyword is_default_recipients_enabled: Its value determine if the notification need to be sent + to the recipient type specified in policy rule. + :paramtype is_default_recipients_enabled: bool + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyNotificationRule" # type: str self.notification_type = notification_type self.notification_level = notification_level self.recipient_type = recipient_type @@ -2741,30 +3448,30 @@ def __init__( self.is_default_recipients_enabled = is_default_recipients_enabled -class RoleManagementPolicyRuleTarget(msrest.serialization.Model): +class RoleManagementPolicyRuleTarget(_serialization.Model): """The role management policy rule target. - :param caller: The caller of the setting. - :type caller: str - :param operations: The type of operation. - :type operations: list[str] - :param level: The assignment level to which it is applied. - :type level: str - :param target_objects: The list of target objects. - :type target_objects: list[str] - :param inheritable_settings: The list of inheritable settings. - :type inheritable_settings: list[str] - :param enforced_settings: The list of enforced settings. - :type enforced_settings: list[str] + :ivar caller: The caller of the setting. + :vartype caller: str + :ivar operations: The type of operation. + :vartype operations: list[str] + :ivar level: The assignment level to which it is applied. + :vartype level: str + :ivar target_objects: The list of target objects. + :vartype target_objects: list[str] + :ivar inheritable_settings: The list of inheritable settings. + :vartype inheritable_settings: list[str] + :ivar enforced_settings: The list of enforced settings. + :vartype enforced_settings: list[str] """ _attribute_map = { - 'caller': {'key': 'caller', 'type': 'str'}, - 'operations': {'key': 'operations', 'type': '[str]'}, - 'level': {'key': 'level', 'type': 'str'}, - 'target_objects': {'key': 'targetObjects', 'type': '[str]'}, - 'inheritable_settings': {'key': 'inheritableSettings', 'type': '[str]'}, - 'enforced_settings': {'key': 'enforcedSettings', 'type': '[str]'}, + "caller": {"key": "caller", "type": "str"}, + "operations": {"key": "operations", "type": "[str]"}, + "level": {"key": "level", "type": "str"}, + "target_objects": {"key": "targetObjects", "type": "[str]"}, + "inheritable_settings": {"key": "inheritableSettings", "type": "[str]"}, + "enforced_settings": {"key": "enforcedSettings", "type": "[str]"}, } def __init__( @@ -2778,7 +3485,21 @@ def __init__( enforced_settings: Optional[List[str]] = None, **kwargs ): - super(RoleManagementPolicyRuleTarget, self).__init__(**kwargs) + """ + :keyword caller: The caller of the setting. + :paramtype caller: str + :keyword operations: The type of operation. + :paramtype operations: list[str] + :keyword level: The assignment level to which it is applied. + :paramtype level: str + :keyword target_objects: The list of target objects. + :paramtype target_objects: list[str] + :keyword inheritable_settings: The list of inheritable settings. + :paramtype inheritable_settings: list[str] + :keyword enforced_settings: The list of enforced settings. + :paramtype enforced_settings: list[str] + """ + super().__init__(**kwargs) self.caller = caller self.operations = operations self.level = level @@ -2787,75 +3508,85 @@ def __init__( self.enforced_settings = enforced_settings -class UserSet(msrest.serialization.Model): +class UserSet(_serialization.Model): """The detail of a user. - :param user_type: The type of user. Possible values include: "User", "Group". - :type user_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.UserType - :param is_backup: The value indicating whether the user is a backup fallback approver. - :type is_backup: bool - :param id: The object id of the user. - :type id: str - :param description: The description of the user. - :type description: str + :ivar user_type: The type of user. Known values are: "User" and "Group". + :vartype user_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.UserType + :ivar is_backup: The value indicating whether the user is a backup fallback approver. + :vartype is_backup: bool + :ivar id: The object id of the user. + :vartype id: str + :ivar description: The description of the user. + :vartype description: str """ _attribute_map = { - 'user_type': {'key': 'userType', 'type': 'str'}, - 'is_backup': {'key': 'isBackup', 'type': 'bool'}, - 'id': {'key': 'id', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "user_type": {"key": "userType", "type": "str"}, + "is_backup": {"key": "isBackup", "type": "bool"}, + "id": {"key": "id", "type": "str"}, + "description": {"key": "description", "type": "str"}, } def __init__( self, *, - user_type: Optional[Union[str, "UserType"]] = None, + user_type: Optional[Union[str, "_models.UserType"]] = None, is_backup: Optional[bool] = None, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin description: Optional[str] = None, **kwargs ): - super(UserSet, self).__init__(**kwargs) + """ + :keyword user_type: The type of user. Known values are: "User" and "Group". + :paramtype user_type: str or ~azure.mgmt.authorization.v2020_10_01_preview.models.UserType + :keyword is_backup: The value indicating whether the user is a backup fallback approver. + :paramtype is_backup: bool + :keyword id: The object id of the user. + :paramtype id: str + :keyword description: The description of the user. + :paramtype description: str + """ + super().__init__(**kwargs) self.user_type = user_type self.is_backup = is_backup self.id = id self.description = description -class ValidationResponse(msrest.serialization.Model): +class ValidationResponse(_serialization.Model): """Validation response. Variables are only populated by the server, and will be ignored when sending a request. :ivar is_valid: Whether or not validation succeeded. :vartype is_valid: bool - :param error_info: Failed validation result details. - :type error_info: + :ivar error_info: Failed validation result details. + :vartype error_info: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponseErrorInfo """ _validation = { - 'is_valid': {'readonly': True}, + "is_valid": {"readonly": True}, } _attribute_map = { - 'is_valid': {'key': 'isValid', 'type': 'bool'}, - 'error_info': {'key': 'errorInfo', 'type': 'ValidationResponseErrorInfo'}, + "is_valid": {"key": "isValid", "type": "bool"}, + "error_info": {"key": "errorInfo", "type": "ValidationResponseErrorInfo"}, } - def __init__( - self, - *, - error_info: Optional["ValidationResponseErrorInfo"] = None, - **kwargs - ): - super(ValidationResponse, self).__init__(**kwargs) + def __init__(self, *, error_info: Optional["_models.ValidationResponseErrorInfo"] = None, **kwargs): + """ + :keyword error_info: Failed validation result details. + :paramtype error_info: + ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponseErrorInfo + """ + super().__init__(**kwargs) self.is_valid = None self.error_info = error_info -class ValidationResponseErrorInfo(msrest.serialization.Model): +class ValidationResponseErrorInfo(_serialization.Model): """Failed validation result details. Variables are only populated by the server, and will be ignored when sending a request. @@ -2867,19 +3598,17 @@ class ValidationResponseErrorInfo(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(ValidationResponseErrorInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/__init__.py index 97e8639830c..baf561800ad 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/__init__.py @@ -17,15 +17,21 @@ from ._role_management_policies_operations import RoleManagementPoliciesOperations from ._role_management_policy_assignments_operations import RoleManagementPolicyAssignmentsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'RoleAssignmentsOperations', - 'EligibleChildResourcesOperations', - 'RoleAssignmentSchedulesOperations', - 'RoleAssignmentScheduleInstancesOperations', - 'RoleAssignmentScheduleRequestsOperations', - 'RoleEligibilitySchedulesOperations', - 'RoleEligibilityScheduleInstancesOperations', - 'RoleEligibilityScheduleRequestsOperations', - 'RoleManagementPoliciesOperations', - 'RoleManagementPolicyAssignmentsOperations', + "RoleAssignmentsOperations", + "EligibleChildResourcesOperations", + "RoleAssignmentSchedulesOperations", + "RoleAssignmentScheduleInstancesOperations", + "RoleAssignmentScheduleRequestsOperations", + "RoleEligibilitySchedulesOperations", + "RoleEligibilityScheduleInstancesOperations", + "RoleEligibilityScheduleRequestsOperations", + "RoleManagementPoliciesOperations", + "RoleManagementPolicyAssignmentsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_eligible_child_resources_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_eligible_child_resources_operations.py index 5249728dc28..6c9331e95d9 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_eligible_child_resources_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_eligible_child_resources_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,102 +6,140 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/eligibleChildResources") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } -class EligibleChildResourcesOperations(object): - """EligibleChildResourcesOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class EligibleChildResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.AuthorizationManagementClient`'s + :attr:`eligible_child_resources` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def get( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.EligibleChildResourcesListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.EligibleChildResource"]: """Get the child resources of a resource on which user has eligible access. - :param scope: The scope of the role management policy. + :param scope: The scope of the role management policy. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=resourceType+eq+'Subscription' to filter on only resource of type = 'Subscription'. Use $filter=resourceType+eq+'subscription'+or+resourceType+eq+'resourcegroup' to filter on resource - of type = 'Subscription' or 'ResourceGroup'. + of type = 'Subscription' or 'ResourceGroup'. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either EligibleChildResourcesListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.EligibleChildResourcesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either EligibleChildResource or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.EligibleChildResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.EligibleChildResourcesListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.EligibleChildResourcesListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_get_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('EligibleChildResourcesListResult', pipeline_response) + deserialized = self._deserialize("EligibleChildResourcesListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -109,7 +148,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -118,7 +159,6 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/eligibleChildResources'} # type: ignore + return ItemPaged(get_next, extract_data) + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/eligibleChildResources"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedule_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedule_instances_operations.py index fc497e655b9..19025d2ee66 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedule_instances_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedule_instances_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,104 +6,174 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class RoleAssignmentScheduleInstancesOperations(object): - """RoleAssignmentScheduleInstancesOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_assignment_schedule_instance_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances/{roleAssignmentScheduleInstanceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentScheduleInstanceName": _SERIALIZER.url( + "role_assignment_schedule_instance_name", role_assignment_schedule_instance_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentScheduleInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.AuthorizationManagementClient`'s + :attr:`role_assignment_schedule_instances` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentScheduleInstanceListResult"] + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignmentScheduleInstance"]: """Gets role assignment schedule instances of a role assignment schedule. - :param scope: The scope of the role assignment schedule. + :param scope: The scope of the role assignment schedule. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role assignment schedule instances for the user. Use $filter=asTarget() to return all role assignment schedule instances created for the current - user. + user. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentScheduleInstanceListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignmentScheduleInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentScheduleInstanceListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -111,7 +182,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -120,66 +193,66 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances'} # type: ignore + return ItemPaged(get_next, extract_data) + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances"} # type: ignore + + @distributed_trace def get( - self, - scope, # type: str - role_assignment_schedule_instance_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentScheduleInstance" + self, scope: str, role_assignment_schedule_instance_name: str, **kwargs: Any + ) -> _models.RoleAssignmentScheduleInstance: """Gets the specified role assignment schedule instance. - :param scope: The scope of the role assignments schedules. + :param scope: The scope of the role assignments schedules. Required. :type scope: str :param role_assignment_schedule_instance_name: The name (hash of schedule name + time) of the - role assignment schedule to get. + role assignment schedule to get. Required. :type role_assignment_schedule_instance_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentScheduleInstance, or the result of cls(response) + :return: RoleAssignmentScheduleInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentScheduleInstanceName': self._serialize.url("role_assignment_schedule_instance_name", role_assignment_schedule_instance_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleInstance] + + request = build_get_request( + scope=scope, + role_assignment_schedule_instance_name=role_assignment_schedule_instance_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentScheduleInstance', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances/{roleAssignmentScheduleInstanceName}'} # type: ignore + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleInstances/{roleAssignmentScheduleInstanceName}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedule_requests_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedule_requests_operations.py index bc66ad220fe..5b05c2dcb80 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedule_requests_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedule_requests_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,54 +6,184 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_request(scope: str, role_assignment_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentScheduleRequestName": _SERIALIZER.url( + "role_assignment_schedule_request_name", role_assignment_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_assignment_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentScheduleRequestName": _SERIALIZER.url( + "role_assignment_schedule_request_name", role_assignment_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class RoleAssignmentScheduleRequestsOperations(object): - """RoleAssignmentScheduleRequestsOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +def build_cancel_request(scope: str, role_assignment_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}/cancel", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentScheduleRequestName": _SERIALIZER.url( + "role_assignment_schedule_request_name", role_assignment_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentScheduleRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.AuthorizationManagementClient`'s + :attr:`role_assignment_schedule_requests` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @overload def create( self, - scope, # type: str - role_assignment_schedule_request_name, # type: str - parameters, # type: "_models.RoleAssignmentScheduleRequest" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentScheduleRequest" + scope: str, + role_assignment_schedule_request_name: str, + parameters: _models.RoleAssignmentScheduleRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: """Creates a role assignment schedule request. :param scope: The scope of the role assignment schedule request to create. The scope can be any @@ -61,132 +192,213 @@ def create( '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str - :param role_assignment_schedule_request_name: The name of the role assignment to create. It can - be any valid GUID. + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. :type role_assignment_schedule_request_name: str - :param parameters: Parameters for the role assignment schedule request. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentScheduleRequest, or the result of cls(response) + :return: RoleAssignmentScheduleRequest or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Creates a role assignment schedule request. + + :param scope: The scope of the role assignment schedule request to create. The scope can be any + REST resource instance. For example, use + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_assignment_schedule_request_name: str, + parameters: Union[_models.RoleAssignmentScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: + """Creates a role assignment schedule request. + + :param scope: The scope of the role assignment schedule request to create. The scope can be any + REST resource instance. For example, use + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_assignment_schedule_request_name: A GUID for the role assignment to create. The + name must be unique and different for each role assignment. Required. + :type role_assignment_schedule_request_name: str + :param parameters: Parameters for the role assignment schedule request. Is either a model type + or a IO type. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleRequest"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentScheduleRequestName': self._serialize.url("role_assignment_schedule_request_name", role_assignment_schedule_request_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentScheduleRequest') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentScheduleRequest") + + request = build_create_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentScheduleRequest', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleRequest", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}'} # type: ignore + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}"} # type: ignore + + @distributed_trace def get( - self, - scope, # type: str - role_assignment_schedule_request_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentScheduleRequest" + self, scope: str, role_assignment_schedule_request_name: str, **kwargs: Any + ) -> _models.RoleAssignmentScheduleRequest: """Get the specified role assignment schedule request. - :param scope: The scope of the role assignment schedule request. + :param scope: The scope of the role assignment schedule request. Required. :type scope: str :param role_assignment_schedule_request_name: The name (guid) of the role assignment schedule - request to get. + request to get. Required. :type role_assignment_schedule_request_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentScheduleRequest, or the result of cls(response) + :return: RoleAssignmentScheduleRequest or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleRequest"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentScheduleRequestName': self._serialize.url("role_assignment_schedule_request_name", role_assignment_schedule_request_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequest] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentScheduleRequest', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleRequest", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentScheduleRequestListResult"] + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignmentScheduleRequest"]: """Gets role assignment schedule requests for a scope. - :param scope: The scope of the role assignments schedule requests. + :param scope: The scope of the role assignments schedule requests. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedule requests at or above the scope. Use $filter=principalId eq {id} to return @@ -194,48 +406,56 @@ def list_for_scope( Use $filter=asRequestor() to return all role assignment schedule requests requested by the current user. Use $filter=asTarget() to return all role assignment schedule requests created for the current user. Use $filter=asApprover() to return all role assignment schedule requests - where the current user is an approver. + where the current user is an approver. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentScheduleRequestListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequestListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignmentScheduleRequest or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleRequest] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleRequestListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleRequestListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentScheduleRequestListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleRequestListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -244,7 +464,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -253,56 +475,55 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests'} # type: ignore + return ItemPaged(get_next, extract_data) - def cancel( - self, - scope, # type: str - role_assignment_schedule_request_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests"} # type: ignore + + @distributed_trace + def cancel( # pylint: disable=inconsistent-return-statements + self, scope: str, role_assignment_schedule_request_name: str, **kwargs: Any + ) -> None: """Cancels a pending role assignment schedule request. - :param scope: The scope of the role assignment request to cancel. + :param scope: The scope of the role assignment request to cancel. Required. :type scope: str :param role_assignment_schedule_request_name: The name of the role assignment request to - cancel. + cancel. Required. :type role_assignment_schedule_request_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.cancel.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentScheduleRequestName': self._serialize.url("role_assignment_schedule_request_name", role_assignment_schedule_request_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_cancel_request( + scope=scope, + role_assignment_schedule_request_name=role_assignment_schedule_request_name, + api_version=api_version, + template_url=self.cancel.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -312,4 +533,4 @@ def cancel( if cls: return cls(pipeline_response, None, {}) - cancel.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}/cancel'} # type: ignore + cancel.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentScheduleRequests/{roleAssignmentScheduleRequestName}/cancel"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedules_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedules_operations.py index 459616f2e5c..2469f234a69 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedules_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignment_schedules_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,161 +6,232 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class RoleAssignmentSchedulesOperations(object): - """RoleAssignmentSchedulesOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_get_request(scope: str, role_assignment_schedule_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules/{roleAssignmentScheduleName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentScheduleName": _SERIALIZER.url( + "role_assignment_schedule_name", role_assignment_schedule_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentSchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.AuthorizationManagementClient`'s + :attr:`role_assignment_schedules` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def get( - self, - scope, # type: str - role_assignment_schedule_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentSchedule" + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, role_assignment_schedule_name: str, **kwargs: Any) -> _models.RoleAssignmentSchedule: """Get the specified role assignment schedule for a resource scope. - :param scope: The scope of the role assignment schedule. + :param scope: The scope of the role assignment schedule. Required. :type scope: str :param role_assignment_schedule_name: The name (guid) of the role assignment schedule to get. + Required. :type role_assignment_schedule_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentSchedule, or the result of cls(response) + :return: RoleAssignmentSchedule or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentSchedule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentSchedule"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentScheduleName': self._serialize.url("role_assignment_schedule_name", role_assignment_schedule_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentSchedule] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + role_assignment_schedule_name=role_assignment_schedule_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentSchedule', pipeline_response) + deserialized = self._deserialize("RoleAssignmentSchedule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules/{roleAssignmentScheduleName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules/{roleAssignmentScheduleName}"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentScheduleListResult"] + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignmentSchedule"]: """Gets role assignment schedules for a resource scope. - :param scope: The scope of the role assignments schedules. + :param scope: The scope of the role assignments schedules. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role assignment schedules for the current user. Use $filter=asTarget() to return all role assignment schedules created for the current user. + Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentScheduleListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentScheduleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignmentSchedule or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentSchedule] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentScheduleListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentScheduleListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentScheduleListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentScheduleListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -168,7 +240,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -177,7 +251,6 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentSchedules"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignments_operations.py index 08463b4693b..56df6f58e24 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,103 +6,491 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_subscription_request( + subscription_id: str, *, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_group_request( + resource_group_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceProviderNamespace": _SERIALIZER.url( + "resource_provider_namespace", resource_provider_namespace, "str", skip_quote=True + ), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + scope: str, role_assignment_name: str, *, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + scope: str, role_assignment_name: str, *, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_validate_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}/validate" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request( + scope: str, *, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(role_assignment_id: str, *, tenant_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop("template_url", "/{roleAssignmentId}") + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str", skip_quote=True), + } -class RoleAssignmentsOperations(object): - """RoleAssignmentsOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_by_id_request(role_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleAssignmentId}") + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request( + role_assignment_id: str, *, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleAssignmentId}") + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_validate_by_id_request(role_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleAssignmentId}/validate") + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_subscription( - self, - filter=None, # type: Optional[str] - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """List all role assignments that apply to a subscription. :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_subscription_request( + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -110,82 +499,86 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_resource_group( - self, - resource_group_name, # type: str - filter=None, # type: Optional[str] - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, resource_group_name: str, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """List all role assignments that apply to a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -194,95 +587,103 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + @distributed_trace def list_for_resource( self, - resource_group_name, # type: str - resource_provider_namespace, # type: str - resource_type, # type: str - resource_name, # type: str - filter=None, # type: Optional[str] - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """List all role assignments that apply to a resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param resource_provider_namespace: The namespace of the resource provider. + :param resource_provider_namespace: The namespace of the resource provider. Required. :type resource_provider_namespace: str :param resource_type: The resource type name. For example the type name of a web app is 'sites' - (from Microsoft.Web/sites). + (from Microsoft.Web/sites). Required. :type resource_type: str - :param resource_name: The resource name. + :param resource_name: The resource name. Required. :type resource_name: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'resourceProviderNamespace': self._serialize.url("resource_provider_namespace", resource_provider_namespace, 'str', skip_quote=True), - 'resourceType': self._serialize.url("resource_type", resource_type, 'str', skip_quote=True), - 'resourceName': self._serialize.url("resource_name", resource_name, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -291,364 +692,536 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace def get( - self, - scope, # type: str - role_assignment_name, # type: str - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> _models.RoleAssignment: """Get a role assignment by scope and name. :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. :type scope: str :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. :type role_assignment_name: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload + def create( + self, + scope: str, + role_assignment_name: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload def create( self, - scope, # type: str - role_assignment_name, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: """Create or update a role assignment by scope and name. :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. :type scope: str :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace def delete( - self, - scope, # type: str - role_assignment_name, # type: str - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleAssignment"] + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: """Delete a role assignment by scope and name. :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. :type scope: str :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. :type role_assignment_name: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload + def validate( + self, + scope: str, + role_assignment_name: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ValidationResponse: + """Validate a role assignment create or update operation by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidationResponse or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload def validate( self, - scope, # type: str - role_assignment_name, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.ValidationResponse" + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ValidationResponse: """Validate a role assignment create or update operation by scope and name. :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. :type scope: str :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. :type role_assignment_name: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ValidationResponse, or the result of cls(response) + :return: ValidationResponse or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def validate( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.ValidationResponse: + """Validate a role assignment create or update operation by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidationResponse or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ValidationResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.validate.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidationResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_validate_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ValidationResponse', pipeline_response) + deserialized = self._deserialize("ValidationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - validate.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}/validate'} # type: ignore + validate.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}/validate"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentListResult"] + self, scope: str, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: """List all role assignments that apply to a scope. :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role - assignments at, above or below the scope for the specified principal. + assignments at, above or below the scope for the specified principal. Default value is None. :type filter: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -657,281 +1230,416 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace def get_by_id( - self, - role_assignment_id, # type: str - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + self, role_assignment_id: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> _models.RoleAssignment: """Get a role assignment by ID. :param role_assignment_id: The fully qualified ID of the role assignment including scope, resource name, and resource type. Format: /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. :type role_assignment_id: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + role_assignment_id=role_assignment_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore + get_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @overload def create_by_id( self, - role_assignment_id, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignment" + role_assignment_id: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: """Create or update a role assignment by ID. :param role_assignment_id: The fully qualified ID of the role assignment including scope, resource name, and resource type. Format: /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. :type role_assignment_id: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_by_id( + self, role_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_by_id( + self, role_assignment_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore + create_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @distributed_trace def delete_by_id( - self, - role_assignment_id, # type: str - tenant_id=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.RoleAssignment"] + self, role_assignment_id: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: """Delete a role assignment by ID. :param role_assignment_id: The fully qualified ID of the role assignment including scope, resource name, and resource type. Format: /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. :type role_assignment_id: str - :param tenant_id: Tenant ID for cross-tenant request. + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. :type tenant_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignment, or the result of cls(response) + :return: RoleAssignment or None or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignment or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.RoleAssignment"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if tenant_id is not None: - query_parameters['tenantId'] = self._serialize.query("tenant_id", tenant_id, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_delete_by_id_request( + role_assignment_id=role_assignment_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('RoleAssignment', pipeline_response) + deserialized = self._deserialize("RoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_id.metadata = {'url': '/{roleAssignmentId}'} # type: ignore + delete_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @overload def validate_by_id( self, - role_assignment_id, # type: str - parameters, # type: "_models.RoleAssignmentCreateParameters" - **kwargs # type: Any - ): - # type: (...) -> "_models.ValidationResponse" + role_assignment_id: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ValidationResponse: + """Validate a role assignment create or update operation by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidationResponse or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def validate_by_id( + self, role_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ValidationResponse: """Validate a role assignment create or update operation by ID. :param role_assignment_id: The fully qualified ID of the role assignment including scope, resource name, and resource type. Format: /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. :type role_assignment_id: str - :param parameters: Parameters for the role assignment. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ValidationResponse, or the result of cls(response) + :return: ValidationResponse or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def validate_by_id( + self, role_assignment_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.ValidationResponse: + """Validate a role assignment create or update operation by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleAssignmentCreateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidationResponse or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.ValidationResponse + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ValidationResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.validate_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'roleAssignmentId': self._serialize.url("role_assignment_id", role_assignment_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidationResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_validate_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ValidationResponse', pipeline_response) + deserialized = self._deserialize("ValidationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - validate_by_id.metadata = {'url': '/{roleAssignmentId}/validate'} # type: ignore + + validate_by_id.metadata = {"url": "/{roleAssignmentId}/validate"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedule_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedule_instances_operations.py index 0d44db0bf21..1a2d7a87d2c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedule_instances_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedule_instances_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,103 +6,174 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class RoleEligibilityScheduleInstancesOperations(object): - """RoleEligibilityScheduleInstancesOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_eligibility_schedule_instance_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances/{roleEligibilityScheduleInstanceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleEligibilityScheduleInstanceName": _SERIALIZER.url( + "role_eligibility_schedule_instance_name", role_eligibility_schedule_instance_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleEligibilityScheduleInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedule_instances` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleEligibilityScheduleInstanceListResult"] + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleEligibilityScheduleInstance"]: """Gets role eligibility schedule instances of a role eligibility schedule. - :param scope: The scope of the role eligibility schedule. + :param scope: The scope of the role eligibility schedule. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role assignment schedules at or above the scope. Use $filter=principalId eq {id} to return all role assignment schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use $filter=asTarget() to return all role eligibility schedules created for the current user. + Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleEligibilityScheduleInstanceListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleEligibilityScheduleInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleEligibilityScheduleInstanceListResult', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -110,7 +182,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -119,66 +193,66 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances'} # type: ignore + return ItemPaged(get_next, extract_data) + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances"} # type: ignore + + @distributed_trace def get( - self, - scope, # type: str - role_eligibility_schedule_instance_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleEligibilityScheduleInstance" + self, scope: str, role_eligibility_schedule_instance_name: str, **kwargs: Any + ) -> _models.RoleEligibilityScheduleInstance: """Gets the specified role eligibility schedule instance. - :param scope: The scope of the role eligibility schedules. + :param scope: The scope of the role eligibility schedules. Required. :type scope: str :param role_eligibility_schedule_instance_name: The name (hash of schedule name + time) of the - role eligibility schedule to get. + role eligibility schedule to get. Required. :type role_eligibility_schedule_instance_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleEligibilityScheduleInstance, or the result of cls(response) + :return: RoleEligibilityScheduleInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleEligibilityScheduleInstanceName': self._serialize.url("role_eligibility_schedule_instance_name", role_eligibility_schedule_instance_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleInstance] + + request = build_get_request( + scope=scope, + role_eligibility_schedule_instance_name=role_eligibility_schedule_instance_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleEligibilityScheduleInstance', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances/{roleEligibilityScheduleInstanceName}'} # type: ignore + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleInstances/{roleEligibilityScheduleInstanceName}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedule_requests_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedule_requests_operations.py index ea97a5f6868..6c9e9f8dcb3 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedule_requests_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedule_requests_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,54 +6,184 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_request(scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleEligibilityScheduleRequestName": _SERIALIZER.url( + "role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleEligibilityScheduleRequestName": _SERIALIZER.url( + "role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class RoleEligibilityScheduleRequestsOperations(object): - """RoleEligibilityScheduleRequestsOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +def build_cancel_request(scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}/cancel", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleEligibilityScheduleRequestName": _SERIALIZER.url( + "role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleEligibilityScheduleRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedule_requests` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @overload def create( self, - scope, # type: str - role_eligibility_schedule_request_name, # type: str - parameters, # type: "_models.RoleEligibilityScheduleRequest" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleEligibilityScheduleRequest" + scope: str, + role_eligibility_schedule_request_name: str, + parameters: _models.RoleEligibilityScheduleRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: """Creates a role eligibility schedule request. :param scope: The scope of the role eligibility schedule request to create. The scope can be @@ -61,132 +192,213 @@ def create( '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' - for a resource. + for a resource. Required. :type scope: str :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It - can be any valid GUID. + can be any valid GUID. Required. :type role_eligibility_schedule_request_name: str - :param parameters: Parameters for the role eligibility schedule request. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleEligibilityScheduleRequest, or the result of cls(response) + :return: RoleEligibilityScheduleRequest or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Creates a role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request to create. The scope can be + any REST resource instance. For example, use + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It + can be any valid GUID. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_eligibility_schedule_request_name: str, + parameters: Union[_models.RoleEligibilityScheduleRequest, IO], + **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: + """Creates a role eligibility schedule request. + + :param scope: The scope of the role eligibility schedule request to create. The scope can be + any REST resource instance. For example, use + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param role_eligibility_schedule_request_name: The name of the role eligibility to create. It + can be any valid GUID. Required. + :type role_eligibility_schedule_request_name: str + :param parameters: Parameters for the role eligibility schedule request. Is either a model type + or a IO type. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleEligibilityScheduleRequest or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleRequest"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleEligibilityScheduleRequestName': self._serialize.url("role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleEligibilityScheduleRequest') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleEligibilityScheduleRequest") + + request = build_create_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleEligibilityScheduleRequest', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleRequest", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}'} # type: ignore + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}"} # type: ignore + + @distributed_trace def get( - self, - scope, # type: str - role_eligibility_schedule_request_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleEligibilityScheduleRequest" + self, scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any + ) -> _models.RoleEligibilityScheduleRequest: """Get the specified role eligibility schedule request. - :param scope: The scope of the role eligibility schedule request. + :param scope: The scope of the role eligibility schedule request. Required. :type scope: str :param role_eligibility_schedule_request_name: The name (guid) of the role eligibility schedule - request to get. + request to get. Required. :type role_eligibility_schedule_request_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleEligibilityScheduleRequest, or the result of cls(response) + :return: RoleEligibilityScheduleRequest or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleRequest"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleEligibilityScheduleRequestName': self._serialize.url("role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequest] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleEligibilityScheduleRequest', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleRequest", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleEligibilityScheduleRequestListResult"] + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleEligibilityScheduleRequest"]: """Gets role eligibility schedule requests for a scope. - :param scope: The scope of the role eligibility schedule requests. + :param scope: The scope of the role eligibility schedule requests. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role eligibility schedule requests at or above the scope. Use $filter=principalId eq {id} to return @@ -194,48 +406,56 @@ def list_for_scope( principal. Use $filter=asRequestor() to return all role eligibility schedule requests requested by the current user. Use $filter=asTarget() to return all role eligibility schedule requests created for the current user. Use $filter=asApprover() to return all role eligibility schedule - requests where the current user is an approver. + requests where the current user is an approver. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleEligibilityScheduleRequestListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequestListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleEligibilityScheduleRequest or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleRequest] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleRequestListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleRequestListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleEligibilityScheduleRequestListResult', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleRequestListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -244,7 +464,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -253,56 +475,55 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests'} # type: ignore + return ItemPaged(get_next, extract_data) - def cancel( - self, - scope, # type: str - role_eligibility_schedule_request_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests"} # type: ignore + + @distributed_trace + def cancel( # pylint: disable=inconsistent-return-statements + self, scope: str, role_eligibility_schedule_request_name: str, **kwargs: Any + ) -> None: """Cancels a pending role eligibility schedule request. - :param scope: The scope of the role eligibility request to cancel. + :param scope: The scope of the role eligibility request to cancel. Required. :type scope: str :param role_eligibility_schedule_request_name: The name of the role eligibility request to - cancel. + cancel. Required. :type role_eligibility_schedule_request_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.cancel.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleEligibilityScheduleRequestName': self._serialize.url("role_eligibility_schedule_request_name", role_eligibility_schedule_request_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_cancel_request( + scope=scope, + role_eligibility_schedule_request_name=role_eligibility_schedule_request_name, + api_version=api_version, + template_url=self.cancel.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -312,4 +533,4 @@ def cancel( if cls: return cls(pipeline_response, None, {}) - cancel.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}/cancel'} # type: ignore + cancel.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilityScheduleRequests/{roleEligibilityScheduleRequestName}/cancel"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedules_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedules_operations.py index a3d1b5ff832..36916d3915b 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedules_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_eligibility_schedules_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,161 +6,232 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class RoleEligibilitySchedulesOperations(object): - """RoleEligibilitySchedulesOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_get_request(scope: str, role_eligibility_schedule_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules/{roleEligibilityScheduleName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleEligibilityScheduleName": _SERIALIZER.url( + "role_eligibility_schedule_name", role_eligibility_schedule_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleEligibilitySchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.AuthorizationManagementClient`'s + :attr:`role_eligibility_schedules` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def get( - self, - scope, # type: str - role_eligibility_schedule_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleEligibilitySchedule" + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, role_eligibility_schedule_name: str, **kwargs: Any) -> _models.RoleEligibilitySchedule: """Get the specified role eligibility schedule for a resource scope. - :param scope: The scope of the role eligibility schedule. + :param scope: The scope of the role eligibility schedule. Required. :type scope: str :param role_eligibility_schedule_name: The name (guid) of the role eligibility schedule to get. + Required. :type role_eligibility_schedule_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleEligibilitySchedule, or the result of cls(response) + :return: RoleEligibilitySchedule or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilitySchedule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilitySchedule"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleEligibilityScheduleName': self._serialize.url("role_eligibility_schedule_name", role_eligibility_schedule_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilitySchedule] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + role_eligibility_schedule_name=role_eligibility_schedule_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleEligibilitySchedule', pipeline_response) + deserialized = self._deserialize("RoleEligibilitySchedule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules/{roleEligibilityScheduleName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules/{roleEligibilityScheduleName}"} # type: ignore + + @distributed_trace def list_for_scope( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleEligibilityScheduleListResult"] + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleEligibilitySchedule"]: """Gets role eligibility schedules for a resource scope. - :param scope: The scope of the role eligibility schedules. + :param scope: The scope of the role eligibility schedules. Required. :type scope: str :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role eligibility schedules at or above the scope. Use $filter=principalId eq {id} to return all role eligibility schedules at, above or below the scope for the specified principal. Use $filter=assignedTo('{userId}') to return all role eligibility schedules for the user. Use $filter=asTarget() to return all role eligibility schedules created for the current user. + Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleEligibilityScheduleListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilityScheduleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleEligibilitySchedule or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleEligibilitySchedule] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleEligibilityScheduleListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleEligibilityScheduleListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleEligibilityScheduleListResult', pipeline_response) + deserialized = self._deserialize("RoleEligibilityScheduleListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -168,7 +240,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -177,7 +251,6 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleEligibilitySchedules"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_management_policies_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_management_policies_operations.py index bbf34302c89..a2f0dc0556d 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_management_policies_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_management_policies_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,214 +6,405 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, role_management_policy_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyName": _SERIALIZER.url("role_management_policy_name", role_management_policy_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request(scope: str, role_management_policy_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyName": _SERIALIZER.url("role_management_policy_name", role_management_policy_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(scope: str, role_management_policy_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyName": _SERIALIZER.url("role_management_policy_name", role_management_policy_name, "str"), + } -class RoleManagementPoliciesOperations(object): - """RoleManagementPoliciesOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleManagementPoliciesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.AuthorizationManagementClient`'s + :attr:`role_management_policies` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def get( - self, - scope, # type: str - role_management_policy_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleManagementPolicy" + @distributed_trace + def get(self, scope: str, role_management_policy_name: str, **kwargs: Any) -> _models.RoleManagementPolicy: """Get the specified role management policy for a resource scope. - :param scope: The scope of the role management policy. + :param scope: The scope of the role management policy. Required. :type scope: str :param role_management_policy_name: The name (guid) of the role management policy to get. + Required. :type role_management_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleManagementPolicy, or the result of cls(response) + :return: RoleManagementPolicy or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyName': self._serialize.url("role_management_policy_name", role_management_policy_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicy] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleManagementPolicy', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore + + @overload def update( self, - scope, # type: str - role_management_policy_name, # type: str - parameters, # type: "_models.RoleManagementPolicy" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleManagementPolicy" + scope: str, + role_management_policy_name: str, + parameters: _models.RoleManagementPolicy, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicy: """Update a role management policy. - :param scope: The scope of the role management policy to upsert. + :param scope: The scope of the role management policy to upsert. Required. :type scope: str :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. :type role_management_policy_name: str - :param parameters: Parameters for the role management policy. + :param parameters: Parameters for the role management policy. Required. :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleManagementPolicy, or the result of cls(response) + :return: RoleManagementPolicy or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + scope: str, + role_management_policy_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicy: + """Update a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :param parameters: Parameters for the role management policy. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + scope: str, + role_management_policy_name: str, + parameters: Union[_models.RoleManagementPolicy, IO], + **kwargs: Any + ) -> _models.RoleManagementPolicy: + """Update a role management policy. + + :param scope: The scope of the role management policy to upsert. Required. + :type scope: str + :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. + :type role_management_policy_name: str + :param parameters: Parameters for the role management policy. Is either a model type or a IO + type. Required. + :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicy or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyName': self._serialize.url("role_management_policy_name", role_management_policy_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleManagementPolicy') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicy] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleManagementPolicy") + + request = build_update_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleManagementPolicy', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}'} # type: ignore - def delete( - self, - scope, # type: str - role_management_policy_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, role_management_policy_name: str, **kwargs: Any + ) -> None: """Delete a role management policy. - :param scope: The scope of the role management policy to upsert. + :param scope: The scope of the role management policy to upsert. Required. :type scope: str :param role_management_policy_name: The name (guid) of the role management policy to upsert. + Required. :type role_management_policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyName': self._serialize.url("role_management_policy_name", role_management_policy_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_delete_request( + scope=scope, + role_management_policy_name=role_management_policy_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -222,56 +414,61 @@ def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies/{roleManagementPolicyName}"} # type: ignore - def list_for_scope( - self, - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleManagementPolicyListResult"] + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.RoleManagementPolicy"]: """Gets role management policies for a resource scope. - :param scope: The scope of the role management policy. + :param scope: The scope of the role management policy. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleManagementPolicyListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleManagementPolicy or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicy] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicyListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleManagementPolicyListResult', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicyListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -280,7 +477,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -289,7 +488,6 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicies'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicies"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_management_policy_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_management_policy_assignments_operations.py index fea0ec5db6e..d74864306f3 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_management_policy_assignments_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2020_10_01_preview/operations/_role_management_policy_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,217 +6,417 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, role_management_policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyAssignmentName": _SERIALIZER.url( + "role_management_policy_assignment_name", role_management_policy_assignment_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(scope: str, role_management_policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyAssignmentName": _SERIALIZER.url( + "role_management_policy_assignment_name", role_management_policy_assignment_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(scope: str, role_management_policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleManagementPolicyAssignmentName": _SERIALIZER.url( + "role_management_policy_assignment_name", role_management_policy_assignment_name, "str" + ), + } -class RoleManagementPolicyAssignmentsOperations(object): - """RoleManagementPolicyAssignmentsOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2020_10_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleManagementPolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2020_10_01_preview.AuthorizationManagementClient`'s + :attr:`role_management_policy_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def get( - self, - scope, # type: str - role_management_policy_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleManagementPolicyAssignment" + self, scope: str, role_management_policy_assignment_name: str, **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: """Get the specified role management policy assignment for a resource scope. - :param scope: The scope of the role management policy. + :param scope: The scope of the role management policy. Required. :type scope: str :param role_management_policy_assignment_name: The name of format {guid_guid} the role - management policy assignment to get. + management policy assignment to get. Required. :type role_management_policy_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleManagementPolicyAssignment, or the result of cls(response) + :return: RoleManagementPolicyAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicyAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyAssignmentName': self._serialize.url("role_management_policy_assignment_name", role_management_policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignment] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleManagementPolicyAssignment', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicyAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore + + @overload def create( self, - scope, # type: str - role_management_policy_assignment_name, # type: str - parameters, # type: "_models.RoleManagementPolicyAssignment" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleManagementPolicyAssignment" + scope: str, + role_management_policy_assignment_name: str, + parameters: _models.RoleManagementPolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: """Create a role management policy assignment. - :param scope: The scope of the role management policy assignment to upsert. + :param scope: The scope of the role management policy assignment to upsert. Required. :type scope: str :param role_management_policy_assignment_name: The name of format {guid_guid} the role - management policy assignment to upsert. + management policy assignment to upsert. Required. :type role_management_policy_assignment_name: str - :param parameters: Parameters for the role management policy assignment. - :type parameters: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment + :param parameters: Parameters for the role management policy assignment. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleManagementPolicyAssignment, or the result of cls(response) + :return: RoleManagementPolicyAssignment or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + role_management_policy_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Create a role management policy assignment. + + :param scope: The scope of the role management policy assignment to upsert. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to upsert. Required. + :type role_management_policy_assignment_name: str + :param parameters: Parameters for the role management policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_management_policy_assignment_name: str, + parameters: Union[_models.RoleManagementPolicyAssignment, IO], + **kwargs: Any + ) -> _models.RoleManagementPolicyAssignment: + """Create a role management policy assignment. + + :param scope: The scope of the role management policy assignment to upsert. Required. + :type scope: str + :param role_management_policy_assignment_name: The name of format {guid_guid} the role + management policy assignment to upsert. Required. + :type role_management_policy_assignment_name: str + :param parameters: Parameters for the role management policy assignment. Is either a model type + or a IO type. Required. + :type parameters: + ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleManagementPolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicyAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyAssignmentName': self._serialize.url("role_management_policy_assignment_name", role_management_policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'RoleManagementPolicyAssignment') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleManagementPolicyAssignment") + + request = build_create_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleManagementPolicyAssignment', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicyAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}'} # type: ignore - def delete( - self, - scope, # type: str - role_management_policy_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, role_management_policy_assignment_name: str, **kwargs: Any + ) -> None: """Delete a role management policy assignment. - :param scope: The scope of the role management policy assignment to delete. + :param scope: The scope of the role management policy assignment to delete. Required. :type scope: str :param role_management_policy_assignment_name: The name of format {guid_guid} the role - management policy assignment to delete. + management policy assignment to delete. Required. :type role_management_policy_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'roleManagementPolicyAssignmentName': self._serialize.url("role_management_policy_assignment_name", role_management_policy_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_delete_request( + scope=scope, + role_management_policy_assignment_name=role_management_policy_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -225,56 +426,61 @@ def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments/{roleManagementPolicyAssignmentName}"} # type: ignore - def list_for_scope( - self, - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleManagementPolicyAssignmentListResult"] + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.RoleManagementPolicyAssignment"]: """Gets role management assignment policies for a resource scope. - :param scope: The scope of the role management policy. + :param scope: The scope of the role management policy. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleManagementPolicyAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleManagementPolicyAssignment or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2020_10_01_preview.models.RoleManagementPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleManagementPolicyAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleManagementPolicyAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-10-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleManagementPolicyAssignmentListResult', pipeline_response) + deserialized = self._deserialize("RoleManagementPolicyAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -283,7 +489,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -292,7 +500,6 @@ def get_next(next_link=None): return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementPolicyAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/__init__.py index ae11ad3e4d9..9eb8d3ec28c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AuthorizationManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_authorization_management_client.py index 9ef3cafd5e6..44d345ff7a1 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_authorization_management_client.py @@ -6,97 +6,115 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + Operations, + RoleAssignmentApprovalOperations, + RoleAssignmentApprovalStepOperations, + RoleAssignmentApprovalStepsOperations, + ScopeRoleAssignmentApprovalOperations, + ScopeRoleAssignmentApprovalStepOperations, + ScopeRoleAssignmentApprovalStepsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import Operations -from .operations import RoleAssignmentApprovalOperations -from .operations import RoleAssignmentApprovalStepsOperations -from .operations import RoleAssignmentApprovalStepOperations -from .operations import ScopeRoleAssignmentApprovalOperations -from .operations import ScopeRoleAssignmentApprovalStepsOperations -from .operations import ScopeRoleAssignmentApprovalStepOperations -from . import models -class AuthorizationManagementClient(object): - """Request Approvals service provides the workflow for running request approvals on different kind of resources. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Request Approvals service provides the workflow for running request approvals on different kind + of resources. :ivar operations: Operations operations :vartype operations: azure.mgmt.authorization.v2021_01_01_preview.operations.Operations :ivar role_assignment_approval: RoleAssignmentApprovalOperations operations - :vartype role_assignment_approval: azure.mgmt.authorization.v2021_01_01_preview.operations.RoleAssignmentApprovalOperations + :vartype role_assignment_approval: + azure.mgmt.authorization.v2021_01_01_preview.operations.RoleAssignmentApprovalOperations :ivar role_assignment_approval_steps: RoleAssignmentApprovalStepsOperations operations - :vartype role_assignment_approval_steps: azure.mgmt.authorization.v2021_01_01_preview.operations.RoleAssignmentApprovalStepsOperations + :vartype role_assignment_approval_steps: + azure.mgmt.authorization.v2021_01_01_preview.operations.RoleAssignmentApprovalStepsOperations :ivar role_assignment_approval_step: RoleAssignmentApprovalStepOperations operations - :vartype role_assignment_approval_step: azure.mgmt.authorization.v2021_01_01_preview.operations.RoleAssignmentApprovalStepOperations + :vartype role_assignment_approval_step: + azure.mgmt.authorization.v2021_01_01_preview.operations.RoleAssignmentApprovalStepOperations :ivar scope_role_assignment_approval: ScopeRoleAssignmentApprovalOperations operations - :vartype scope_role_assignment_approval: azure.mgmt.authorization.v2021_01_01_preview.operations.ScopeRoleAssignmentApprovalOperations - :ivar scope_role_assignment_approval_steps: ScopeRoleAssignmentApprovalStepsOperations operations - :vartype scope_role_assignment_approval_steps: azure.mgmt.authorization.v2021_01_01_preview.operations.ScopeRoleAssignmentApprovalStepsOperations + :vartype scope_role_assignment_approval: + azure.mgmt.authorization.v2021_01_01_preview.operations.ScopeRoleAssignmentApprovalOperations + :ivar scope_role_assignment_approval_steps: ScopeRoleAssignmentApprovalStepsOperations + operations + :vartype scope_role_assignment_approval_steps: + azure.mgmt.authorization.v2021_01_01_preview.operations.ScopeRoleAssignmentApprovalStepsOperations :ivar scope_role_assignment_approval_step: ScopeRoleAssignmentApprovalStepOperations operations - :vartype scope_role_assignment_approval_step: azure.mgmt.authorization.v2021_01_01_preview.operations.ScopeRoleAssignmentApprovalStepOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype scope_role_assignment_approval_step: + azure.mgmt.authorization.v2021_01_01_preview.operations.ScopeRoleAssignmentApprovalStepOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2021-01-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( - self, - credential, # type: "TokenCredential" - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, **kwargs) + self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration(credential=credential, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.role_assignment_approval = RoleAssignmentApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignment_approval_steps = RoleAssignmentApprovalStepsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignment_approval_step = RoleAssignmentApprovalStepOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.scope_role_assignment_approval = ScopeRoleAssignmentApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.scope_role_assignment_approval_steps = ScopeRoleAssignmentApprovalStepsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.scope_role_assignment_approval_step = ScopeRoleAssignmentApprovalStepOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - http_request.url = self._client.format_url(http_request.url) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_configuration.py index 95df76e19b2..ac72476dce7 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_configuration.py @@ -6,60 +6,59 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential + :keyword api_version: Api Version. Default value is "2021-01-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2021-01-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential - self.api_version = "2021-01-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_metadata.json index 143a0ba7ab5..985abca5526 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_metadata.json +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_metadata.json @@ -5,19 +5,19 @@ "name": "AuthorizationManagementClient", "filename": "_authorization_management_client", "description": "Request Approvals service provides the workflow for running request approvals on different kind of resources.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, "azure_arm": true, "has_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true } @@ -25,7 +25,7 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true } @@ -42,7 +42,7 @@ "required": false }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -62,7 +62,7 @@ "required": false }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -79,11 +79,10 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "operations": "Operations", diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_version.py index 48944bf3938..cac9f5d10f8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/__init__.py index ffc49d028e4..dd28625b36f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._authorization_management_client import AuthorizationManagementClient -__all__ = ['AuthorizationManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_authorization_management_client.py index 4d7b16fdf35..1bdb789a147 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_authorization_management_client.py @@ -6,93 +6,115 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + Operations, + RoleAssignmentApprovalOperations, + RoleAssignmentApprovalStepOperations, + RoleAssignmentApprovalStepsOperations, + ScopeRoleAssignmentApprovalOperations, + ScopeRoleAssignmentApprovalStepOperations, + ScopeRoleAssignmentApprovalStepsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import Operations -from .operations import RoleAssignmentApprovalOperations -from .operations import RoleAssignmentApprovalStepsOperations -from .operations import RoleAssignmentApprovalStepOperations -from .operations import ScopeRoleAssignmentApprovalOperations -from .operations import ScopeRoleAssignmentApprovalStepsOperations -from .operations import ScopeRoleAssignmentApprovalStepOperations -from .. import models - -class AuthorizationManagementClient(object): - """Request Approvals service provides the workflow for running request approvals on different kind of resources. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Request Approvals service provides the workflow for running request approvals on different kind + of resources. :ivar operations: Operations operations :vartype operations: azure.mgmt.authorization.v2021_01_01_preview.aio.operations.Operations :ivar role_assignment_approval: RoleAssignmentApprovalOperations operations - :vartype role_assignment_approval: azure.mgmt.authorization.v2021_01_01_preview.aio.operations.RoleAssignmentApprovalOperations + :vartype role_assignment_approval: + azure.mgmt.authorization.v2021_01_01_preview.aio.operations.RoleAssignmentApprovalOperations :ivar role_assignment_approval_steps: RoleAssignmentApprovalStepsOperations operations - :vartype role_assignment_approval_steps: azure.mgmt.authorization.v2021_01_01_preview.aio.operations.RoleAssignmentApprovalStepsOperations + :vartype role_assignment_approval_steps: + azure.mgmt.authorization.v2021_01_01_preview.aio.operations.RoleAssignmentApprovalStepsOperations :ivar role_assignment_approval_step: RoleAssignmentApprovalStepOperations operations - :vartype role_assignment_approval_step: azure.mgmt.authorization.v2021_01_01_preview.aio.operations.RoleAssignmentApprovalStepOperations + :vartype role_assignment_approval_step: + azure.mgmt.authorization.v2021_01_01_preview.aio.operations.RoleAssignmentApprovalStepOperations :ivar scope_role_assignment_approval: ScopeRoleAssignmentApprovalOperations operations - :vartype scope_role_assignment_approval: azure.mgmt.authorization.v2021_01_01_preview.aio.operations.ScopeRoleAssignmentApprovalOperations - :ivar scope_role_assignment_approval_steps: ScopeRoleAssignmentApprovalStepsOperations operations - :vartype scope_role_assignment_approval_steps: azure.mgmt.authorization.v2021_01_01_preview.aio.operations.ScopeRoleAssignmentApprovalStepsOperations + :vartype scope_role_assignment_approval: + azure.mgmt.authorization.v2021_01_01_preview.aio.operations.ScopeRoleAssignmentApprovalOperations + :ivar scope_role_assignment_approval_steps: ScopeRoleAssignmentApprovalStepsOperations + operations + :vartype scope_role_assignment_approval_steps: + azure.mgmt.authorization.v2021_01_01_preview.aio.operations.ScopeRoleAssignmentApprovalStepsOperations :ivar scope_role_assignment_approval_step: ScopeRoleAssignmentApprovalStepOperations operations - :vartype scope_role_assignment_approval_step: azure.mgmt.authorization.v2021_01_01_preview.aio.operations.ScopeRoleAssignmentApprovalStepOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype scope_role_assignment_approval_step: + azure.mgmt.authorization.v2021_01_01_preview.aio.operations.ScopeRoleAssignmentApprovalStepOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2021-01-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( - self, - credential: "AsyncTokenCredential", - base_url: Optional[str] = None, - **kwargs: Any + self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, **kwargs) + self._config = AuthorizationManagementClientConfiguration(credential=credential, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.role_assignment_approval = RoleAssignmentApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignment_approval_steps = RoleAssignmentApprovalStepsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.role_assignment_approval_step = RoleAssignmentApprovalStepOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.scope_role_assignment_approval = ScopeRoleAssignmentApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.scope_role_assignment_approval_steps = ScopeRoleAssignmentApprovalStepsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.scope_role_assignment_approval_step = ScopeRoleAssignmentApprovalStepOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - http_request.url = self._client.format_url(http_request.url) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_configuration.py index bb368f50e81..2259bb63e28 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,43 +19,43 @@ from azure.core.credentials_async import AsyncTokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: Api Version. Default value is "2021-01-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2021-01-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential - self.api_version = "2021-01-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/__init__.py index c5030cb2549..c9d41189173 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/__init__.py @@ -14,12 +14,18 @@ from ._scope_role_assignment_approval_steps_operations import ScopeRoleAssignmentApprovalStepsOperations from ._scope_role_assignment_approval_step_operations import ScopeRoleAssignmentApprovalStepOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'Operations', - 'RoleAssignmentApprovalOperations', - 'RoleAssignmentApprovalStepsOperations', - 'RoleAssignmentApprovalStepOperations', - 'ScopeRoleAssignmentApprovalOperations', - 'ScopeRoleAssignmentApprovalStepsOperations', - 'ScopeRoleAssignmentApprovalStepOperations', + "Operations", + "RoleAssignmentApprovalOperations", + "RoleAssignmentApprovalStepsOperations", + "RoleAssignmentApprovalStepOperations", + "ScopeRoleAssignmentApprovalOperations", + "ScopeRoleAssignmentApprovalStepsOperations", + "ScopeRoleAssignmentApprovalStepOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_operations.py index 86197f34d0c..fb47a071d82 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,101 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.aio.AuthorizationManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists the operations available from this provider. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -89,17 +109,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/operations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_operations.py index 0e6672403f1..eefc4acbd8d 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,47 +6,55 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_assignment_approval_operations import build_get_by_id_request, build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentApprovalOperations: - """RoleAssignmentApprovalOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_assignment_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentApprovalListResult"]: + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.RoleAssignmentApproval"]: """Get role assignment approvals. :param filter: The filter to apply on the operation. Valid values for $filter are: @@ -55,44 +64,55 @@ def list( $filter=asCreatedBy() is provided, the returned list only includes all role assignment approvals that the calling user created requests for. If $filter=asTarget() is provided, the returned list only includes all role assignment approvals that the calling user has requests - targeted for. + targeted for. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentApprovalListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignmentApproval or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentApprovalListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -101,71 +121,73 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals"} # type: ignore - async def get_by_id( - self, - approval_id: str, - **kwargs: Any - ) -> "_models.RoleAssignmentApproval": + @distributed_trace_async + async def get_by_id(self, approval_id: str, **kwargs: Any) -> _models.RoleAssignmentApproval: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApproval, or the result of cls(response) + :return: RoleAssignmentApproval or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApproval"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApproval] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + approval_id=approval_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApproval', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApproval", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}'} # type: ignore + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_step_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_step_operations.py index 041f280a3e3..9b72f42600b 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_step_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_step_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,227 +6,372 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._role_assignment_approval_step_operations import ( + build_get_by_id_request, + build_patch_request, + build_put_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentApprovalStepOperations: - """RoleAssignmentApprovalStepOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentApprovalStepOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_assignment_approval_step` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get_by_id( - self, - approval_id: str, - stage_id: str, - **kwargs: Any - ) -> "_models.RoleAssignmentApprovalStep": + @distributed_trace_async + async def get_by_id(self, approval_id: str, stage_id: str, **kwargs: Any) -> _models.RoleAssignmentApprovalStep: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_by_id_request( + approval_id=approval_id, + stage_id=stage_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore + + @overload async def patch( self, approval_id: str, stage_id: str, - properties: "_models.RoleAssignmentApprovalStepProperties", + properties: _models.RoleAssignmentApprovalStepProperties, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignmentApprovalStep": + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param properties: Role Assignment Approval stage properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def patch( + self, approval_id: str, stage_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: """Record a decision. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str - :param properties: Role Assignment Approval stage properties to patch. - :type properties: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :param properties: Role Assignment Approval stage properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def patch( + self, + approval_id: str, + stage_id: str, + properties: Union[_models.RoleAssignmentApprovalStepProperties, IO], + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param properties: Role Assignment Approval stage properties to patch. Is either a model type + or a IO type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.patch.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'RoleAssignmentApprovalStepProperties') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "RoleAssignmentApprovalStepProperties") + + request = build_patch_request( + approval_id=approval_id, + stage_id=stage_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - patch.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + patch.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore + + @overload async def put( self, approval_id: str, stage_id: str, - properties: "_models.RoleAssignmentApprovalStepProperties", + properties: _models.RoleAssignmentApprovalStepProperties, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.RoleAssignmentApprovalStep": + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param properties: Role Assignment Approval stage properties to put. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put( + self, approval_id: str, stage_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: """Record a decision. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str - :param properties: Role Assignment Approval stage properties to put. - :type properties: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :param properties: Role Assignment Approval stage properties to put. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put( + self, + approval_id: str, + stage_id: str, + properties: Union[_models.RoleAssignmentApprovalStepProperties, IO], + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param properties: Role Assignment Approval stage properties to put. Is either a model type or + a IO type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.put.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'RoleAssignmentApprovalStepProperties') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "RoleAssignmentApprovalStepProperties") + + request = build_put_request( + approval_id=approval_id, + stage_id=stage_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + + put.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_steps_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_steps_operations.py index 746cf056422..f37091a75ad 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_steps_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_role_assignment_approval_steps_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,91 +6,102 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_assignment_approval_steps_operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RoleAssignmentApprovalStepsOperations: - """RoleAssignmentApprovalStepsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentApprovalStepsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.aio.AuthorizationManagementClient`'s + :attr:`role_assignment_approval_steps` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - async def list( - self, - approval_id: str, - **kwargs: Any - ) -> "_models.RoleAssignmentApprovalStepListResult": + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def list(self, approval_id: str, **kwargs: Any) -> _models.RoleAssignmentApprovalStepListResult: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStepListResult, or the result of cls(response) - :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepListResult - :raises: ~azure.core.exceptions.HttpResponseError + :return: RoleAssignmentApprovalStepListResult or the result of cls(response) + :rtype: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepListResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStepListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStepListResult] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_list_request( + approval_id=approval_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStepListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStepListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages'} # type: ignore + + list.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_operations.py index ac2f82cdfe7..5985d4f00f5 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,51 +6,60 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_role_assignment_approval_operations import build_get_by_id_request, build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ScopeRoleAssignmentApprovalOperations: - """ScopeRoleAssignmentApprovalOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ScopeRoleAssignmentApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_role_assignment_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RoleAssignmentApprovalListResult"]: + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignmentApproval"]: """Get role assignment approvals. - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str :param filter: The filter to apply on the operation. Valid values for $filter are: 'asApprover()', 'asCreatedBy()' and 'asTarget()'. If $filter is not provided, no filtering is @@ -58,48 +68,56 @@ def list( $filter=asCreatedBy() is provided, the returned list only includes all role assignment approvals that the calling user created requests for. If $filter=asTarget() is provided, the returned list only includes all role assignment approvals that the calling user has requests - targeted for. + targeted for. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentApprovalListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignmentApproval or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentApprovalListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -108,75 +126,76 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals'} # type: ignore - - async def get_by_id( - self, - approval_id: str, - scope: str, - **kwargs: Any - ) -> "_models.RoleAssignmentApproval": + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, approval_id: str, scope: str, **kwargs: Any) -> _models.RoleAssignmentApproval: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApproval, or the result of cls(response) + :return: RoleAssignmentApproval or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApproval"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApproval] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + approval_id=approval_id, + scope=scope, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApproval', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApproval", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}'} # type: ignore + + get_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_step_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_step_operations.py index e5134c9426a..1e1a68b0cc4 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_step_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_step_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,239 +6,409 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._scope_role_assignment_approval_step_operations import ( + build_get_by_id_request, + build_patch_request, + build_put_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ScopeRoleAssignmentApprovalStepOperations: - """ScopeRoleAssignmentApprovalStepOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ScopeRoleAssignmentApprovalStepOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_role_assignment_approval_step` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace_async async def get_by_id( - self, - approval_id: str, - stage_id: str, - scope: str, - **kwargs: Any - ) -> "_models.RoleAssignmentApprovalStep": + self, approval_id: str, stage_id: str, scope: str, **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] + + request = build_get_by_id_request( + approval_id=approval_id, + stage_id=stage_id, + scope=scope, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + get_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore + + @overload + async def patch( + self, + approval_id: str, + stage_id: str, + scope: str, + properties: _models.RoleAssignmentApprovalStepProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Role Assignment Approval stage properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def patch( + self, + approval_id: str, + stage_id: str, + scope: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Role Assignment Approval stage properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async async def patch( self, approval_id: str, stage_id: str, scope: str, - properties: "_models.RoleAssignmentApprovalStepProperties", + properties: Union[_models.RoleAssignmentApprovalStepProperties, IO], **kwargs: Any - ) -> "_models.RoleAssignmentApprovalStep": + ) -> _models.RoleAssignmentApprovalStep: """Record a decision. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str - :param properties: Role Assignment Approval stage properties to patch. - :type properties: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :param properties: Role Assignment Approval stage properties to patch. Is either a model type + or a IO type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.patch.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'RoleAssignmentApprovalStepProperties') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "RoleAssignmentApprovalStepProperties") + + request = build_patch_request( + approval_id=approval_id, + stage_id=stage_id, + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - patch.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + patch.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore + + @overload + async def put( + self, + approval_id: str, + stage_id: str, + scope: str, + properties: _models.RoleAssignmentApprovalStepProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Role Assignment Approval stage properties to put. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put( + self, + approval_id: str, + stage_id: str, + scope: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Role Assignment Approval stage properties to put. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async async def put( self, approval_id: str, stage_id: str, scope: str, - properties: "_models.RoleAssignmentApprovalStepProperties", + properties: Union[_models.RoleAssignmentApprovalStepProperties, IO], **kwargs: Any - ) -> "_models.RoleAssignmentApprovalStep": + ) -> _models.RoleAssignmentApprovalStep: """Record a decision. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str - :param properties: Role Assignment Approval stage properties to put. - :type properties: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :param properties: Role Assignment Approval stage properties to put. Is either a model type or + a IO type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.put.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'RoleAssignmentApprovalStepProperties') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "RoleAssignmentApprovalStepProperties") + + request = build_put_request( + approval_id=approval_id, + stage_id=stage_id, + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + + put.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_steps_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_steps_operations.py index d6b9c1f103b..647f003a7a7 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_steps_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/aio/operations/_scope_role_assignment_approval_steps_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,105 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_role_assignment_approval_steps_operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ScopeRoleAssignmentApprovalStepsOperations: - """ScopeRoleAssignmentApprovalStepsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ScopeRoleAssignmentApprovalStepsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_role_assignment_approval_steps` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - async def list( - self, - approval_id: str, - scope: str, - **kwargs: Any - ) -> "_models.RoleAssignmentApprovalStepListResult": + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def list(self, approval_id: str, scope: str, **kwargs: Any) -> _models.RoleAssignmentApprovalStepListResult: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStepListResult, or the result of cls(response) - :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepListResult - :raises: ~azure.core.exceptions.HttpResponseError + :return: RoleAssignmentApprovalStepListResult or the result of cls(response) + :rtype: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepListResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStepListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStepListResult] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_list_request( + approval_id=approval_id, + scope=scope, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStepListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStepListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages'} # type: ignore + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/__init__.py index 6bfcb58bfb9..a784ef8770f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/__init__.py @@ -6,47 +6,38 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ErrorDefinition - from ._models_py3 import ErrorDefinitionProperties - from ._models_py3 import Operation - from ._models_py3 import OperationDisplay - from ._models_py3 import OperationListResult - from ._models_py3 import RoleAssignmentApproval - from ._models_py3 import RoleAssignmentApprovalListResult - from ._models_py3 import RoleAssignmentApprovalStep - from ._models_py3 import RoleAssignmentApprovalStepListResult - from ._models_py3 import RoleAssignmentApprovalStepProperties -except (SyntaxError, ImportError): - from ._models import ErrorDefinition # type: ignore - from ._models import ErrorDefinitionProperties # type: ignore - from ._models import Operation # type: ignore - from ._models import OperationDisplay # type: ignore - from ._models import OperationListResult # type: ignore - from ._models import RoleAssignmentApproval # type: ignore - from ._models import RoleAssignmentApprovalListResult # type: ignore - from ._models import RoleAssignmentApprovalStep # type: ignore - from ._models import RoleAssignmentApprovalStepListResult # type: ignore - from ._models import RoleAssignmentApprovalStepProperties # type: ignore +from ._models_py3 import ErrorDefinition +from ._models_py3 import ErrorDefinitionProperties +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import RoleAssignmentApproval +from ._models_py3 import RoleAssignmentApprovalListResult +from ._models_py3 import RoleAssignmentApprovalStep +from ._models_py3 import RoleAssignmentApprovalStepListResult +from ._models_py3 import RoleAssignmentApprovalStepProperties -from ._authorization_management_client_enums import ( - RoleAssignmentApprovalActorIdentityType, - RoleAssignmentApprovalStepReviewResult, - RoleAssignmentApprovalStepStatus, -) +from ._authorization_management_client_enums import RoleAssignmentApprovalActorIdentityType +from ._authorization_management_client_enums import RoleAssignmentApprovalStepReviewResult +from ._authorization_management_client_enums import RoleAssignmentApprovalStepStatus +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ErrorDefinition', - 'ErrorDefinitionProperties', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'RoleAssignmentApproval', - 'RoleAssignmentApprovalListResult', - 'RoleAssignmentApprovalStep', - 'RoleAssignmentApprovalStepListResult', - 'RoleAssignmentApprovalStepProperties', - 'RoleAssignmentApprovalActorIdentityType', - 'RoleAssignmentApprovalStepReviewResult', - 'RoleAssignmentApprovalStepStatus', + "ErrorDefinition", + "ErrorDefinitionProperties", + "Operation", + "OperationDisplay", + "OperationListResult", + "RoleAssignmentApproval", + "RoleAssignmentApprovalListResult", + "RoleAssignmentApprovalStep", + "RoleAssignmentApprovalStepListResult", + "RoleAssignmentApprovalStepProperties", + "RoleAssignmentApprovalActorIdentityType", + "RoleAssignmentApprovalStepReviewResult", + "RoleAssignmentApprovalStepStatus", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_authorization_management_client_enums.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_authorization_management_client_enums.py index c02590626aa..74ba291f3bc 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_authorization_management_client_enums.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_authorization_management_client_enums.py @@ -6,45 +6,29 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass - -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class RoleAssignmentApprovalActorIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The identity type : user/servicePrincipal - """ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class RoleAssignmentApprovalActorIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type : user/servicePrincipal.""" USER = "user" SERVICE_PRINCIPAL = "servicePrincipal" -class RoleAssignmentApprovalStepReviewResult(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class RoleAssignmentApprovalStepReviewResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The decision on the approval stage. This value is initially set to NotReviewed. Approvers can - take action of Approve/Deny + take action of Approve/Deny. """ APPROVE = "Approve" DENY = "Deny" NOT_REVIEWED = "NotReviewed" -class RoleAssignmentApprovalStepStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """This read-only field specifies the status of an approval. - """ + +class RoleAssignmentApprovalStepStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This read-only field specifies the status of an approval.""" NOT_STARTED = "NotStarted" IN_PROGRESS = "InProgress" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_models.py deleted file mode 100644 index 88eb0cd0d10..00000000000 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_models.py +++ /dev/null @@ -1,416 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class ErrorDefinition(msrest.serialization.Model): - """Error description and code explaining why an operation failed. - - :param error: Error of the list gateway status. - :type error: ~azure.mgmt.authorization.v2021_01_01_preview.models.ErrorDefinitionProperties - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinitionProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDefinition, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ErrorDefinitionProperties(msrest.serialization.Model): - """Error description and code explaining why an operation failed. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar message: Description of the error. - :vartype message: str - :param code: Error code of list gateway. - :type code: str - """ - - _validation = { - 'message': {'readonly': True}, - } - - _attribute_map = { - 'message': {'key': 'message', 'type': 'str'}, - 'code': {'key': 'code', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDefinitionProperties, self).__init__(**kwargs) - self.message = None - self.code = kwargs.get('code', None) - - -class Operation(msrest.serialization.Model): - """The definition of a Microsoft.Authorization operation. - - :param name: Name of the operation. - :type name: str - :param is_data_action: Indicates whether the operation is a data action. - :type is_data_action: bool - :param display: Display of the operation. - :type display: ~azure.mgmt.authorization.v2021_01_01_preview.models.OperationDisplay - :param origin: Origin of the operation. Values include user|system|user,system. - :type origin: str - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'origin': {'key': 'origin', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Operation, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.is_data_action = kwargs.get('is_data_action', None) - self.display = kwargs.get('display', None) - self.origin = kwargs.get('origin', None) - - -class OperationDisplay(msrest.serialization.Model): - """The display information for a Microsoft.Authorization operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provider: The resource provider name: Microsoft.Authorization. - :vartype provider: str - :ivar resource: The resource on which the operation is performed. - :vartype resource: str - :ivar operation: The operation that users can perform. - :vartype operation: str - :ivar description: The description for the operation. - :vartype description: str - """ - - _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, - } - - _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None - self.description = None - - -class OperationListResult(msrest.serialization.Model): - """The result of a request to list Microsoft.Authorization operations. - - :param value: The collection value. - :type value: list[~azure.mgmt.authorization.v2021_01_01_preview.models.Operation] - :param next_link: The URI that can be used to request the next set of paged results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class RoleAssignmentApproval(msrest.serialization.Model): - """Role Assignment Approval. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role assignment approval id. - :vartype id: str - :ivar name: The role assignment approval unique id. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - :param stages: This is the collection of stages returned when one does an expand on it. - :type stages: - list[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'stages': {'key': 'properties.stages', 'type': '[RoleAssignmentApprovalStep]'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentApproval, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.stages = kwargs.get('stages', None) - - -class RoleAssignmentApprovalListResult(msrest.serialization.Model): - """List of role assignment approvals. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param value: Role Assignment Approval list. - :type value: list[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _validation = { - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignmentApproval]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentApprovalListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = None - - -class RoleAssignmentApprovalStep(msrest.serialization.Model): - """Role assignment approval stage properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The role assignment approval stage id. - :vartype id: str - :ivar name: The role assignment approval stage name. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - :param display_name: The display name for the approval stage. - :type display_name: str - :ivar status: This read-only field specifies the status of an approval. Possible values - include: "NotStarted", "InProgress", "Completed", "Expired", "Initializing", "Escalating", - "Completing", "Escalated". - :vartype status: str or - ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepStatus - :ivar assigned_to_me: Indicates whether the stage is assigned to me for review. - :vartype assigned_to_me: bool - :ivar reviewed_date_time: Date Time when a decision was taken. - :vartype reviewed_date_time: ~datetime.datetime - :param review_result: The decision on the approval stage. This value is initially set to - NotReviewed. Approvers can take action of Approve/Deny. Possible values include: "Approve", - "Deny", "NotReviewed". - :type review_result: str or - ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str - :ivar principal_id: The identity id. - :vartype principal_id: str - :ivar principal_type: The identity type : user/servicePrincipal. Possible values include: - "user", "servicePrincipal". - :vartype principal_type: str or - ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalActorIdentityType - :ivar principal_name: The identity display name. - :vartype principal_name: str - :ivar user_principal_name: The user principal name(if valid). - :vartype user_principal_name: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'status': {'readonly': True}, - 'assigned_to_me': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'assigned_to_me': {'key': 'properties.assignedToMe', 'type': 'bool'}, - 'reviewed_date_time': {'key': 'properties.reviewedDateTime', 'type': 'iso-8601'}, - 'review_result': {'key': 'properties.reviewResult', 'type': 'str'}, - 'justification': {'key': 'properties.justification', 'type': 'str'}, - 'principal_id': {'key': 'properties.reviewedBy.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.reviewedBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'properties.reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'properties.reviewedBy.userPrincipalName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentApprovalStep, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.display_name = kwargs.get('display_name', None) - self.status = None - self.assigned_to_me = None - self.reviewed_date_time = None - self.review_result = kwargs.get('review_result', None) - self.justification = kwargs.get('justification', None) - self.principal_id = None - self.principal_type = None - self.principal_name = None - self.user_principal_name = None - - -class RoleAssignmentApprovalStepListResult(msrest.serialization.Model): - """List of role assignment approval stage list. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param value: Role Assignment Approval Step list. - :type value: - list[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep] - :ivar next_link: The URL to use for getting the next set of results. - :vartype next_link: str - """ - - _validation = { - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignmentApprovalStep]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentApprovalStepListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = None - - -class RoleAssignmentApprovalStepProperties(msrest.serialization.Model): - """Approval Step. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param display_name: The display name for the approval stage. - :type display_name: str - :ivar status: This read-only field specifies the status of an approval. Possible values - include: "NotStarted", "InProgress", "Completed", "Expired", "Initializing", "Escalating", - "Completing", "Escalated". - :vartype status: str or - ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepStatus - :ivar assigned_to_me: Indicates whether the stage is assigned to me for review. - :vartype assigned_to_me: bool - :ivar reviewed_date_time: Date Time when a decision was taken. - :vartype reviewed_date_time: ~datetime.datetime - :param review_result: The decision on the approval stage. This value is initially set to - NotReviewed. Approvers can take action of Approve/Deny. Possible values include: "Approve", - "Deny", "NotReviewed". - :type review_result: str or - ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str - :ivar principal_id: The identity id. - :vartype principal_id: str - :ivar principal_type: The identity type : user/servicePrincipal. Possible values include: - "user", "servicePrincipal". - :vartype principal_type: str or - ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalActorIdentityType - :ivar principal_name: The identity display name. - :vartype principal_name: str - :ivar user_principal_name: The user principal name(if valid). - :vartype user_principal_name: str - """ - - _validation = { - 'status': {'readonly': True}, - 'assigned_to_me': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, - } - - _attribute_map = { - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'assigned_to_me': {'key': 'assignedToMe', 'type': 'bool'}, - 'reviewed_date_time': {'key': 'reviewedDateTime', 'type': 'iso-8601'}, - 'review_result': {'key': 'reviewResult', 'type': 'str'}, - 'justification': {'key': 'justification', 'type': 'str'}, - 'principal_id': {'key': 'reviewedBy.principalId', 'type': 'str'}, - 'principal_type': {'key': 'reviewedBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'reviewedBy.userPrincipalName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RoleAssignmentApprovalStepProperties, self).__init__(**kwargs) - self.display_name = kwargs.get('display_name', None) - self.status = None - self.assigned_to_me = None - self.reviewed_date_time = None - self.review_result = kwargs.get('review_result', None) - self.justification = kwargs.get('justification', None) - self.principal_id = None - self.principal_type = None - self.principal_name = None - self.user_principal_name = None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_models_py3.py index f33ff8c7edc..163516e08ef 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_models_py3.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -6,84 +7,84 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import List, Optional, Union +from typing import List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization -from ._authorization_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class ErrorDefinition(msrest.serialization.Model): +class ErrorDefinition(_serialization.Model): """Error description and code explaining why an operation failed. - :param error: Error of the list gateway status. - :type error: ~azure.mgmt.authorization.v2021_01_01_preview.models.ErrorDefinitionProperties + :ivar error: Error of the list gateway status. + :vartype error: ~azure.mgmt.authorization.v2021_01_01_preview.models.ErrorDefinitionProperties """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinitionProperties'}, + "error": {"key": "error", "type": "ErrorDefinitionProperties"}, } - def __init__( - self, - *, - error: Optional["ErrorDefinitionProperties"] = None, - **kwargs - ): - super(ErrorDefinition, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDefinitionProperties"] = None, **kwargs): + """ + :keyword error: Error of the list gateway status. + :paramtype error: + ~azure.mgmt.authorization.v2021_01_01_preview.models.ErrorDefinitionProperties + """ + super().__init__(**kwargs) self.error = error -class ErrorDefinitionProperties(msrest.serialization.Model): +class ErrorDefinitionProperties(_serialization.Model): """Error description and code explaining why an operation failed. Variables are only populated by the server, and will be ignored when sending a request. :ivar message: Description of the error. :vartype message: str - :param code: Error code of list gateway. - :type code: str + :ivar code: Error code of list gateway. + :vartype code: str """ _validation = { - 'message': {'readonly': True}, + "message": {"readonly": True}, } _attribute_map = { - 'message': {'key': 'message', 'type': 'str'}, - 'code': {'key': 'code', 'type': 'str'}, + "message": {"key": "message", "type": "str"}, + "code": {"key": "code", "type": "str"}, } - def __init__( - self, - *, - code: Optional[str] = None, - **kwargs - ): - super(ErrorDefinitionProperties, self).__init__(**kwargs) + def __init__(self, *, code: Optional[str] = None, **kwargs): + """ + :keyword code: Error code of list gateway. + :paramtype code: str + """ + super().__init__(**kwargs) self.message = None self.code = code -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """The definition of a Microsoft.Authorization operation. - :param name: Name of the operation. - :type name: str - :param is_data_action: Indicates whether the operation is a data action. - :type is_data_action: bool - :param display: Display of the operation. - :type display: ~azure.mgmt.authorization.v2021_01_01_preview.models.OperationDisplay - :param origin: Origin of the operation. Values include user|system|user,system. - :type origin: str + :ivar name: Name of the operation. + :vartype name: str + :ivar is_data_action: Indicates whether the operation is a data action. + :vartype is_data_action: bool + :ivar display: Display of the operation. + :vartype display: ~azure.mgmt.authorization.v2021_01_01_preview.models.OperationDisplay + :ivar origin: Origin of the operation. Values include user|system|user,system. + :vartype origin: str """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'origin': {'key': 'origin', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, } def __init__( @@ -91,18 +92,28 @@ def __init__( *, name: Optional[str] = None, is_data_action: Optional[bool] = None, - display: Optional["OperationDisplay"] = None, + display: Optional["_models.OperationDisplay"] = None, origin: Optional[str] = None, **kwargs ): - super(Operation, self).__init__(**kwargs) + """ + :keyword name: Name of the operation. + :paramtype name: str + :keyword is_data_action: Indicates whether the operation is a data action. + :paramtype is_data_action: bool + :keyword display: Display of the operation. + :paramtype display: ~azure.mgmt.authorization.v2021_01_01_preview.models.OperationDisplay + :keyword origin: Origin of the operation. Values include user|system|user,system. + :paramtype origin: str + """ + super().__init__(**kwargs) self.name = name self.is_data_action = is_data_action self.display = display self.origin = origin -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """The display information for a Microsoft.Authorization operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -118,57 +129,55 @@ class OperationDisplay(msrest.serialization.Model): """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """The result of a request to list Microsoft.Authorization operations. - :param value: The collection value. - :type value: list[~azure.mgmt.authorization.v2021_01_01_preview.models.Operation] - :param next_link: The URI that can be used to request the next set of paged results. - :type next_link: str + :ivar value: The collection value. + :vartype value: list[~azure.mgmt.authorization.v2021_01_01_preview.models.Operation] + :ivar next_link: The URI that can be used to request the next set of paged results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["Operation"]] = None, - next_link: Optional[str] = None, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs): + """ + :keyword value: The collection value. + :paramtype value: list[~azure.mgmt.authorization.v2021_01_01_preview.models.Operation] + :keyword next_link: The URI that can be used to request the next set of paged results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class RoleAssignmentApproval(msrest.serialization.Model): +class RoleAssignmentApproval(_serialization.Model): """Role Assignment Approval. Variables are only populated by the server, and will be ignored when sending a request. @@ -179,69 +188,70 @@ class RoleAssignmentApproval(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :param stages: This is the collection of stages returned when one does an expand on it. - :type stages: + :ivar stages: This is the collection of stages returned when one does an expand on it. + :vartype stages: list[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'stages': {'key': 'properties.stages', 'type': '[RoleAssignmentApprovalStep]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "stages": {"key": "properties.stages", "type": "[RoleAssignmentApprovalStep]"}, } - def __init__( - self, - *, - stages: Optional[List["RoleAssignmentApprovalStep"]] = None, - **kwargs - ): - super(RoleAssignmentApproval, self).__init__(**kwargs) + def __init__(self, *, stages: Optional[List["_models.RoleAssignmentApprovalStep"]] = None, **kwargs): + """ + :keyword stages: This is the collection of stages returned when one does an expand on it. + :paramtype stages: + list[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep] + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None self.stages = stages -class RoleAssignmentApprovalListResult(msrest.serialization.Model): +class RoleAssignmentApprovalListResult(_serialization.Model): """List of role assignment approvals. Variables are only populated by the server, and will be ignored when sending a request. - :param value: Role Assignment Approval list. - :type value: list[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval] + :ivar value: Role Assignment Approval list. + :vartype value: + list[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval] :ivar next_link: The URL to use for getting the next set of results. :vartype next_link: str """ _validation = { - 'next_link': {'readonly': True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignmentApproval]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleAssignmentApproval]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["RoleAssignmentApproval"]] = None, - **kwargs - ): - super(RoleAssignmentApprovalListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.RoleAssignmentApproval"]] = None, **kwargs): + """ + :keyword value: Role Assignment Approval list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval] + """ + super().__init__(**kwargs) self.value = value self.next_link = None -class RoleAssignmentApprovalStep(msrest.serialization.Model): +class RoleAssignmentApprovalStep(_serialization.Model): # pylint: disable=too-many-instance-attributes """Role assignment approval stage properties. Variables are only populated by the server, and will be ignored when sending a request. @@ -252,28 +262,28 @@ class RoleAssignmentApprovalStep(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :param display_name: The display name for the approval stage. - :type display_name: str - :ivar status: This read-only field specifies the status of an approval. Possible values - include: "NotStarted", "InProgress", "Completed", "Expired", "Initializing", "Escalating", - "Completing", "Escalated". + :ivar display_name: The display name for the approval stage. + :vartype display_name: str + :ivar status: This read-only field specifies the status of an approval. Known values are: + "NotStarted", "InProgress", "Completed", "Expired", "Initializing", "Escalating", "Completing", + and "Escalated". :vartype status: str or ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepStatus :ivar assigned_to_me: Indicates whether the stage is assigned to me for review. :vartype assigned_to_me: bool :ivar reviewed_date_time: Date Time when a decision was taken. :vartype reviewed_date_time: ~datetime.datetime - :param review_result: The decision on the approval stage. This value is initially set to - NotReviewed. Approvers can take action of Approve/Deny. Possible values include: "Approve", - "Deny", "NotReviewed". - :type review_result: str or + :ivar review_result: The decision on the approval stage. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + and "NotReviewed". + :vartype review_result: str or ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str + :ivar justification: Justification provided by approvers for their action. + :vartype justification: str :ivar principal_id: The identity id. :vartype principal_id: str - :ivar principal_type: The identity type : user/servicePrincipal. Possible values include: - "user", "servicePrincipal". + :ivar principal_type: The identity type : user/servicePrincipal. Known values are: "user" and + "servicePrincipal". :vartype principal_type: str or ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalActorIdentityType :ivar principal_name: The identity display name. @@ -283,43 +293,54 @@ class RoleAssignmentApprovalStep(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'status': {'readonly': True}, - 'assigned_to_me': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "status": {"readonly": True}, + "assigned_to_me": {"readonly": True}, + "reviewed_date_time": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'assigned_to_me': {'key': 'properties.assignedToMe', 'type': 'bool'}, - 'reviewed_date_time': {'key': 'properties.reviewedDateTime', 'type': 'iso-8601'}, - 'review_result': {'key': 'properties.reviewResult', 'type': 'str'}, - 'justification': {'key': 'properties.justification', 'type': 'str'}, - 'principal_id': {'key': 'properties.reviewedBy.principalId', 'type': 'str'}, - 'principal_type': {'key': 'properties.reviewedBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'properties.reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'properties.reviewedBy.userPrincipalName', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "assigned_to_me": {"key": "properties.assignedToMe", "type": "bool"}, + "reviewed_date_time": {"key": "properties.reviewedDateTime", "type": "iso-8601"}, + "review_result": {"key": "properties.reviewResult", "type": "str"}, + "justification": {"key": "properties.justification", "type": "str"}, + "principal_id": {"key": "properties.reviewedBy.principalId", "type": "str"}, + "principal_type": {"key": "properties.reviewedBy.principalType", "type": "str"}, + "principal_name": {"key": "properties.reviewedBy.principalName", "type": "str"}, + "user_principal_name": {"key": "properties.reviewedBy.userPrincipalName", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, - review_result: Optional[Union[str, "RoleAssignmentApprovalStepReviewResult"]] = None, + review_result: Optional[Union[str, "_models.RoleAssignmentApprovalStepReviewResult"]] = None, justification: Optional[str] = None, **kwargs ): - super(RoleAssignmentApprovalStep, self).__init__(**kwargs) + """ + :keyword display_name: The display name for the approval stage. + :paramtype display_name: str + :keyword review_result: The decision on the approval stage. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + and "NotReviewed". + :paramtype review_result: str or + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepReviewResult + :keyword justification: Justification provided by approvers for their action. + :paramtype justification: str + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -335,65 +356,65 @@ def __init__( self.user_principal_name = None -class RoleAssignmentApprovalStepListResult(msrest.serialization.Model): +class RoleAssignmentApprovalStepListResult(_serialization.Model): """List of role assignment approval stage list. Variables are only populated by the server, and will be ignored when sending a request. - :param value: Role Assignment Approval Step list. - :type value: + :ivar value: Role Assignment Approval Step list. + :vartype value: list[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep] :ivar next_link: The URL to use for getting the next set of results. :vartype next_link: str """ _validation = { - 'next_link': {'readonly': True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[RoleAssignmentApprovalStep]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RoleAssignmentApprovalStep]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["RoleAssignmentApprovalStep"]] = None, - **kwargs - ): - super(RoleAssignmentApprovalStepListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.RoleAssignmentApprovalStep"]] = None, **kwargs): + """ + :keyword value: Role Assignment Approval Step list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep] + """ + super().__init__(**kwargs) self.value = value self.next_link = None -class RoleAssignmentApprovalStepProperties(msrest.serialization.Model): +class RoleAssignmentApprovalStepProperties(_serialization.Model): """Approval Step. Variables are only populated by the server, and will be ignored when sending a request. - :param display_name: The display name for the approval stage. - :type display_name: str - :ivar status: This read-only field specifies the status of an approval. Possible values - include: "NotStarted", "InProgress", "Completed", "Expired", "Initializing", "Escalating", - "Completing", "Escalated". + :ivar display_name: The display name for the approval stage. + :vartype display_name: str + :ivar status: This read-only field specifies the status of an approval. Known values are: + "NotStarted", "InProgress", "Completed", "Expired", "Initializing", "Escalating", "Completing", + and "Escalated". :vartype status: str or ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepStatus :ivar assigned_to_me: Indicates whether the stage is assigned to me for review. :vartype assigned_to_me: bool :ivar reviewed_date_time: Date Time when a decision was taken. :vartype reviewed_date_time: ~datetime.datetime - :param review_result: The decision on the approval stage. This value is initially set to - NotReviewed. Approvers can take action of Approve/Deny. Possible values include: "Approve", - "Deny", "NotReviewed". - :type review_result: str or + :ivar review_result: The decision on the approval stage. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + and "NotReviewed". + :vartype review_result: str or ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str + :ivar justification: Justification provided by approvers for their action. + :vartype justification: str :ivar principal_id: The identity id. :vartype principal_id: str - :ivar principal_type: The identity type : user/servicePrincipal. Possible values include: - "user", "servicePrincipal". + :ivar principal_type: The identity type : user/servicePrincipal. Known values are: "user" and + "servicePrincipal". :vartype principal_type: str or ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalActorIdentityType :ivar principal_name: The identity display name. @@ -403,37 +424,48 @@ class RoleAssignmentApprovalStepProperties(msrest.serialization.Model): """ _validation = { - 'status': {'readonly': True}, - 'assigned_to_me': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, + "status": {"readonly": True}, + "assigned_to_me": {"readonly": True}, + "reviewed_date_time": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, } _attribute_map = { - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'assigned_to_me': {'key': 'assignedToMe', 'type': 'bool'}, - 'reviewed_date_time': {'key': 'reviewedDateTime', 'type': 'iso-8601'}, - 'review_result': {'key': 'reviewResult', 'type': 'str'}, - 'justification': {'key': 'justification', 'type': 'str'}, - 'principal_id': {'key': 'reviewedBy.principalId', 'type': 'str'}, - 'principal_type': {'key': 'reviewedBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'reviewedBy.userPrincipalName', 'type': 'str'}, + "display_name": {"key": "displayName", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "assigned_to_me": {"key": "assignedToMe", "type": "bool"}, + "reviewed_date_time": {"key": "reviewedDateTime", "type": "iso-8601"}, + "review_result": {"key": "reviewResult", "type": "str"}, + "justification": {"key": "justification", "type": "str"}, + "principal_id": {"key": "reviewedBy.principalId", "type": "str"}, + "principal_type": {"key": "reviewedBy.principalType", "type": "str"}, + "principal_name": {"key": "reviewedBy.principalName", "type": "str"}, + "user_principal_name": {"key": "reviewedBy.userPrincipalName", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, - review_result: Optional[Union[str, "RoleAssignmentApprovalStepReviewResult"]] = None, + review_result: Optional[Union[str, "_models.RoleAssignmentApprovalStepReviewResult"]] = None, justification: Optional[str] = None, **kwargs ): - super(RoleAssignmentApprovalStepProperties, self).__init__(**kwargs) + """ + :keyword display_name: The display name for the approval stage. + :paramtype display_name: str + :keyword review_result: The decision on the approval stage. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + and "NotReviewed". + :paramtype review_result: str or + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepReviewResult + :keyword justification: Justification provided by approvers for their action. + :paramtype justification: str + """ + super().__init__(**kwargs) self.display_name = display_name self.status = None self.assigned_to_me = None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/__init__.py index c5030cb2549..c9d41189173 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/__init__.py @@ -14,12 +14,18 @@ from ._scope_role_assignment_approval_steps_operations import ScopeRoleAssignmentApprovalStepsOperations from ._scope_role_assignment_approval_step_operations import ScopeRoleAssignmentApprovalStepOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'Operations', - 'RoleAssignmentApprovalOperations', - 'RoleAssignmentApprovalStepsOperations', - 'RoleAssignmentApprovalStepOperations', - 'ScopeRoleAssignmentApprovalOperations', - 'ScopeRoleAssignmentApprovalStepsOperations', - 'ScopeRoleAssignmentApprovalStepOperations', + "Operations", + "RoleAssignmentApprovalOperations", + "RoleAssignmentApprovalStepsOperations", + "RoleAssignmentApprovalStepOperations", + "ScopeRoleAssignmentApprovalOperations", + "ScopeRoleAssignmentApprovalStepsOperations", + "ScopeRoleAssignmentApprovalStepOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_operations.py index 7e220da70af..67d44cf0189 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,123 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") -class Operations(object): - """Operations operations. + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/operations") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.AuthorizationManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.OperationListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists the operations available from this provider. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,17 +131,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/operations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_operations.py index 3aba6671037..e7a63ecf9e8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,52 +6,102 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(*, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/roleAssignmentApprovals") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(approval_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}") + path_format_arguments = { + "approvalId": _SERIALIZER.url("approval_id", approval_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class RoleAssignmentApprovalOperations(object): - """RoleAssignmentApprovalOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RoleAssignmentApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.AuthorizationManagementClient`'s + :attr:`role_assignment_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentApprovalListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.RoleAssignmentApproval"]: """Get role assignment approvals. :param filter: The filter to apply on the operation. Valid values for $filter are: @@ -60,44 +111,55 @@ def list( $filter=asCreatedBy() is provided, the returned list only includes all role assignment approvals that the calling user created requests for. If $filter=asTarget() is provided, the returned list only includes all role assignment approvals that the calling user has requests - targeted for. + targeted for. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentApprovalListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignmentApproval or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentApprovalListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -106,72 +168,73 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals'} # type: ignore - - def get_by_id( - self, - approval_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentApproval" + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals"} # type: ignore + + @distributed_trace + def get_by_id(self, approval_id: str, **kwargs: Any) -> _models.RoleAssignmentApproval: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApproval, or the result of cls(response) + :return: RoleAssignmentApproval or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApproval"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApproval] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + approval_id=approval_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApproval', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApproval", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}'} # type: ignore + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_step_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_step_operations.py index f7b151bea74..5ef56529388 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_step_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_step_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,234 +6,458 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_by_id_request(approval_id: str, stage_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "approvalId": _SERIALIZER.url("approval_id", approval_id, "str"), + "stageId": _SERIALIZER.url("stage_id", stage_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_patch_request(approval_id: str, stage_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "approvalId": _SERIALIZER.url("approval_id", approval_id, "str"), + "stageId": _SERIALIZER.url("stage_id", stage_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +def build_put_request(approval_id: str, stage_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -class RoleAssignmentApprovalStepOperations(object): - """RoleAssignmentApprovalStepOperations operations. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "approvalId": _SERIALIZER.url("approval_id", approval_id, "str"), + "stageId": _SERIALIZER.url("stage_id", stage_id, "str"), + } - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentApprovalStepOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.AuthorizationManagementClient`'s + :attr:`role_assignment_approval_step` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def get_by_id( - self, - approval_id, # type: str - stage_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentApprovalStep" + @distributed_trace + def get_by_id(self, approval_id: str, stage_id: str, **kwargs: Any) -> _models.RoleAssignmentApprovalStep: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + approval_id=approval_id, + stage_id=stage_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore + + @overload def patch( self, - approval_id, # type: str - stage_id, # type: str - properties, # type: "_models.RoleAssignmentApprovalStepProperties" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentApprovalStep" + approval_id: str, + stage_id: str, + properties: _models.RoleAssignmentApprovalStepProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: """Record a decision. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str - :param properties: Role Assignment Approval stage properties to patch. - :type properties: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :param properties: Role Assignment Approval stage properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def patch( + self, approval_id: str, stage_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param properties: Role Assignment Approval stage properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def patch( + self, + approval_id: str, + stage_id: str, + properties: Union[_models.RoleAssignmentApprovalStepProperties, IO], + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param properties: Role Assignment Approval stage properties to patch. Is either a model type + or a IO type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.patch.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'RoleAssignmentApprovalStepProperties') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "RoleAssignmentApprovalStepProperties") + + request = build_patch_request( + approval_id=approval_id, + stage_id=stage_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - patch.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + patch.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore + + @overload def put( self, - approval_id, # type: str - stage_id, # type: str - properties, # type: "_models.RoleAssignmentApprovalStepProperties" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentApprovalStep" + approval_id: str, + stage_id: str, + properties: _models.RoleAssignmentApprovalStepProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: """Record a decision. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str - :param properties: Role Assignment Approval stage properties to put. - :type properties: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :param properties: Role Assignment Approval stage properties to put. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put( + self, approval_id: str, stage_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param properties: Role Assignment Approval stage properties to put. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put( + self, + approval_id: str, + stage_id: str, + properties: Union[_models.RoleAssignmentApprovalStepProperties, IO], + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param properties: Role Assignment Approval stage properties to put. Is either a model type or + a IO type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.put.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'RoleAssignmentApprovalStepProperties') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "RoleAssignmentApprovalStepProperties") + + request = build_put_request( + approval_id=approval_id, + stage_id=stage_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + + put.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_steps_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_steps_operations.py index 9f1af04b4e0..acb2b466023 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_steps_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_role_assignment_approval_steps_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,96 +6,129 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(approval_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages") + path_format_arguments = { + "approvalId": _SERIALIZER.url("approval_id", approval_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class RoleAssignmentApprovalStepsOperations(object): - """RoleAssignmentApprovalStepsOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class RoleAssignmentApprovalStepsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.AuthorizationManagementClient`'s + :attr:`role_assignment_approval_steps` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - approval_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentApprovalStepListResult" + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, approval_id: str, **kwargs: Any) -> _models.RoleAssignmentApprovalStepListResult: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStepListResult, or the result of cls(response) - :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepListResult - :raises: ~azure.core.exceptions.HttpResponseError + :return: RoleAssignmentApprovalStepListResult or the result of cls(response) + :rtype: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepListResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStepListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStepListResult] + + request = build_list_request( + approval_id=approval_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStepListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStepListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages'} # type: ignore + + list.metadata = {"url": "/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_operations.py index 9a21685006f..b4cf7ac2ecb 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,56 +6,113 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(approval_id: str, scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}") + path_format_arguments = { + "approvalId": _SERIALIZER.url("approval_id", approval_id, "str"), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class ScopeRoleAssignmentApprovalOperations(object): - """ScopeRoleAssignmentApprovalOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class ScopeRoleAssignmentApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.AuthorizationManagementClient`'s + :attr:`scope_role_assignment_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - scope, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RoleAssignmentApprovalListResult"] + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignmentApproval"]: """Get role assignment approvals. - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str :param filter: The filter to apply on the operation. Valid values for $filter are: 'asApprover()', 'asCreatedBy()' and 'asTarget()'. If $filter is not provided, no filtering is @@ -63,48 +121,56 @@ def list( $filter=asCreatedBy() is provided, the returned list only includes all role assignment approvals that the calling user created requests for. If $filter=asTarget() is provided, the returned list only includes all role assignment approvals that the calling user has requests - targeted for. + targeted for. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RoleAssignmentApprovalListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RoleAssignmentApproval or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RoleAssignmentApprovalListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -113,76 +179,76 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals'} # type: ignore - - def get_by_id( - self, - approval_id, # type: str - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentApproval" + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals"} # type: ignore + + @distributed_trace + def get_by_id(self, approval_id: str, scope: str, **kwargs: Any) -> _models.RoleAssignmentApproval: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApproval, or the result of cls(response) + :return: RoleAssignmentApproval or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApproval - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApproval"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApproval] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + approval_id=approval_id, + scope=scope, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApproval', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApproval", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}'} # type: ignore + + get_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_step_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_step_operations.py index e883fa43961..71067dc9453 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_step_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_step_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,246 +6,501 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_by_id_request(approval_id: str, stage_id: str, scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "approvalId": _SERIALIZER.url("approval_id", approval_id, "str"), + "stageId": _SERIALIZER.url("stage_id", stage_id, "str"), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_patch_request(approval_id: str, stage_id: str, scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "approvalId": _SERIALIZER.url("approval_id", approval_id, "str"), + "stageId": _SERIALIZER.url("stage_id", stage_id, "str"), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_put_request(approval_id: str, stage_id: str, scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "approvalId": _SERIALIZER.url("approval_id", approval_id, "str"), + "stageId": _SERIALIZER.url("stage_id", stage_id, "str"), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } -class ScopeRoleAssignmentApprovalStepOperations(object): - """ScopeRoleAssignmentApprovalStepOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScopeRoleAssignmentApprovalStepOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.AuthorizationManagementClient`'s + :attr:`scope_role_assignment_approval_step` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def get_by_id( - self, - approval_id, # type: str - stage_id, # type: str - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentApprovalStep" + self, approval_id: str, stage_id: str, scope: str, **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] + + request = build_get_by_id_request( + approval_id=approval_id, + stage_id=stage_id, + scope=scope, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + get_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore + + @overload def patch( self, - approval_id, # type: str - stage_id, # type: str - scope, # type: str - properties, # type: "_models.RoleAssignmentApprovalStepProperties" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentApprovalStep" + approval_id: str, + stage_id: str, + scope: str, + properties: _models.RoleAssignmentApprovalStepProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: """Record a decision. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str - :param properties: Role Assignment Approval stage properties to patch. - :type properties: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :param properties: Role Assignment Approval stage properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def patch( + self, + approval_id: str, + stage_id: str, + scope: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Role Assignment Approval stage properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def patch( + self, + approval_id: str, + stage_id: str, + scope: str, + properties: Union[_models.RoleAssignmentApprovalStepProperties, IO], + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Role Assignment Approval stage properties to patch. Is either a model type + or a IO type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.patch.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'RoleAssignmentApprovalStepProperties') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "RoleAssignmentApprovalStepProperties") + + request = build_patch_request( + approval_id=approval_id, + stage_id=stage_id, + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - patch.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + patch.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore + + @overload + def put( + self, + approval_id: str, + stage_id: str, + scope: str, + properties: _models.RoleAssignmentApprovalStepProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Role Assignment Approval stage properties to put. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put( + self, + approval_id: str, + stage_id: str, + scope: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: + """Record a decision. + + :param approval_id: The id of the role assignment approval. Required. + :type approval_id: str + :param stage_id: The id of the role assignment approval stage. Required. + :type stage_id: str + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Role Assignment Approval stage properties to put. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignmentApprovalStep or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace def put( self, - approval_id, # type: str - stage_id, # type: str - scope, # type: str - properties, # type: "_models.RoleAssignmentApprovalStepProperties" - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentApprovalStep" + approval_id: str, + stage_id: str, + scope: str, + properties: Union[_models.RoleAssignmentApprovalStepProperties, IO], + **kwargs: Any + ) -> _models.RoleAssignmentApprovalStep: """Record a decision. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param stage_id: The id of the role assignment approval stage. + :param stage_id: The id of the role assignment approval stage. Required. :type stage_id: str - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str - :param properties: Role Assignment Approval stage properties to put. - :type properties: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties + :param properties: Role Assignment Approval stage properties to put. Is either a model type or + a IO type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStep, or the result of cls(response) + :return: RoleAssignmentApprovalStep or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStep - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStep"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.put.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'stageId': self._serialize.url("stage_id", stage_id, 'str'), - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'RoleAssignmentApprovalStepProperties') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStep] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "RoleAssignmentApprovalStepProperties") + + request = build_put_request( + approval_id=approval_id, + stage_id=stage_id, + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStep', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStep", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}'} # type: ignore + + put.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages/{stageId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_steps_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_steps_operations.py index 5a02802fe66..3dfaf538172 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_steps_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_01_01_preview/operations/_scope_role_assignment_approval_steps_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,100 +6,135 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(approval_id: str, scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages" + ) # pylint: disable=line-too-long + path_format_arguments = { + "approvalId": _SERIALIZER.url("approval_id", approval_id, "str"), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class ScopeRoleAssignmentApprovalStepsOperations(object): - """ScopeRoleAssignmentApprovalStepsOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_01_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class ScopeRoleAssignmentApprovalStepsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_01_01_preview.AuthorizationManagementClient`'s + :attr:`scope_role_assignment_approval_steps` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - approval_id, # type: str - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.RoleAssignmentApprovalStepListResult" + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, approval_id: str, scope: str, **kwargs: Any) -> _models.RoleAssignmentApprovalStepListResult: """Get role assignment approval. - :param approval_id: The id of the role assignment approval. + :param approval_id: The id of the role assignment approval. Required. :type approval_id: str - :param scope: The scope of the resource. + :param scope: The scope of the resource. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RoleAssignmentApprovalStepListResult, or the result of cls(response) - :rtype: ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepListResult - :raises: ~azure.core.exceptions.HttpResponseError + :return: RoleAssignmentApprovalStepListResult or the result of cls(response) + :rtype: + ~azure.mgmt.authorization.v2021_01_01_preview.models.RoleAssignmentApprovalStepListResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RoleAssignmentApprovalStepListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01-preview" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'approvalId': self._serialize.url("approval_id", approval_id, 'str'), - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-01-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentApprovalStepListResult] + + request = build_list_request( + approval_id=approval_id, + scope=scope, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('RoleAssignmentApprovalStepListResult', pipeline_response) + deserialized = self._deserialize("RoleAssignmentApprovalStepListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages'} # type: ignore + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignmentApprovals/{approvalId}/stages"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/__init__.py index ae11ad3e4d9..9eb8d3ec28c 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AuthorizationManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_authorization_management_client.py index 024c0891cf6..995dd456598 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_authorization_management_client.py @@ -6,113 +6,140 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + AccessReviewDefaultSettingsOperations, + AccessReviewInstanceDecisionsOperations, + AccessReviewInstanceMyDecisionsOperations, + AccessReviewInstanceOperations, + AccessReviewInstancesAssignedForMyApprovalOperations, + AccessReviewInstancesOperations, + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, + AccessReviewScheduleDefinitionsOperations, + Operations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import Operations -from .operations import AccessReviewScheduleDefinitionsOperations -from .operations import AccessReviewInstancesOperations -from .operations import AccessReviewInstanceOperations -from .operations import AccessReviewInstanceDecisionsOperations -from .operations import AccessReviewDefaultSettingsOperations -from .operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations -from .operations import AccessReviewInstancesAssignedForMyApprovalOperations -from .operations import AccessReviewInstanceMyDecisionsOperations -from . import models -class AuthorizationManagementClient(object): - """Access reviews service provides the workflow for running access reviews on different kind of resources. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Access reviews service provides the workflow for running access reviews on different kind of + resources. :ivar operations: Operations operations :vartype operations: azure.mgmt.authorization.v2021_03_01_preview.operations.Operations :ivar access_review_schedule_definitions: AccessReviewScheduleDefinitionsOperations operations - :vartype access_review_schedule_definitions: azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewScheduleDefinitionsOperations + :vartype access_review_schedule_definitions: + azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewScheduleDefinitionsOperations :ivar access_review_instances: AccessReviewInstancesOperations operations - :vartype access_review_instances: azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewInstancesOperations + :vartype access_review_instances: + azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewInstancesOperations :ivar access_review_instance: AccessReviewInstanceOperations operations - :vartype access_review_instance: azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewInstanceOperations + :vartype access_review_instance: + azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewInstanceOperations :ivar access_review_instance_decisions: AccessReviewInstanceDecisionsOperations operations - :vartype access_review_instance_decisions: azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewInstanceDecisionsOperations + :vartype access_review_instance_decisions: + azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewInstanceDecisionsOperations :ivar access_review_default_settings: AccessReviewDefaultSettingsOperations operations - :vartype access_review_default_settings: azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewDefaultSettingsOperations - :ivar access_review_schedule_definitions_assigned_for_my_approval: AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations - :vartype access_review_schedule_definitions_assigned_for_my_approval: azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations - :ivar access_review_instances_assigned_for_my_approval: AccessReviewInstancesAssignedForMyApprovalOperations operations - :vartype access_review_instances_assigned_for_my_approval: azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewInstancesAssignedForMyApprovalOperations + :vartype access_review_default_settings: + azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewDefaultSettingsOperations + :ivar access_review_schedule_definitions_assigned_for_my_approval: + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations + :vartype access_review_schedule_definitions_assigned_for_my_approval: + azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations + :ivar access_review_instances_assigned_for_my_approval: + AccessReviewInstancesAssignedForMyApprovalOperations operations + :vartype access_review_instances_assigned_for_my_approval: + azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewInstancesAssignedForMyApprovalOperations :ivar access_review_instance_my_decisions: AccessReviewInstanceMyDecisionsOperations operations - :vartype access_review_instance_my_decisions: azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewInstanceMyDecisionsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype access_review_instance_my_decisions: + azure.mgmt.authorization.v2021_03_01_preview.operations.AccessReviewInstanceMyDecisionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2021-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.access_review_schedule_definitions = AccessReviewScheduleDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instances = AccessReviewInstancesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance = AccessReviewInstanceOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance_decisions = AccessReviewInstanceDecisionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_default_settings = AccessReviewDefaultSettingsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.access_review_schedule_definitions_assigned_for_my_approval = AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_schedule_definitions_assigned_for_my_approval = ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) self.access_review_instances_assigned_for_my_approval = AccessReviewInstancesAssignedForMyApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance_my_decisions = AccessReviewInstanceMyDecisionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_configuration.py index 06e446c9564..189ab49d501 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_configuration.py @@ -6,66 +6,64 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2021-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2021-03-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2021-03-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_metadata.json index b908ed305c6..1fad7f18822 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_metadata.json +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_metadata.json @@ -5,25 +5,25 @@ "name": "AuthorizationManagementClient", "filename": "_authorization_management_client", "description": "Access reviews service provides the workflow for running access reviews on different kind of resources.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, "azure_arm": true, "has_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID of the target subscription.", + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The ID of the target subscription.", + "description": "The ID of the target subscription. Required.", "docstring_type": "str", "required": true } @@ -54,7 +54,7 @@ "required": false }, "base_url": { - "signature": "base_url=None, # type: Optional[str]", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -74,7 +74,7 @@ "required": false }, "base_url": { - "signature": "base_url: Optional[str] = None,", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false @@ -91,11 +91,10 @@ "config": { "credential": true, "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "operations": "Operations", diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_version.py index 48944bf3938..cac9f5d10f8 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_version.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/__init__.py index ffc49d028e4..dd28625b36f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._authorization_management_client import AuthorizationManagementClient -__all__ = ['AuthorizationManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_authorization_management_client.py index 3d185b7b855..2ca77d4e206 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_authorization_management_client.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_authorization_management_client.py @@ -6,109 +6,140 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + AccessReviewDefaultSettingsOperations, + AccessReviewInstanceDecisionsOperations, + AccessReviewInstanceMyDecisionsOperations, + AccessReviewInstanceOperations, + AccessReviewInstancesAssignedForMyApprovalOperations, + AccessReviewInstancesOperations, + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, + AccessReviewScheduleDefinitionsOperations, + Operations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AuthorizationManagementClientConfiguration -from .operations import Operations -from .operations import AccessReviewScheduleDefinitionsOperations -from .operations import AccessReviewInstancesOperations -from .operations import AccessReviewInstanceOperations -from .operations import AccessReviewInstanceDecisionsOperations -from .operations import AccessReviewDefaultSettingsOperations -from .operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations -from .operations import AccessReviewInstancesAssignedForMyApprovalOperations -from .operations import AccessReviewInstanceMyDecisionsOperations -from .. import models - -class AuthorizationManagementClient(object): - """Access reviews service provides the workflow for running access reviews on different kind of resources. +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Access reviews service provides the workflow for running access reviews on different kind of + resources. :ivar operations: Operations operations :vartype operations: azure.mgmt.authorization.v2021_03_01_preview.aio.operations.Operations :ivar access_review_schedule_definitions: AccessReviewScheduleDefinitionsOperations operations - :vartype access_review_schedule_definitions: azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewScheduleDefinitionsOperations + :vartype access_review_schedule_definitions: + azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewScheduleDefinitionsOperations :ivar access_review_instances: AccessReviewInstancesOperations operations - :vartype access_review_instances: azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewInstancesOperations + :vartype access_review_instances: + azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewInstancesOperations :ivar access_review_instance: AccessReviewInstanceOperations operations - :vartype access_review_instance: azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewInstanceOperations + :vartype access_review_instance: + azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewInstanceOperations :ivar access_review_instance_decisions: AccessReviewInstanceDecisionsOperations operations - :vartype access_review_instance_decisions: azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewInstanceDecisionsOperations + :vartype access_review_instance_decisions: + azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewInstanceDecisionsOperations :ivar access_review_default_settings: AccessReviewDefaultSettingsOperations operations - :vartype access_review_default_settings: azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewDefaultSettingsOperations - :ivar access_review_schedule_definitions_assigned_for_my_approval: AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations - :vartype access_review_schedule_definitions_assigned_for_my_approval: azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations - :ivar access_review_instances_assigned_for_my_approval: AccessReviewInstancesAssignedForMyApprovalOperations operations - :vartype access_review_instances_assigned_for_my_approval: azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewInstancesAssignedForMyApprovalOperations + :vartype access_review_default_settings: + azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewDefaultSettingsOperations + :ivar access_review_schedule_definitions_assigned_for_my_approval: + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations + :vartype access_review_schedule_definitions_assigned_for_my_approval: + azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations + :ivar access_review_instances_assigned_for_my_approval: + AccessReviewInstancesAssignedForMyApprovalOperations operations + :vartype access_review_instances_assigned_for_my_approval: + azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewInstancesAssignedForMyApprovalOperations :ivar access_review_instance_my_decisions: AccessReviewInstanceMyDecisionsOperations operations - :vartype access_review_instance_my_decisions: azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewInstanceMyDecisionsOperations - :param credential: Credential needed for the client to connect to Azure. + :vartype access_review_instance_my_decisions: + azure.mgmt.authorization.v2021_03_01_preview.aio.operations.AccessReviewInstanceMyDecisionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2021-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AuthorizationManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.access_review_schedule_definitions = AccessReviewScheduleDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instances = AccessReviewInstancesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance = AccessReviewInstanceOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance_decisions = AccessReviewInstanceDecisionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_default_settings = AccessReviewDefaultSettingsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.access_review_schedule_definitions_assigned_for_my_approval = AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_schedule_definitions_assigned_for_my_approval = ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) self.access_review_instances_assigned_for_my_approval = AccessReviewInstancesAssignedForMyApprovalOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.access_review_instance_my_decisions = AccessReviewInstanceMyDecisionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_configuration.py index 984ddf81ab6..5df9e6760bf 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_configuration.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,49 +19,48 @@ from azure.core.credentials_async import AsyncTokenCredential -class AuthorizationManagementClientConfiguration(Configuration): +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AuthorizationManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2021-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2021-03-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2021-03-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-authorization/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/__init__.py index 9fe7178064d..2ed7cbae216 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/__init__.py @@ -12,18 +12,28 @@ from ._access_review_instance_operations import AccessReviewInstanceOperations from ._access_review_instance_decisions_operations import AccessReviewInstanceDecisionsOperations from ._access_review_default_settings_operations import AccessReviewDefaultSettingsOperations -from ._access_review_schedule_definitions_assigned_for_my_approval_operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations -from ._access_review_instances_assigned_for_my_approval_operations import AccessReviewInstancesAssignedForMyApprovalOperations +from ._access_review_schedule_definitions_assigned_for_my_approval_operations import ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, +) +from ._access_review_instances_assigned_for_my_approval_operations import ( + AccessReviewInstancesAssignedForMyApprovalOperations, +) from ._access_review_instance_my_decisions_operations import AccessReviewInstanceMyDecisionsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'Operations', - 'AccessReviewScheduleDefinitionsOperations', - 'AccessReviewInstancesOperations', - 'AccessReviewInstanceOperations', - 'AccessReviewInstanceDecisionsOperations', - 'AccessReviewDefaultSettingsOperations', - 'AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations', - 'AccessReviewInstancesAssignedForMyApprovalOperations', - 'AccessReviewInstanceMyDecisionsOperations', + "Operations", + "AccessReviewScheduleDefinitionsOperations", + "AccessReviewInstancesOperations", + "AccessReviewInstanceOperations", + "AccessReviewInstanceDecisionsOperations", + "AccessReviewDefaultSettingsOperations", + "AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations", + "AccessReviewInstancesAssignedForMyApprovalOperations", + "AccessReviewInstanceMyDecisionsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_default_settings_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_default_settings_operations.py index 07a4a1853c0..609ff0b952e 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_default_settings_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_default_settings_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,147 +6,208 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_default_settings_operations import build_get_request, build_put_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewDefaultSettingsOperations: - """AccessReviewDefaultSettingsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewDefaultSettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_default_settings` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get( - self, - **kwargs: Any - ) -> "_models.AccessReviewDefaultSettings": + @distributed_trace_async + async def get(self, **kwargs: Any) -> _models.AccessReviewDefaultSettings: """Get access review default settings for the subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDefaultSettings, or the result of cls(response) + :return: AccessReviewDefaultSettings or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDefaultSettings - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDefaultSettings"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDefaultSettings', pipeline_response) + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore + + @overload async def put( - self, - properties: "_models.AccessReviewScheduleSettings", - **kwargs: Any - ) -> "_models.AccessReviewDefaultSettings": + self, properties: _models.AccessReviewScheduleSettings, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: """Get access review default settings for the subscription. - :param properties: Access review schedule settings. - :type properties: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleSettings + :param properties: Access review schedule settings. Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleSettings + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDefaultSettings, or the result of cls(response) + :return: AccessReviewDefaultSettings or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDefaultSettings - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put( + self, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put( + self, properties: Union[_models.AccessReviewScheduleSettings, IO], **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleSettings or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDefaultSettings"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.put.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewScheduleSettings') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleSettings") + + request = build_put_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDefaultSettings', pipeline_response) + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default'} # type: ignore + + put.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_decisions_operations.py index 46aa06675b4..08d8a2891fc 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_decisions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_decisions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,102 +6,117 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instance_decisions_operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewInstanceDecisionsOperations: - """AccessReviewInstanceDecisionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewInstanceDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance_decisions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - schedule_definition_id: str, - id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewDecisionListResult"]: + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewDecision"]: """Get access review instance decisions. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewDecisionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecisionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecisionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewDecisionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -109,17 +125,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py index 11b4e5669c5..83f8b528ab0 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,101 +6,121 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._access_review_instance_my_decisions_operations import ( + build_get_by_id_request, + build_list_request, + build_patch_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewInstanceMyDecisionsOperations: - """AccessReviewInstanceMyDecisionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewInstanceMyDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance_my_decisions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - schedule_definition_id: str, - id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewDecisionListResult"]: + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewDecision"]: """Get my access review instance decisions. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewDecisionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecisionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecisionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewDecisionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -108,149 +129,229 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore + + @distributed_trace_async async def get_by_id( - self, - schedule_definition_id: str, - id: str, - decision_id: str, - **kwargs: Any - ) -> "_models.AccessReviewDecision": + self, schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any + ) -> _models.AccessReviewDecision: """Get my single access review instance decision. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str - :param decision_id: The id of the decision record. + :param decision_id: The id of the decision record. Required. :type decision_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDecision, or the result of cls(response) + :return: AccessReviewDecision or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecision"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'decisionId': self._serialize.url("decision_id", decision_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDecision', pipeline_response) + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}'} # type: ignore + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore + + @overload async def patch( self, schedule_definition_id: str, id: str, decision_id: str, - properties: "_models.AccessReviewDecisionProperties", + properties: _models.AccessReviewDecisionProperties, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.AccessReviewDecision": + ) -> _models.AccessReviewDecision: """Record a decision. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str - :param decision_id: The id of the decision record. + :param decision_id: The id of the decision record. Required. :type decision_id: str - :param properties: Access review decision properties to patch. - :type properties: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecisionProperties + :param properties: Access review decision properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecisionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDecision, or the result of cls(response) + :return: AccessReviewDecision or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: Union[_models.AccessReviewDecisionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecisionProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecision"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.patch.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'decisionId': self._serialize.url("decision_id", decision_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewDecisionProperties') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewDecisionProperties") + + request = build_patch_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDecision', pipeline_response) + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - patch.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}'} # type: ignore + + patch.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_operations.py index 05b717381d8..a6852695ba4 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instance_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,316 +6,336 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._access_review_instance_operations import ( + build_accept_recommendations_request, + build_apply_decisions_request, + build_reset_decisions_request, + build_send_reminders_request, + build_stop_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewInstanceOperations: - """AccessReviewInstanceOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - async def stop( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any ) -> None: """An action to stop an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.stop.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - stop.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop'} # type: ignore + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop"} # type: ignore - async def reset_decisions( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any + @distributed_trace_async + async def reset_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any ) -> None: """An action to reset all decisions for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.reset_decisions.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reset_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.reset_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - reset_decisions.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions'} # type: ignore + reset_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions"} # type: ignore - async def apply_decisions( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any + @distributed_trace_async + async def apply_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any ) -> None: """An action to apply all decisions for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.apply_decisions.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_apply_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.apply_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - apply_decisions.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions'} # type: ignore + apply_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions"} # type: ignore - async def send_reminders( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any + @distributed_trace_async + async def send_reminders( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any ) -> None: """An action to send reminders for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.send_reminders.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_send_reminders_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.send_reminders.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - send_reminders.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders'} # type: ignore + send_reminders.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders"} # type: ignore - async def accept_recommendations( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any + @distributed_trace_async + async def accept_recommendations( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any ) -> None: """An action to accept recommendations for decision in an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.accept_recommendations.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_accept_recommendations_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.accept_recommendations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - accept_recommendations.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations'} # type: ignore + accept_recommendations.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py index 51d11415220..d6a93c39390 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,97 +6,117 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instances_assigned_for_my_approval_operations import ( + build_get_by_id_request, + build_list_request, +) -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewInstancesAssignedForMyApprovalOperations: - """AccessReviewInstancesAssignedForMyApprovalOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewInstancesAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instances_assigned_for_my_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - schedule_definition_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewInstanceListResult"]: + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewInstance"]: """Get access review instances assigned for my approval. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewInstanceListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewInstanceListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -104,75 +125,76 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances'} # type: ignore - - async def get_by_id( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any - ) -> "_models.AccessReviewInstance": + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: """Get single access review instance assigned for my approval. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewInstance, or the result of cls(response) + :return: AccessReviewInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewInstance', pipeline_response) + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}'} # type: ignore + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instances_operations.py index ac8213f0010..2225f897e6f 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instances_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_instances_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,98 +6,115 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instances_operations import build_get_by_id_request, build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewInstancesOperations: - """AccessReviewInstancesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instances` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - schedule_definition_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewInstanceListResult"]: + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewInstance"]: """Get access review instances. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewInstanceListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewInstanceListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -105,76 +123,77 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances'} # type: ignore - - async def get_by_id( - self, - schedule_definition_id: str, - id: str, - **kwargs: Any - ) -> "_models.AccessReviewInstance": + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: """Get access review instances. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewInstance, or the result of cls(response) + :return: AccessReviewInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewInstance', pipeline_response) + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}'} # type: ignore + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py index af0a064b834..0f9d9b31e54 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,90 +6,110 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_schedule_definitions_assigned_for_my_approval_operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations: - """AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions_assigned_for_my_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewScheduleDefinitionListResult"]: + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewScheduleDefinition"]: """Get access review instances assigned for my approval. :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewScheduleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewScheduleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -97,17 +118,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_schedule_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_schedule_definitions_operations.py index d762fddac40..df10b9ee796 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_schedule_definitions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_access_review_schedule_definitions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,94 +6,118 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._access_review_schedule_definitions_operations import ( + build_create_or_update_by_id_request, + build_delete_by_id_request, + build_get_by_id_request, + build_list_request, + build_stop_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AccessReviewScheduleDefinitionsOperations: - """AccessReviewScheduleDefinitionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewScheduleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.AccessReviewScheduleDefinitionListResult"]: + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewScheduleDefinition"]: """Get access review schedule definitions. :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewScheduleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewScheduleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -101,239 +126,307 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get_by_id( - self, - schedule_definition_id: str, - **kwargs: Any - ) -> "_models.AccessReviewScheduleDefinition": + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, **kwargs: Any) -> _models.AccessReviewScheduleDefinition: """Get single access review definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewScheduleDefinition, or the result of cls(response) + :return: AccessReviewScheduleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewScheduleDefinition', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore - async def delete_by_id( - self, - schedule_definition_id: str, - **kwargs: Any + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def delete_by_id( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any ) -> None: """Delete access review schedule definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_delete_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore + delete_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + @overload async def create_or_update_by_id( self, schedule_definition_id: str, - properties: "_models.AccessReviewScheduleDefinitionProperties", + properties: _models.AccessReviewScheduleDefinitionProperties, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.AccessReviewScheduleDefinition": + ) -> _models.AccessReviewScheduleDefinition: """Create or Update access review schedule definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param properties: Access review schedule definition properties. - :type properties: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionProperties + :param properties: Access review schedule definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewScheduleDefinition, or the result of cls(response) + :return: AccessReviewScheduleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_by_id( + self, schedule_definition_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: Union[_models.AccessReviewScheduleDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionProperties + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewScheduleDefinitionProperties') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleDefinitionProperties") + + request = build_create_or_update_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewScheduleDefinition', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore - async def stop( - self, - schedule_definition_id: str, - **kwargs: Any + create_or_update_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any ) -> None: """Stop access review definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.stop.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - stop.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop'} # type: ignore + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_operations.py index 7dafd9b6b2b..f1a1fc8fbbd 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,101 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.aio.AuthorizationManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists the operations available from this provider. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -89,17 +109,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/operations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/__init__.py index 61394ed229f..25e650b919e 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/__init__.py @@ -6,101 +6,82 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import AccessReviewDecision - from ._models_py3 import AccessReviewDecisionIdentity - from ._models_py3 import AccessReviewDecisionListResult - from ._models_py3 import AccessReviewDecisionProperties - from ._models_py3 import AccessReviewDecisionResource - from ._models_py3 import AccessReviewDecisionServicePrincipalIdentity - from ._models_py3 import AccessReviewDecisionUserIdentity - from ._models_py3 import AccessReviewDefaultSettings - from ._models_py3 import AccessReviewInstance - from ._models_py3 import AccessReviewInstanceListResult - from ._models_py3 import AccessReviewReviewer - from ._models_py3 import AccessReviewScheduleDefinition - from ._models_py3 import AccessReviewScheduleDefinitionListResult - from ._models_py3 import AccessReviewScheduleDefinitionProperties - from ._models_py3 import AccessReviewScheduleSettings - from ._models_py3 import ErrorDefinition - from ._models_py3 import ErrorDefinitionProperties - from ._models_py3 import Operation - from ._models_py3 import OperationDisplay - from ._models_py3 import OperationListResult -except (SyntaxError, ImportError): - from ._models import AccessReviewDecision # type: ignore - from ._models import AccessReviewDecisionIdentity # type: ignore - from ._models import AccessReviewDecisionListResult # type: ignore - from ._models import AccessReviewDecisionProperties # type: ignore - from ._models import AccessReviewDecisionResource # type: ignore - from ._models import AccessReviewDecisionServicePrincipalIdentity # type: ignore - from ._models import AccessReviewDecisionUserIdentity # type: ignore - from ._models import AccessReviewDefaultSettings # type: ignore - from ._models import AccessReviewInstance # type: ignore - from ._models import AccessReviewInstanceListResult # type: ignore - from ._models import AccessReviewReviewer # type: ignore - from ._models import AccessReviewScheduleDefinition # type: ignore - from ._models import AccessReviewScheduleDefinitionListResult # type: ignore - from ._models import AccessReviewScheduleDefinitionProperties # type: ignore - from ._models import AccessReviewScheduleSettings # type: ignore - from ._models import ErrorDefinition # type: ignore - from ._models import ErrorDefinitionProperties # type: ignore - from ._models import Operation # type: ignore - from ._models import OperationDisplay # type: ignore - from ._models import OperationListResult # type: ignore +from ._models_py3 import AccessReviewDecision +from ._models_py3 import AccessReviewDecisionIdentity +from ._models_py3 import AccessReviewDecisionListResult +from ._models_py3 import AccessReviewDecisionProperties +from ._models_py3 import AccessReviewDecisionResource +from ._models_py3 import AccessReviewDecisionServicePrincipalIdentity +from ._models_py3 import AccessReviewDecisionUserIdentity +from ._models_py3 import AccessReviewDefaultSettings +from ._models_py3 import AccessReviewInstance +from ._models_py3 import AccessReviewInstanceListResult +from ._models_py3 import AccessReviewReviewer +from ._models_py3 import AccessReviewScheduleDefinition +from ._models_py3 import AccessReviewScheduleDefinitionListResult +from ._models_py3 import AccessReviewScheduleDefinitionProperties +from ._models_py3 import AccessReviewScheduleSettings +from ._models_py3 import ErrorDefinition +from ._models_py3 import ErrorDefinitionProperties +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult -from ._authorization_management_client_enums import ( - AccessRecommendationType, - AccessReviewActorIdentityType, - AccessReviewApplyResult, - AccessReviewInstanceStatus, - AccessReviewRecurrencePatternType, - AccessReviewRecurrenceRangeType, - AccessReviewResult, - AccessReviewReviewerType, - AccessReviewScheduleDefinitionReviewersType, - AccessReviewScheduleDefinitionStatus, - AccessReviewScopeAssignmentState, - AccessReviewScopePrincipalType, - DecisionResourceType, - DecisionTargetType, - DefaultDecisionType, -) +from ._authorization_management_client_enums import AccessRecommendationType +from ._authorization_management_client_enums import AccessReviewActorIdentityType +from ._authorization_management_client_enums import AccessReviewApplyResult +from ._authorization_management_client_enums import AccessReviewInstanceStatus +from ._authorization_management_client_enums import AccessReviewRecurrencePatternType +from ._authorization_management_client_enums import AccessReviewRecurrenceRangeType +from ._authorization_management_client_enums import AccessReviewResult +from ._authorization_management_client_enums import AccessReviewReviewerType +from ._authorization_management_client_enums import AccessReviewScheduleDefinitionReviewersType +from ._authorization_management_client_enums import AccessReviewScheduleDefinitionStatus +from ._authorization_management_client_enums import AccessReviewScopeAssignmentState +from ._authorization_management_client_enums import AccessReviewScopePrincipalType +from ._authorization_management_client_enums import DecisionResourceType +from ._authorization_management_client_enums import DecisionTargetType +from ._authorization_management_client_enums import DefaultDecisionType +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'AccessReviewDecision', - 'AccessReviewDecisionIdentity', - 'AccessReviewDecisionListResult', - 'AccessReviewDecisionProperties', - 'AccessReviewDecisionResource', - 'AccessReviewDecisionServicePrincipalIdentity', - 'AccessReviewDecisionUserIdentity', - 'AccessReviewDefaultSettings', - 'AccessReviewInstance', - 'AccessReviewInstanceListResult', - 'AccessReviewReviewer', - 'AccessReviewScheduleDefinition', - 'AccessReviewScheduleDefinitionListResult', - 'AccessReviewScheduleDefinitionProperties', - 'AccessReviewScheduleSettings', - 'ErrorDefinition', - 'ErrorDefinitionProperties', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'AccessRecommendationType', - 'AccessReviewActorIdentityType', - 'AccessReviewApplyResult', - 'AccessReviewInstanceStatus', - 'AccessReviewRecurrencePatternType', - 'AccessReviewRecurrenceRangeType', - 'AccessReviewResult', - 'AccessReviewReviewerType', - 'AccessReviewScheduleDefinitionReviewersType', - 'AccessReviewScheduleDefinitionStatus', - 'AccessReviewScopeAssignmentState', - 'AccessReviewScopePrincipalType', - 'DecisionResourceType', - 'DecisionTargetType', - 'DefaultDecisionType', + "AccessReviewDecision", + "AccessReviewDecisionIdentity", + "AccessReviewDecisionListResult", + "AccessReviewDecisionProperties", + "AccessReviewDecisionResource", + "AccessReviewDecisionServicePrincipalIdentity", + "AccessReviewDecisionUserIdentity", + "AccessReviewDefaultSettings", + "AccessReviewInstance", + "AccessReviewInstanceListResult", + "AccessReviewReviewer", + "AccessReviewScheduleDefinition", + "AccessReviewScheduleDefinitionListResult", + "AccessReviewScheduleDefinitionProperties", + "AccessReviewScheduleSettings", + "ErrorDefinition", + "ErrorDefinitionProperties", + "Operation", + "OperationDisplay", + "OperationListResult", + "AccessRecommendationType", + "AccessReviewActorIdentityType", + "AccessReviewApplyResult", + "AccessReviewInstanceStatus", + "AccessReviewRecurrencePatternType", + "AccessReviewRecurrenceRangeType", + "AccessReviewResult", + "AccessReviewReviewerType", + "AccessReviewScheduleDefinitionReviewersType", + "AccessReviewScheduleDefinitionStatus", + "AccessReviewScopeAssignmentState", + "AccessReviewScopePrincipalType", + "DecisionResourceType", + "DecisionTargetType", + "DefaultDecisionType", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_authorization_management_client_enums.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_authorization_management_client_enums.py index 3342334011d..a98d78c0b73 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_authorization_management_client_enums.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_authorization_management_client_enums.py @@ -6,44 +6,27 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass - -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class AccessRecommendationType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The feature- generated recommendation shown to the reviewer. - """ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AccessRecommendationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The feature- generated recommendation shown to the reviewer.""" APPROVE = "Approve" DENY = "Deny" NO_INFO_AVAILABLE = "NoInfoAvailable" -class AccessReviewActorIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The identity type : user/servicePrincipal - """ + +class AccessReviewActorIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type : user/servicePrincipal.""" USER = "user" SERVICE_PRINCIPAL = "servicePrincipal" -class AccessReviewApplyResult(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The outcome of applying the decision. - """ + +class AccessReviewApplyResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The outcome of applying the decision.""" NEW = "New" APPLYING = "Applying" @@ -52,9 +35,9 @@ class AccessReviewApplyResult(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum APPLIED_SUCCESSFULLY_BUT_OBJECT_NOT_FOUND = "AppliedSuccessfullyButObjectNotFound" APPLY_NOT_SUPPORTED = "ApplyNotSupported" -class AccessReviewInstanceStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """This read-only field specifies the status of an access review instance. - """ + +class AccessReviewInstanceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This read-only field specifies the status of an access review instance.""" NOT_STARTED = "NotStarted" IN_PROGRESS = "InProgress" @@ -68,24 +51,25 @@ class AccessReviewInstanceStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, E AUTO_REVIEWED = "AutoReviewed" STARTING = "Starting" -class AccessReviewRecurrencePatternType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The recurrence type : weekly, monthly, etc. - """ + +class AccessReviewRecurrencePatternType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The recurrence type : weekly, monthly, etc.""" WEEKLY = "weekly" ABSOLUTE_MONTHLY = "absoluteMonthly" -class AccessReviewRecurrenceRangeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The recurrence range type. The possible values are: endDate, noEnd, numbered. - """ + +class AccessReviewRecurrenceRangeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The recurrence range type. The possible values are: endDate, noEnd, numbered.""" END_DATE = "endDate" NO_END = "noEnd" NUMBERED = "numbered" -class AccessReviewResult(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class AccessReviewResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The decision on the approval step. This value is initially set to NotReviewed. Approvers can - take action of Approve/Deny + take action of Approve/Deny. """ APPROVE = "Approve" @@ -94,14 +78,15 @@ class AccessReviewResult(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DONT_KNOW = "DontKnow" NOT_NOTIFIED = "NotNotified" -class AccessReviewReviewerType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The identity type : user/servicePrincipal - """ + +class AccessReviewReviewerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type : user/servicePrincipal.""" USER = "user" SERVICE_PRINCIPAL = "servicePrincipal" -class AccessReviewScheduleDefinitionReviewersType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class AccessReviewScheduleDefinitionReviewersType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """This field specifies the type of reviewers for a review. Usually for a review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be assigned and instead be chosen dynamically. For example managers review or self review. @@ -111,9 +96,9 @@ class AccessReviewScheduleDefinitionReviewersType(with_metaclass(_CaseInsensitiv SELF = "Self" MANAGERS = "Managers" -class AccessReviewScheduleDefinitionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """This read-only field specifies the status of an accessReview. - """ + +class AccessReviewScheduleDefinitionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This read-only field specifies the status of an accessReview.""" NOT_STARTED = "NotStarted" IN_PROGRESS = "InProgress" @@ -127,37 +112,37 @@ class AccessReviewScheduleDefinitionStatus(with_metaclass(_CaseInsensitiveEnumMe AUTO_REVIEWED = "AutoReviewed" STARTING = "Starting" -class AccessReviewScopeAssignmentState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The role assignment state eligible/active to review - """ + +class AccessReviewScopeAssignmentState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The role assignment state eligible/active to review.""" ELIGIBLE = "eligible" ACTIVE = "active" -class AccessReviewScopePrincipalType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The identity type user/servicePrincipal to review - """ + +class AccessReviewScopePrincipalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type user/servicePrincipal to review.""" USER = "user" GUEST_USER = "guestUser" SERVICE_PRINCIPAL = "servicePrincipal" -class DecisionResourceType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of resource - """ + +class DecisionResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of resource.""" AZURE_ROLE = "azureRole" -class DecisionTargetType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of decision target : User/ServicePrincipal - """ + +class DecisionTargetType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of decision target : User/ServicePrincipal.""" USER = "user" SERVICE_PRINCIPAL = "servicePrincipal" -class DefaultDecisionType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """This specifies the behavior for the autoReview feature when an access review completes. - """ + +class DefaultDecisionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This specifies the behavior for the autoReview feature when an access review completes.""" APPROVE = "Approve" DENY = "Deny" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_models.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_models.py deleted file mode 100644 index ae4866e6351..00000000000 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_models.py +++ /dev/null @@ -1,1352 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class AccessReviewDecision(msrest.serialization.Model): - """Access Review. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The access review decision id. - :vartype id: str - :ivar name: The access review decision name. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - :ivar recommendation: The feature- generated recommendation shown to the reviewer. Possible - values include: "Approve", "Deny", "NoInfoAvailable". - :vartype recommendation: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessRecommendationType - :param decision: The decision on the approval step. This value is initially set to NotReviewed. - Approvers can take action of Approve/Deny. Possible values include: "Approve", "Deny", - "NotReviewed", "DontKnow", "NotNotified". - :type decision: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str - :ivar reviewed_date_time: Date Time when a decision was taken. - :vartype reviewed_date_time: ~datetime.datetime - :ivar apply_result: The outcome of applying the decision. Possible values include: "New", - "Applying", "AppliedSuccessfully", "AppliedWithUnknownFailure", - "AppliedSuccessfullyButObjectNotFound", "ApplyNotSupported". - :vartype apply_result: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewApplyResult - :ivar applied_date_time: The date and time when the review decision was applied. - :vartype applied_date_time: ~datetime.datetime - :ivar principal_id_properties_applied_by_principal_id: The identity id. - :vartype principal_id_properties_applied_by_principal_id: str - :ivar principal_type_properties_applied_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". - :vartype principal_type_properties_applied_by_principal_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name_properties_applied_by_principal_name: The identity display name. - :vartype principal_name_properties_applied_by_principal_name: str - :ivar user_principal_name_properties_applied_by_user_principal_name: The user principal name(if - valid). - :vartype user_principal_name_properties_applied_by_user_principal_name: str - :ivar principal_id_properties_reviewed_by_principal_id: The identity id. - :vartype principal_id_properties_reviewed_by_principal_id: str - :ivar principal_type_properties_reviewed_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". - :vartype principal_type_properties_reviewed_by_principal_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name_properties_reviewed_by_principal_name: The identity display name. - :vartype principal_name_properties_reviewed_by_principal_name: str - :ivar user_principal_name_properties_reviewed_by_user_principal_name: The user principal - name(if valid). - :vartype user_principal_name_properties_reviewed_by_user_principal_name: str - :param type_properties_resource_type: The type of resource.Constant filled by server. Possible - values include: "azureRole". - :type type_properties_resource_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionResourceType - :ivar id_properties_resource_id: The id of resource associated with a decision record. - :vartype id_properties_resource_id: str - :ivar display_name_properties_resource_display_name: The display name of resource associated - with a decision record. - :vartype display_name_properties_resource_display_name: str - :param type_properties_principal_type: The type of decision target : - User/ServicePrincipal.Constant filled by server. Possible values include: "user", - "servicePrincipal". - :type type_properties_principal_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType - :ivar id_properties_principal_id: The id of principal whose access was reviewed. - :vartype id_properties_principal_id: str - :ivar display_name_properties_principal_display_name: The display name of the user whose access - was reviewed. - :vartype display_name_properties_principal_display_name: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'recommendation': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'apply_result': {'readonly': True}, - 'applied_date_time': {'readonly': True}, - 'principal_id_properties_applied_by_principal_id': {'readonly': True}, - 'principal_type_properties_applied_by_principal_type': {'readonly': True}, - 'principal_name_properties_applied_by_principal_name': {'readonly': True}, - 'user_principal_name_properties_applied_by_user_principal_name': {'readonly': True}, - 'principal_id_properties_reviewed_by_principal_id': {'readonly': True}, - 'principal_type_properties_reviewed_by_principal_type': {'readonly': True}, - 'principal_name_properties_reviewed_by_principal_name': {'readonly': True}, - 'user_principal_name_properties_reviewed_by_user_principal_name': {'readonly': True}, - 'id_properties_resource_id': {'readonly': True}, - 'display_name_properties_resource_display_name': {'readonly': True}, - 'id_properties_principal_id': {'readonly': True}, - 'display_name_properties_principal_display_name': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'recommendation': {'key': 'properties.recommendation', 'type': 'str'}, - 'decision': {'key': 'properties.decision', 'type': 'str'}, - 'justification': {'key': 'properties.justification', 'type': 'str'}, - 'reviewed_date_time': {'key': 'properties.reviewedDateTime', 'type': 'iso-8601'}, - 'apply_result': {'key': 'properties.applyResult', 'type': 'str'}, - 'applied_date_time': {'key': 'properties.appliedDateTime', 'type': 'iso-8601'}, - 'principal_id_properties_applied_by_principal_id': {'key': 'properties.appliedBy.principalId', 'type': 'str'}, - 'principal_type_properties_applied_by_principal_type': {'key': 'properties.appliedBy.principalType', 'type': 'str'}, - 'principal_name_properties_applied_by_principal_name': {'key': 'properties.appliedBy.principalName', 'type': 'str'}, - 'user_principal_name_properties_applied_by_user_principal_name': {'key': 'properties.appliedBy.userPrincipalName', 'type': 'str'}, - 'principal_id_properties_reviewed_by_principal_id': {'key': 'properties.reviewedBy.principalId', 'type': 'str'}, - 'principal_type_properties_reviewed_by_principal_type': {'key': 'properties.reviewedBy.principalType', 'type': 'str'}, - 'principal_name_properties_reviewed_by_principal_name': {'key': 'properties.reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name_properties_reviewed_by_user_principal_name': {'key': 'properties.reviewedBy.userPrincipalName', 'type': 'str'}, - 'type_properties_resource_type': {'key': 'properties.resource.type', 'type': 'str'}, - 'id_properties_resource_id': {'key': 'properties.resource.id', 'type': 'str'}, - 'display_name_properties_resource_display_name': {'key': 'properties.resource.displayName', 'type': 'str'}, - 'type_properties_principal_type': {'key': 'properties.principal.type', 'type': 'str'}, - 'id_properties_principal_id': {'key': 'properties.principal.id', 'type': 'str'}, - 'display_name_properties_principal_display_name': {'key': 'properties.principal.displayName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDecision, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.recommendation = None - self.decision = kwargs.get('decision', None) - self.justification = kwargs.get('justification', None) - self.reviewed_date_time = None - self.apply_result = None - self.applied_date_time = None - self.principal_id_properties_applied_by_principal_id = None - self.principal_type_properties_applied_by_principal_type = None - self.principal_name_properties_applied_by_principal_name = None - self.user_principal_name_properties_applied_by_user_principal_name = None - self.principal_id_properties_reviewed_by_principal_id = None - self.principal_type_properties_reviewed_by_principal_type = None - self.principal_name_properties_reviewed_by_principal_name = None - self.user_principal_name_properties_reviewed_by_user_principal_name = None - self.type_properties_resource_type = None # type: Optional[str] - self.id_properties_resource_id = None - self.display_name_properties_resource_display_name = None - self.type_properties_principal_type = None # type: Optional[str] - self.id_properties_principal_id = None - self.display_name_properties_principal_display_name = None - - -class AccessReviewDecisionIdentity(msrest.serialization.Model): - """Target of the decision. - - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: AccessReviewDecisionServicePrincipalIdentity, AccessReviewDecisionUserIdentity. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType - :ivar id: The id of principal whose access was reviewed. - :vartype id: str - :ivar display_name: The display name of the user whose access was reviewed. - :vartype display_name: str - """ - - _validation = { - 'type': {'required': True}, - 'id': {'readonly': True}, - 'display_name': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - } - - _subtype_map = { - 'type': {'servicePrincipal': 'AccessReviewDecisionServicePrincipalIdentity', 'user': 'AccessReviewDecisionUserIdentity'} - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionIdentity, self).__init__(**kwargs) - self.type = None # type: Optional[str] - self.id = None - self.display_name = None - - -class AccessReviewDecisionListResult(msrest.serialization.Model): - """List of access review decisions. - - :param value: Access Review Decision list. - :type value: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewDecision]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class AccessReviewDecisionProperties(msrest.serialization.Model): - """Approval Step. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar recommendation: The feature- generated recommendation shown to the reviewer. Possible - values include: "Approve", "Deny", "NoInfoAvailable". - :vartype recommendation: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessRecommendationType - :param decision: The decision on the approval step. This value is initially set to NotReviewed. - Approvers can take action of Approve/Deny. Possible values include: "Approve", "Deny", - "NotReviewed", "DontKnow", "NotNotified". - :type decision: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str - :ivar reviewed_date_time: Date Time when a decision was taken. - :vartype reviewed_date_time: ~datetime.datetime - :ivar apply_result: The outcome of applying the decision. Possible values include: "New", - "Applying", "AppliedSuccessfully", "AppliedWithUnknownFailure", - "AppliedSuccessfullyButObjectNotFound", "ApplyNotSupported". - :vartype apply_result: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewApplyResult - :ivar applied_date_time: The date and time when the review decision was applied. - :vartype applied_date_time: ~datetime.datetime - :ivar principal_id_applied_by_principal_id: The identity id. - :vartype principal_id_applied_by_principal_id: str - :ivar principal_type_applied_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". - :vartype principal_type_applied_by_principal_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name_applied_by_principal_name: The identity display name. - :vartype principal_name_applied_by_principal_name: str - :ivar user_principal_name_applied_by_user_principal_name: The user principal name(if valid). - :vartype user_principal_name_applied_by_user_principal_name: str - :ivar principal_id_reviewed_by_principal_id: The identity id. - :vartype principal_id_reviewed_by_principal_id: str - :ivar principal_type_reviewed_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". - :vartype principal_type_reviewed_by_principal_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name_reviewed_by_principal_name: The identity display name. - :vartype principal_name_reviewed_by_principal_name: str - :ivar user_principal_name_reviewed_by_user_principal_name: The user principal name(if valid). - :vartype user_principal_name_reviewed_by_user_principal_name: str - :param type_resource_type: The type of resource.Constant filled by server. Possible values - include: "azureRole". - :type type_resource_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionResourceType - :ivar id_resource_id: The id of resource associated with a decision record. - :vartype id_resource_id: str - :ivar display_name_resource_display_name: The display name of resource associated with a - decision record. - :vartype display_name_resource_display_name: str - :param type_principal_type: The type of decision target : User/ServicePrincipal.Constant filled - by server. Possible values include: "user", "servicePrincipal". - :type type_principal_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType - :ivar id_principal_id: The id of principal whose access was reviewed. - :vartype id_principal_id: str - :ivar display_name_principal_display_name: The display name of the user whose access was - reviewed. - :vartype display_name_principal_display_name: str - """ - - _validation = { - 'recommendation': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'apply_result': {'readonly': True}, - 'applied_date_time': {'readonly': True}, - 'principal_id_applied_by_principal_id': {'readonly': True}, - 'principal_type_applied_by_principal_type': {'readonly': True}, - 'principal_name_applied_by_principal_name': {'readonly': True}, - 'user_principal_name_applied_by_user_principal_name': {'readonly': True}, - 'principal_id_reviewed_by_principal_id': {'readonly': True}, - 'principal_type_reviewed_by_principal_type': {'readonly': True}, - 'principal_name_reviewed_by_principal_name': {'readonly': True}, - 'user_principal_name_reviewed_by_user_principal_name': {'readonly': True}, - 'id_resource_id': {'readonly': True}, - 'display_name_resource_display_name': {'readonly': True}, - 'id_principal_id': {'readonly': True}, - 'display_name_principal_display_name': {'readonly': True}, - } - - _attribute_map = { - 'recommendation': {'key': 'recommendation', 'type': 'str'}, - 'decision': {'key': 'decision', 'type': 'str'}, - 'justification': {'key': 'justification', 'type': 'str'}, - 'reviewed_date_time': {'key': 'reviewedDateTime', 'type': 'iso-8601'}, - 'apply_result': {'key': 'applyResult', 'type': 'str'}, - 'applied_date_time': {'key': 'appliedDateTime', 'type': 'iso-8601'}, - 'principal_id_applied_by_principal_id': {'key': 'appliedBy.principalId', 'type': 'str'}, - 'principal_type_applied_by_principal_type': {'key': 'appliedBy.principalType', 'type': 'str'}, - 'principal_name_applied_by_principal_name': {'key': 'appliedBy.principalName', 'type': 'str'}, - 'user_principal_name_applied_by_user_principal_name': {'key': 'appliedBy.userPrincipalName', 'type': 'str'}, - 'principal_id_reviewed_by_principal_id': {'key': 'reviewedBy.principalId', 'type': 'str'}, - 'principal_type_reviewed_by_principal_type': {'key': 'reviewedBy.principalType', 'type': 'str'}, - 'principal_name_reviewed_by_principal_name': {'key': 'reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name_reviewed_by_user_principal_name': {'key': 'reviewedBy.userPrincipalName', 'type': 'str'}, - 'type_resource_type': {'key': 'resource.type', 'type': 'str'}, - 'id_resource_id': {'key': 'resource.id', 'type': 'str'}, - 'display_name_resource_display_name': {'key': 'resource.displayName', 'type': 'str'}, - 'type_principal_type': {'key': 'principal.type', 'type': 'str'}, - 'id_principal_id': {'key': 'principal.id', 'type': 'str'}, - 'display_name_principal_display_name': {'key': 'principal.displayName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionProperties, self).__init__(**kwargs) - self.recommendation = None - self.decision = kwargs.get('decision', None) - self.justification = kwargs.get('justification', None) - self.reviewed_date_time = None - self.apply_result = None - self.applied_date_time = None - self.principal_id_applied_by_principal_id = None - self.principal_type_applied_by_principal_type = None - self.principal_name_applied_by_principal_name = None - self.user_principal_name_applied_by_user_principal_name = None - self.principal_id_reviewed_by_principal_id = None - self.principal_type_reviewed_by_principal_type = None - self.principal_name_reviewed_by_principal_name = None - self.user_principal_name_reviewed_by_user_principal_name = None - self.type_resource_type = None # type: Optional[str] - self.id_resource_id = None - self.display_name_resource_display_name = None - self.type_principal_type = None # type: Optional[str] - self.id_principal_id = None - self.display_name_principal_display_name = None - - -class AccessReviewDecisionResource(msrest.serialization.Model): - """Target of the decision. - - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: . - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of resource.Constant filled by server. Possible values - include: "azureRole". - :type type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionResourceType - :ivar id: The id of resource associated with a decision record. - :vartype id: str - :ivar display_name: The display name of resource associated with a decision record. - :vartype display_name: str - """ - - _validation = { - 'type': {'required': True}, - 'id': {'readonly': True}, - 'display_name': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - } - - _subtype_map = { - 'type': {} - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionResource, self).__init__(**kwargs) - self.type = None # type: Optional[str] - self.id = None - self.display_name = None - - -class AccessReviewDecisionServicePrincipalIdentity(AccessReviewDecisionIdentity): - """Service Principal Decision Target. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType - :ivar id: The id of principal whose access was reviewed. - :vartype id: str - :ivar display_name: The display name of the user whose access was reviewed. - :vartype display_name: str - :ivar app_id: The appId for the service principal entity being reviewed. - :vartype app_id: str - """ - - _validation = { - 'type': {'required': True}, - 'id': {'readonly': True}, - 'display_name': {'readonly': True}, - 'app_id': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'app_id': {'key': 'appId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionServicePrincipalIdentity, self).__init__(**kwargs) - self.type = 'servicePrincipal' # type: str - self.app_id = None - - -class AccessReviewDecisionUserIdentity(AccessReviewDecisionIdentity): - """User Decision Target. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType - :ivar id: The id of principal whose access was reviewed. - :vartype id: str - :ivar display_name: The display name of the user whose access was reviewed. - :vartype display_name: str - :ivar user_principal_name: The user principal name of the user whose access was reviewed. - :vartype user_principal_name: str - """ - - _validation = { - 'type': {'required': True}, - 'id': {'readonly': True}, - 'display_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'user_principal_name': {'key': 'userPrincipalName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionUserIdentity, self).__init__(**kwargs) - self.type = 'user' # type: str - self.user_principal_name = None - - -class AccessReviewDefaultSettings(msrest.serialization.Model): - """Access Review Default Settings. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The access review default settings id. This is only going to be default. - :vartype id: str - :ivar name: The access review default settings name. This is always going to be Access Review - Default Settings. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the - review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to - reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a - justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to - pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to - automatically change the target object access resource, is enabled. If not enabled, a user - must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_properties_recurrence_range_type: The recurrence range type. The possible values - are: endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_properties_recurrence_range_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date - in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. - Possible values include: "weekly", "absoluteMonthly". - :type type_properties_recurrence_pattern_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'mail_notifications_enabled': {'key': 'properties.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'properties.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'properties.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'properties.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'properties.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'properties.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'properties.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'properties.instanceDurationInDays', 'type': 'int'}, - 'type_properties_recurrence_range_type': {'key': 'properties.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'properties.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'properties.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_properties_recurrence_pattern_type': {'key': 'properties.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'properties.recurrence.pattern.interval', 'type': 'int'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewDefaultSettings, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.mail_notifications_enabled = kwargs.get('mail_notifications_enabled', None) - self.reminder_notifications_enabled = kwargs.get('reminder_notifications_enabled', None) - self.default_decision_enabled = kwargs.get('default_decision_enabled', None) - self.justification_required_on_approval = kwargs.get('justification_required_on_approval', None) - self.default_decision = kwargs.get('default_decision', None) - self.auto_apply_decisions_enabled = kwargs.get('auto_apply_decisions_enabled', None) - self.recommendations_enabled = kwargs.get('recommendations_enabled', None) - self.instance_duration_in_days = kwargs.get('instance_duration_in_days', None) - self.type_properties_recurrence_range_type = kwargs.get('type_properties_recurrence_range_type', None) - self.number_of_occurrences = kwargs.get('number_of_occurrences', None) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.type_properties_recurrence_pattern_type = kwargs.get('type_properties_recurrence_pattern_type', None) - self.interval = kwargs.get('interval', None) - - -class AccessReviewInstance(msrest.serialization.Model): - """Access Review Instance. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The access review instance id. - :vartype id: str - :ivar name: The access review instance name. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - :ivar status: This read-only field specifies the status of an access review instance. Possible - values include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". - :vartype status: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstanceStatus - :param start_date_time: The DateTime when the review instance is scheduled to be start. - :type start_date_time: ~datetime.datetime - :param end_date_time: The DateTime when the review instance is scheduled to end. - :type end_date_time: ~datetime.datetime - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'status': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewInstance, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.status = None - self.start_date_time = kwargs.get('start_date_time', None) - self.end_date_time = kwargs.get('end_date_time', None) - - -class AccessReviewInstanceListResult(msrest.serialization.Model): - """List of Access Review Instances. - - :param value: Access Review Instance list. - :type value: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewInstance]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewInstanceListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class AccessReviewReviewer(msrest.serialization.Model): - """Descriptor for what needs to be reviewed. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param principal_id: The id of the reviewer(user/servicePrincipal). - :type principal_id: str - :ivar principal_type: The identity type : user/servicePrincipal. Possible values include: - "user", "servicePrincipal". - :vartype principal_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewerType - """ - - _validation = { - 'principal_type': {'readonly': True}, - } - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'principal_type': {'key': 'principalType', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewReviewer, self).__init__(**kwargs) - self.principal_id = kwargs.get('principal_id', None) - self.principal_type = None - - -class AccessReviewScheduleDefinition(msrest.serialization.Model): - """Access Review Schedule Definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The access review schedule definition id. - :vartype id: str - :ivar name: The access review schedule definition unique id. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - :param display_name: The display name for the schedule definition. - :type display_name: str - :ivar status: This read-only field specifies the status of an accessReview. Possible values - include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". - :vartype status: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionStatus - :param description_for_admins: The description provided by the access review creator and - visible to admins. - :type description_for_admins: str - :param description_for_reviewers: The description provided by the access review creator to be - shown to reviewers. - :type description_for_reviewers: str - :param reviewers: This is the collection of reviewers. - :type reviewers: - list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] - :param backup_reviewers: This is the collection of backup reviewers. - :type backup_reviewers: - list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] - :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a - review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be - assigned and instead be chosen dynamically. For example managers review or self review. - Possible values include: "Assigned", "Self", "Managers". - :vartype reviewers_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionReviewersType - :param instances: This is the collection of instances returned when one does an expand on it. - :type instances: - list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] - :ivar resource_id: ResourceId in which this review is getting created. - :vartype resource_id: str - :ivar role_definition_id: This is used to indicate the role being reviewed. - :vartype role_definition_id: str - :ivar principal_type_properties_scope_principal_type: The identity type user/servicePrincipal - to review. Possible values include: "user", "guestUser", "servicePrincipal". - :vartype principal_type_properties_scope_principal_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScopePrincipalType - :ivar assignment_state: The role assignment state eligible/active to review. Possible values - include: "eligible", "active". - :vartype assignment_state: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScopeAssignmentState - :param inactive_duration: Duration users are inactive for. The value should be in ISO 8601 - format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert - TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, - seconds)). - :type inactive_duration: ~datetime.timedelta - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the - review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to - reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a - justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to - pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to - automatically change the target object access resource, is enabled. If not enabled, a user - must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_properties_settings_recurrence_range_type: The recurrence range type. The possible - values are: endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_properties_settings_recurrence_range_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date - in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, - etc. Possible values include: "weekly", "absoluteMonthly". - :type type_properties_settings_recurrence_pattern_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int - :ivar principal_id: The identity id. - :vartype principal_id: str - :ivar principal_type_properties_created_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". - :vartype principal_type_properties_created_by_principal_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name: The identity display name. - :vartype principal_name: str - :ivar user_principal_name: The user principal name(if valid). - :vartype user_principal_name: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'status': {'readonly': True}, - 'reviewers_type': {'readonly': True}, - 'resource_id': {'readonly': True}, - 'role_definition_id': {'readonly': True}, - 'principal_type_properties_scope_principal_type': {'readonly': True}, - 'assignment_state': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type_properties_created_by_principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'description_for_admins': {'key': 'properties.descriptionForAdmins', 'type': 'str'}, - 'description_for_reviewers': {'key': 'properties.descriptionForReviewers', 'type': 'str'}, - 'reviewers': {'key': 'properties.reviewers', 'type': '[AccessReviewReviewer]'}, - 'backup_reviewers': {'key': 'properties.backupReviewers', 'type': '[AccessReviewReviewer]'}, - 'reviewers_type': {'key': 'properties.reviewersType', 'type': 'str'}, - 'instances': {'key': 'properties.instances', 'type': '[AccessReviewInstance]'}, - 'resource_id': {'key': 'properties.scope.resourceId', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.scope.roleDefinitionId', 'type': 'str'}, - 'principal_type_properties_scope_principal_type': {'key': 'properties.scope.principalType', 'type': 'str'}, - 'assignment_state': {'key': 'properties.scope.assignmentState', 'type': 'str'}, - 'inactive_duration': {'key': 'properties.scope.inactiveDuration', 'type': 'duration'}, - 'mail_notifications_enabled': {'key': 'properties.settings.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'properties.settings.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'properties.settings.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'properties.settings.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'properties.settings.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'properties.settings.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'properties.settings.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'properties.settings.instanceDurationInDays', 'type': 'int'}, - 'type_properties_settings_recurrence_range_type': {'key': 'properties.settings.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'properties.settings.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'properties.settings.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.settings.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_properties_settings_recurrence_pattern_type': {'key': 'properties.settings.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'properties.settings.recurrence.pattern.interval', 'type': 'int'}, - 'principal_id': {'key': 'properties.createdBy.principalId', 'type': 'str'}, - 'principal_type_properties_created_by_principal_type': {'key': 'properties.createdBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'properties.createdBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'properties.createdBy.userPrincipalName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewScheduleDefinition, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.display_name = kwargs.get('display_name', None) - self.status = None - self.description_for_admins = kwargs.get('description_for_admins', None) - self.description_for_reviewers = kwargs.get('description_for_reviewers', None) - self.reviewers = kwargs.get('reviewers', None) - self.backup_reviewers = kwargs.get('backup_reviewers', None) - self.reviewers_type = None - self.instances = kwargs.get('instances', None) - self.resource_id = None - self.role_definition_id = None - self.principal_type_properties_scope_principal_type = None - self.assignment_state = None - self.inactive_duration = kwargs.get('inactive_duration', None) - self.mail_notifications_enabled = kwargs.get('mail_notifications_enabled', None) - self.reminder_notifications_enabled = kwargs.get('reminder_notifications_enabled', None) - self.default_decision_enabled = kwargs.get('default_decision_enabled', None) - self.justification_required_on_approval = kwargs.get('justification_required_on_approval', None) - self.default_decision = kwargs.get('default_decision', None) - self.auto_apply_decisions_enabled = kwargs.get('auto_apply_decisions_enabled', None) - self.recommendations_enabled = kwargs.get('recommendations_enabled', None) - self.instance_duration_in_days = kwargs.get('instance_duration_in_days', None) - self.type_properties_settings_recurrence_range_type = kwargs.get('type_properties_settings_recurrence_range_type', None) - self.number_of_occurrences = kwargs.get('number_of_occurrences', None) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.type_properties_settings_recurrence_pattern_type = kwargs.get('type_properties_settings_recurrence_pattern_type', None) - self.interval = kwargs.get('interval', None) - self.principal_id = None - self.principal_type_properties_created_by_principal_type = None - self.principal_name = None - self.user_principal_name = None - - -class AccessReviewScheduleDefinitionListResult(msrest.serialization.Model): - """List of Access Review Schedule Definitions. - - :param value: Access Review Schedule Definition list. - :type value: - list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewScheduleDefinition]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewScheduleDefinitionListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class AccessReviewScheduleDefinitionProperties(msrest.serialization.Model): - """Access Review. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param display_name: The display name for the schedule definition. - :type display_name: str - :ivar status: This read-only field specifies the status of an accessReview. Possible values - include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". - :vartype status: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionStatus - :param description_for_admins: The description provided by the access review creator and - visible to admins. - :type description_for_admins: str - :param description_for_reviewers: The description provided by the access review creator to be - shown to reviewers. - :type description_for_reviewers: str - :param reviewers: This is the collection of reviewers. - :type reviewers: - list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] - :param backup_reviewers: This is the collection of backup reviewers. - :type backup_reviewers: - list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] - :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a - review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be - assigned and instead be chosen dynamically. For example managers review or self review. - Possible values include: "Assigned", "Self", "Managers". - :vartype reviewers_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionReviewersType - :param instances: This is the collection of instances returned when one does an expand on it. - :type instances: - list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] - :ivar resource_id: ResourceId in which this review is getting created. - :vartype resource_id: str - :ivar role_definition_id: This is used to indicate the role being reviewed. - :vartype role_definition_id: str - :ivar principal_type_scope_principal_type: The identity type user/servicePrincipal to review. - Possible values include: "user", "guestUser", "servicePrincipal". - :vartype principal_type_scope_principal_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScopePrincipalType - :ivar assignment_state: The role assignment state eligible/active to review. Possible values - include: "eligible", "active". - :vartype assignment_state: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScopeAssignmentState - :param inactive_duration: Duration users are inactive for. The value should be in ISO 8601 - format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert - TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, - seconds)). - :type inactive_duration: ~datetime.timedelta - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the - review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to - reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a - justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to - pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to - automatically change the target object access resource, is enabled. If not enabled, a user - must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_settings_recurrence_range_type: The recurrence range type. The possible values are: - endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_settings_recurrence_range_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date - in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. - Possible values include: "weekly", "absoluteMonthly". - :type type_settings_recurrence_pattern_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int - :ivar principal_id: The identity id. - :vartype principal_id: str - :ivar principal_type_created_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". - :vartype principal_type_created_by_principal_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType - :ivar principal_name: The identity display name. - :vartype principal_name: str - :ivar user_principal_name: The user principal name(if valid). - :vartype user_principal_name: str - """ - - _validation = { - 'status': {'readonly': True}, - 'reviewers_type': {'readonly': True}, - 'resource_id': {'readonly': True}, - 'role_definition_id': {'readonly': True}, - 'principal_type_scope_principal_type': {'readonly': True}, - 'assignment_state': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type_created_by_principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, - } - - _attribute_map = { - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'description_for_admins': {'key': 'descriptionForAdmins', 'type': 'str'}, - 'description_for_reviewers': {'key': 'descriptionForReviewers', 'type': 'str'}, - 'reviewers': {'key': 'reviewers', 'type': '[AccessReviewReviewer]'}, - 'backup_reviewers': {'key': 'backupReviewers', 'type': '[AccessReviewReviewer]'}, - 'reviewers_type': {'key': 'reviewersType', 'type': 'str'}, - 'instances': {'key': 'instances', 'type': '[AccessReviewInstance]'}, - 'resource_id': {'key': 'scope.resourceId', 'type': 'str'}, - 'role_definition_id': {'key': 'scope.roleDefinitionId', 'type': 'str'}, - 'principal_type_scope_principal_type': {'key': 'scope.principalType', 'type': 'str'}, - 'assignment_state': {'key': 'scope.assignmentState', 'type': 'str'}, - 'inactive_duration': {'key': 'scope.inactiveDuration', 'type': 'duration'}, - 'mail_notifications_enabled': {'key': 'settings.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'settings.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'settings.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'settings.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'settings.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'settings.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'settings.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'settings.instanceDurationInDays', 'type': 'int'}, - 'type_settings_recurrence_range_type': {'key': 'settings.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'settings.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'settings.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'settings.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_settings_recurrence_pattern_type': {'key': 'settings.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'settings.recurrence.pattern.interval', 'type': 'int'}, - 'principal_id': {'key': 'createdBy.principalId', 'type': 'str'}, - 'principal_type_created_by_principal_type': {'key': 'createdBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'createdBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'createdBy.userPrincipalName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewScheduleDefinitionProperties, self).__init__(**kwargs) - self.display_name = kwargs.get('display_name', None) - self.status = None - self.description_for_admins = kwargs.get('description_for_admins', None) - self.description_for_reviewers = kwargs.get('description_for_reviewers', None) - self.reviewers = kwargs.get('reviewers', None) - self.backup_reviewers = kwargs.get('backup_reviewers', None) - self.reviewers_type = None - self.instances = kwargs.get('instances', None) - self.resource_id = None - self.role_definition_id = None - self.principal_type_scope_principal_type = None - self.assignment_state = None - self.inactive_duration = kwargs.get('inactive_duration', None) - self.mail_notifications_enabled = kwargs.get('mail_notifications_enabled', None) - self.reminder_notifications_enabled = kwargs.get('reminder_notifications_enabled', None) - self.default_decision_enabled = kwargs.get('default_decision_enabled', None) - self.justification_required_on_approval = kwargs.get('justification_required_on_approval', None) - self.default_decision = kwargs.get('default_decision', None) - self.auto_apply_decisions_enabled = kwargs.get('auto_apply_decisions_enabled', None) - self.recommendations_enabled = kwargs.get('recommendations_enabled', None) - self.instance_duration_in_days = kwargs.get('instance_duration_in_days', None) - self.type_settings_recurrence_range_type = kwargs.get('type_settings_recurrence_range_type', None) - self.number_of_occurrences = kwargs.get('number_of_occurrences', None) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.type_settings_recurrence_pattern_type = kwargs.get('type_settings_recurrence_pattern_type', None) - self.interval = kwargs.get('interval', None) - self.principal_id = None - self.principal_type_created_by_principal_type = None - self.principal_name = None - self.user_principal_name = None - - -class AccessReviewScheduleSettings(msrest.serialization.Model): - """Settings of an Access Review. - - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the - review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to - reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a - justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to - pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to - automatically change the target object access resource, is enabled. If not enabled, a user - must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_recurrence_range_type: The recurrence range type. The possible values are: endDate, - noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_recurrence_range_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date - in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Possible - values include: "weekly", "absoluteMonthly". - :type type_recurrence_pattern_type: str or - ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int - """ - - _attribute_map = { - 'mail_notifications_enabled': {'key': 'mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'instanceDurationInDays', 'type': 'int'}, - 'type_recurrence_range_type': {'key': 'recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_recurrence_pattern_type': {'key': 'recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'recurrence.pattern.interval', 'type': 'int'}, - } - - def __init__( - self, - **kwargs - ): - super(AccessReviewScheduleSettings, self).__init__(**kwargs) - self.mail_notifications_enabled = kwargs.get('mail_notifications_enabled', None) - self.reminder_notifications_enabled = kwargs.get('reminder_notifications_enabled', None) - self.default_decision_enabled = kwargs.get('default_decision_enabled', None) - self.justification_required_on_approval = kwargs.get('justification_required_on_approval', None) - self.default_decision = kwargs.get('default_decision', None) - self.auto_apply_decisions_enabled = kwargs.get('auto_apply_decisions_enabled', None) - self.recommendations_enabled = kwargs.get('recommendations_enabled', None) - self.instance_duration_in_days = kwargs.get('instance_duration_in_days', None) - self.type_recurrence_range_type = kwargs.get('type_recurrence_range_type', None) - self.number_of_occurrences = kwargs.get('number_of_occurrences', None) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.type_recurrence_pattern_type = kwargs.get('type_recurrence_pattern_type', None) - self.interval = kwargs.get('interval', None) - - -class ErrorDefinition(msrest.serialization.Model): - """Error description and code explaining why an operation failed. - - :param error: Error of the list gateway status. - :type error: ~azure.mgmt.authorization.v2021_03_01_preview.models.ErrorDefinitionProperties - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinitionProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDefinition, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ErrorDefinitionProperties(msrest.serialization.Model): - """Error description and code explaining why an operation failed. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar message: Description of the error. - :vartype message: str - :param code: Error code of list gateway. - :type code: str - """ - - _validation = { - 'message': {'readonly': True}, - } - - _attribute_map = { - 'message': {'key': 'message', 'type': 'str'}, - 'code': {'key': 'code', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDefinitionProperties, self).__init__(**kwargs) - self.message = None - self.code = kwargs.get('code', None) - - -class Operation(msrest.serialization.Model): - """The definition of a Microsoft.Authorization operation. - - :param name: Name of the operation. - :type name: str - :param is_data_action: Indicates whether the operation is a data action. - :type is_data_action: bool - :param display: Display of the operation. - :type display: ~azure.mgmt.authorization.v2021_03_01_preview.models.OperationDisplay - :param origin: Origin of the operation. - :type origin: str - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'origin': {'key': 'origin', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Operation, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.is_data_action = kwargs.get('is_data_action', None) - self.display = kwargs.get('display', None) - self.origin = kwargs.get('origin', None) - - -class OperationDisplay(msrest.serialization.Model): - """The display information for a Microsoft.Authorization operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provider: The resource provider name: Microsoft.Authorization. - :vartype provider: str - :ivar resource: The resource on which the operation is performed. - :vartype resource: str - :ivar operation: The operation that users can perform. - :vartype operation: str - :ivar description: The description for the operation. - :vartype description: str - """ - - _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, - } - - _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None - self.description = None - - -class OperationListResult(msrest.serialization.Model): - """The result of a request to list Microsoft.Authorization operations. - - :param value: The collection value. - :type value: list[~azure.mgmt.authorization.v2021_03_01_preview.models.Operation] - :param next_link: The URI that can be used to request the next set of paged results. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_models_py3.py index 830c5a8f66d..cb7fc95c1ba 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_models_py3.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,15 +8,16 @@ # -------------------------------------------------------------------------- import datetime -from typing import List, Optional, Union +from typing import List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization -from ._authorization_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class AccessReviewDecision(msrest.serialization.Model): +class AccessReviewDecision(_serialization.Model): # pylint: disable=too-many-instance-attributes """Access Review. Variables are only populated by the server, and will be ignored when sending a request. @@ -26,21 +28,22 @@ class AccessReviewDecision(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :ivar recommendation: The feature- generated recommendation shown to the reviewer. Possible - values include: "Approve", "Deny", "NoInfoAvailable". + :ivar recommendation: The feature- generated recommendation shown to the reviewer. Known values + are: "Approve", "Deny", and "NoInfoAvailable". :vartype recommendation: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessRecommendationType - :param decision: The decision on the approval step. This value is initially set to NotReviewed. - Approvers can take action of Approve/Deny. Possible values include: "Approve", "Deny", - "NotReviewed", "DontKnow", "NotNotified". - :type decision: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str + :ivar decision: The decision on the approval step. This value is initially set to NotReviewed. + Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", "NotReviewed", + "DontKnow", and "NotNotified". + :vartype decision: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewResult + :ivar justification: Justification provided by approvers for their action. + :vartype justification: str :ivar reviewed_date_time: Date Time when a decision was taken. :vartype reviewed_date_time: ~datetime.datetime - :ivar apply_result: The outcome of applying the decision. Possible values include: "New", - "Applying", "AppliedSuccessfully", "AppliedWithUnknownFailure", - "AppliedSuccessfullyButObjectNotFound", "ApplyNotSupported". + :ivar apply_result: The outcome of applying the decision. Known values are: "New", "Applying", + "AppliedSuccessfully", "AppliedWithUnknownFailure", "AppliedSuccessfullyButObjectNotFound", and + "ApplyNotSupported". :vartype apply_result: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewApplyResult :ivar applied_date_time: The date and time when the review decision was applied. @@ -48,7 +51,7 @@ class AccessReviewDecision(msrest.serialization.Model): :ivar principal_id_properties_applied_by_principal_id: The identity id. :vartype principal_id_properties_applied_by_principal_id: str :ivar principal_type_properties_applied_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". + user/servicePrincipal. Known values are: "user" and "servicePrincipal". :vartype principal_type_properties_applied_by_principal_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType :ivar principal_name_properties_applied_by_principal_name: The identity display name. @@ -59,7 +62,7 @@ class AccessReviewDecision(msrest.serialization.Model): :ivar principal_id_properties_reviewed_by_principal_id: The identity id. :vartype principal_id_properties_reviewed_by_principal_id: str :ivar principal_type_properties_reviewed_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". + user/servicePrincipal. Known values are: "user" and "servicePrincipal". :vartype principal_type_properties_reviewed_by_principal_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType :ivar principal_name_properties_reviewed_by_principal_name: The identity display name. @@ -67,19 +70,17 @@ class AccessReviewDecision(msrest.serialization.Model): :ivar user_principal_name_properties_reviewed_by_user_principal_name: The user principal name(if valid). :vartype user_principal_name_properties_reviewed_by_user_principal_name: str - :param type_properties_resource_type: The type of resource.Constant filled by server. Possible - values include: "azureRole". - :type type_properties_resource_type: str or + :ivar type_properties_resource_type: The type of resource. "azureRole" + :vartype type_properties_resource_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionResourceType :ivar id_properties_resource_id: The id of resource associated with a decision record. :vartype id_properties_resource_id: str :ivar display_name_properties_resource_display_name: The display name of resource associated with a decision record. :vartype display_name_properties_resource_display_name: str - :param type_properties_principal_type: The type of decision target : - User/ServicePrincipal.Constant filled by server. Possible values include: "user", - "servicePrincipal". - :type type_properties_principal_type: str or + :ivar type_properties_principal_type: The type of decision target : User/ServicePrincipal. + Known values are: "user" and "servicePrincipal". + :vartype type_properties_principal_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType :ivar id_properties_principal_id: The id of principal whose access was reviewed. :vartype id_properties_principal_id: str @@ -89,61 +90,88 @@ class AccessReviewDecision(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'recommendation': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'apply_result': {'readonly': True}, - 'applied_date_time': {'readonly': True}, - 'principal_id_properties_applied_by_principal_id': {'readonly': True}, - 'principal_type_properties_applied_by_principal_type': {'readonly': True}, - 'principal_name_properties_applied_by_principal_name': {'readonly': True}, - 'user_principal_name_properties_applied_by_user_principal_name': {'readonly': True}, - 'principal_id_properties_reviewed_by_principal_id': {'readonly': True}, - 'principal_type_properties_reviewed_by_principal_type': {'readonly': True}, - 'principal_name_properties_reviewed_by_principal_name': {'readonly': True}, - 'user_principal_name_properties_reviewed_by_user_principal_name': {'readonly': True}, - 'id_properties_resource_id': {'readonly': True}, - 'display_name_properties_resource_display_name': {'readonly': True}, - 'id_properties_principal_id': {'readonly': True}, - 'display_name_properties_principal_display_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "recommendation": {"readonly": True}, + "reviewed_date_time": {"readonly": True}, + "apply_result": {"readonly": True}, + "applied_date_time": {"readonly": True}, + "principal_id_properties_applied_by_principal_id": {"readonly": True}, + "principal_type_properties_applied_by_principal_type": {"readonly": True}, + "principal_name_properties_applied_by_principal_name": {"readonly": True}, + "user_principal_name_properties_applied_by_user_principal_name": {"readonly": True}, + "principal_id_properties_reviewed_by_principal_id": {"readonly": True}, + "principal_type_properties_reviewed_by_principal_type": {"readonly": True}, + "principal_name_properties_reviewed_by_principal_name": {"readonly": True}, + "user_principal_name_properties_reviewed_by_user_principal_name": {"readonly": True}, + "id_properties_resource_id": {"readonly": True}, + "display_name_properties_resource_display_name": {"readonly": True}, + "id_properties_principal_id": {"readonly": True}, + "display_name_properties_principal_display_name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'recommendation': {'key': 'properties.recommendation', 'type': 'str'}, - 'decision': {'key': 'properties.decision', 'type': 'str'}, - 'justification': {'key': 'properties.justification', 'type': 'str'}, - 'reviewed_date_time': {'key': 'properties.reviewedDateTime', 'type': 'iso-8601'}, - 'apply_result': {'key': 'properties.applyResult', 'type': 'str'}, - 'applied_date_time': {'key': 'properties.appliedDateTime', 'type': 'iso-8601'}, - 'principal_id_properties_applied_by_principal_id': {'key': 'properties.appliedBy.principalId', 'type': 'str'}, - 'principal_type_properties_applied_by_principal_type': {'key': 'properties.appliedBy.principalType', 'type': 'str'}, - 'principal_name_properties_applied_by_principal_name': {'key': 'properties.appliedBy.principalName', 'type': 'str'}, - 'user_principal_name_properties_applied_by_user_principal_name': {'key': 'properties.appliedBy.userPrincipalName', 'type': 'str'}, - 'principal_id_properties_reviewed_by_principal_id': {'key': 'properties.reviewedBy.principalId', 'type': 'str'}, - 'principal_type_properties_reviewed_by_principal_type': {'key': 'properties.reviewedBy.principalType', 'type': 'str'}, - 'principal_name_properties_reviewed_by_principal_name': {'key': 'properties.reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name_properties_reviewed_by_user_principal_name': {'key': 'properties.reviewedBy.userPrincipalName', 'type': 'str'}, - 'type_properties_resource_type': {'key': 'properties.resource.type', 'type': 'str'}, - 'id_properties_resource_id': {'key': 'properties.resource.id', 'type': 'str'}, - 'display_name_properties_resource_display_name': {'key': 'properties.resource.displayName', 'type': 'str'}, - 'type_properties_principal_type': {'key': 'properties.principal.type', 'type': 'str'}, - 'id_properties_principal_id': {'key': 'properties.principal.id', 'type': 'str'}, - 'display_name_properties_principal_display_name': {'key': 'properties.principal.displayName', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "recommendation": {"key": "properties.recommendation", "type": "str"}, + "decision": {"key": "properties.decision", "type": "str"}, + "justification": {"key": "properties.justification", "type": "str"}, + "reviewed_date_time": {"key": "properties.reviewedDateTime", "type": "iso-8601"}, + "apply_result": {"key": "properties.applyResult", "type": "str"}, + "applied_date_time": {"key": "properties.appliedDateTime", "type": "iso-8601"}, + "principal_id_properties_applied_by_principal_id": {"key": "properties.appliedBy.principalId", "type": "str"}, + "principal_type_properties_applied_by_principal_type": { + "key": "properties.appliedBy.principalType", + "type": "str", + }, + "principal_name_properties_applied_by_principal_name": { + "key": "properties.appliedBy.principalName", + "type": "str", + }, + "user_principal_name_properties_applied_by_user_principal_name": { + "key": "properties.appliedBy.userPrincipalName", + "type": "str", + }, + "principal_id_properties_reviewed_by_principal_id": {"key": "properties.reviewedBy.principalId", "type": "str"}, + "principal_type_properties_reviewed_by_principal_type": { + "key": "properties.reviewedBy.principalType", + "type": "str", + }, + "principal_name_properties_reviewed_by_principal_name": { + "key": "properties.reviewedBy.principalName", + "type": "str", + }, + "user_principal_name_properties_reviewed_by_user_principal_name": { + "key": "properties.reviewedBy.userPrincipalName", + "type": "str", + }, + "type_properties_resource_type": {"key": "properties.resource.type", "type": "str"}, + "id_properties_resource_id": {"key": "properties.resource.id", "type": "str"}, + "display_name_properties_resource_display_name": {"key": "properties.resource.displayName", "type": "str"}, + "type_properties_principal_type": {"key": "properties.principal.type", "type": "str"}, + "id_properties_principal_id": {"key": "properties.principal.id", "type": "str"}, + "display_name_properties_principal_display_name": {"key": "properties.principal.displayName", "type": "str"}, } def __init__( self, *, - decision: Optional[Union[str, "AccessReviewResult"]] = None, + decision: Optional[Union[str, "_models.AccessReviewResult"]] = None, justification: Optional[str] = None, **kwargs ): - super(AccessReviewDecision, self).__init__(**kwargs) + """ + :keyword decision: The decision on the approval step. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + "NotReviewed", "DontKnow", and "NotNotified". + :paramtype decision: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewResult + :keyword justification: Justification provided by approvers for their action. + :paramtype justification: str + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -169,19 +197,19 @@ def __init__( self.display_name_properties_principal_display_name = None -class AccessReviewDecisionIdentity(msrest.serialization.Model): +class AccessReviewDecisionIdentity(_serialization.Model): """Target of the decision. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: AccessReviewDecisionServicePrincipalIdentity, AccessReviewDecisionUserIdentity. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AccessReviewDecisionServicePrincipalIdentity, AccessReviewDecisionUserIdentity Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType :ivar id: The id of principal whose access was reviewed. :vartype id: str :ivar display_name: The display name of the user whose access was reviewed. @@ -189,77 +217,82 @@ class AccessReviewDecisionIdentity(msrest.serialization.Model): """ _validation = { - 'type': {'required': True}, - 'id': {'readonly': True}, - 'display_name': {'readonly': True}, + "type": {"required": True}, + "id": {"readonly": True}, + "display_name": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, } _subtype_map = { - 'type': {'servicePrincipal': 'AccessReviewDecisionServicePrincipalIdentity', 'user': 'AccessReviewDecisionUserIdentity'} + "type": { + "servicePrincipal": "AccessReviewDecisionServicePrincipalIdentity", + "user": "AccessReviewDecisionUserIdentity", + } } - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionIdentity, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None # type: Optional[str] self.id = None self.display_name = None -class AccessReviewDecisionListResult(msrest.serialization.Model): +class AccessReviewDecisionListResult(_serialization.Model): """List of access review decisions. - :param value: Access Review Decision list. - :type value: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Access Review Decision list. + :vartype value: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewDecision]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[AccessReviewDecision]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["AccessReviewDecision"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.AccessReviewDecision"]] = None, next_link: Optional[str] = None, **kwargs ): - super(AccessReviewDecisionListResult, self).__init__(**kwargs) + """ + :keyword value: Access Review Decision list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class AccessReviewDecisionProperties(msrest.serialization.Model): +class AccessReviewDecisionProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes """Approval Step. Variables are only populated by the server, and will be ignored when sending a request. - :ivar recommendation: The feature- generated recommendation shown to the reviewer. Possible - values include: "Approve", "Deny", "NoInfoAvailable". + :ivar recommendation: The feature- generated recommendation shown to the reviewer. Known values + are: "Approve", "Deny", and "NoInfoAvailable". :vartype recommendation: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessRecommendationType - :param decision: The decision on the approval step. This value is initially set to NotReviewed. - Approvers can take action of Approve/Deny. Possible values include: "Approve", "Deny", - "NotReviewed", "DontKnow", "NotNotified". - :type decision: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewResult - :param justification: Justification provided by approvers for their action. - :type justification: str + :ivar decision: The decision on the approval step. This value is initially set to NotReviewed. + Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", "NotReviewed", + "DontKnow", and "NotNotified". + :vartype decision: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewResult + :ivar justification: Justification provided by approvers for their action. + :vartype justification: str :ivar reviewed_date_time: Date Time when a decision was taken. :vartype reviewed_date_time: ~datetime.datetime - :ivar apply_result: The outcome of applying the decision. Possible values include: "New", - "Applying", "AppliedSuccessfully", "AppliedWithUnknownFailure", - "AppliedSuccessfullyButObjectNotFound", "ApplyNotSupported". + :ivar apply_result: The outcome of applying the decision. Known values are: "New", "Applying", + "AppliedSuccessfully", "AppliedWithUnknownFailure", "AppliedSuccessfullyButObjectNotFound", and + "ApplyNotSupported". :vartype apply_result: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewApplyResult :ivar applied_date_time: The date and time when the review decision was applied. @@ -267,7 +300,7 @@ class AccessReviewDecisionProperties(msrest.serialization.Model): :ivar principal_id_applied_by_principal_id: The identity id. :vartype principal_id_applied_by_principal_id: str :ivar principal_type_applied_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". + Known values are: "user" and "servicePrincipal". :vartype principal_type_applied_by_principal_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType :ivar principal_name_applied_by_principal_name: The identity display name. @@ -277,25 +310,24 @@ class AccessReviewDecisionProperties(msrest.serialization.Model): :ivar principal_id_reviewed_by_principal_id: The identity id. :vartype principal_id_reviewed_by_principal_id: str :ivar principal_type_reviewed_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". + Known values are: "user" and "servicePrincipal". :vartype principal_type_reviewed_by_principal_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType :ivar principal_name_reviewed_by_principal_name: The identity display name. :vartype principal_name_reviewed_by_principal_name: str :ivar user_principal_name_reviewed_by_user_principal_name: The user principal name(if valid). :vartype user_principal_name_reviewed_by_user_principal_name: str - :param type_resource_type: The type of resource.Constant filled by server. Possible values - include: "azureRole". - :type type_resource_type: str or + :ivar type_resource_type: The type of resource. "azureRole" + :vartype type_resource_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionResourceType :ivar id_resource_id: The id of resource associated with a decision record. :vartype id_resource_id: str :ivar display_name_resource_display_name: The display name of resource associated with a decision record. :vartype display_name_resource_display_name: str - :param type_principal_type: The type of decision target : User/ServicePrincipal.Constant filled - by server. Possible values include: "user", "servicePrincipal". - :type type_principal_type: str or + :ivar type_principal_type: The type of decision target : User/ServicePrincipal. Known values + are: "user" and "servicePrincipal". + :vartype type_principal_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType :ivar id_principal_id: The id of principal whose access was reviewed. :vartype id_principal_id: str @@ -305,55 +337,64 @@ class AccessReviewDecisionProperties(msrest.serialization.Model): """ _validation = { - 'recommendation': {'readonly': True}, - 'reviewed_date_time': {'readonly': True}, - 'apply_result': {'readonly': True}, - 'applied_date_time': {'readonly': True}, - 'principal_id_applied_by_principal_id': {'readonly': True}, - 'principal_type_applied_by_principal_type': {'readonly': True}, - 'principal_name_applied_by_principal_name': {'readonly': True}, - 'user_principal_name_applied_by_user_principal_name': {'readonly': True}, - 'principal_id_reviewed_by_principal_id': {'readonly': True}, - 'principal_type_reviewed_by_principal_type': {'readonly': True}, - 'principal_name_reviewed_by_principal_name': {'readonly': True}, - 'user_principal_name_reviewed_by_user_principal_name': {'readonly': True}, - 'id_resource_id': {'readonly': True}, - 'display_name_resource_display_name': {'readonly': True}, - 'id_principal_id': {'readonly': True}, - 'display_name_principal_display_name': {'readonly': True}, + "recommendation": {"readonly": True}, + "reviewed_date_time": {"readonly": True}, + "apply_result": {"readonly": True}, + "applied_date_time": {"readonly": True}, + "principal_id_applied_by_principal_id": {"readonly": True}, + "principal_type_applied_by_principal_type": {"readonly": True}, + "principal_name_applied_by_principal_name": {"readonly": True}, + "user_principal_name_applied_by_user_principal_name": {"readonly": True}, + "principal_id_reviewed_by_principal_id": {"readonly": True}, + "principal_type_reviewed_by_principal_type": {"readonly": True}, + "principal_name_reviewed_by_principal_name": {"readonly": True}, + "user_principal_name_reviewed_by_user_principal_name": {"readonly": True}, + "id_resource_id": {"readonly": True}, + "display_name_resource_display_name": {"readonly": True}, + "id_principal_id": {"readonly": True}, + "display_name_principal_display_name": {"readonly": True}, } _attribute_map = { - 'recommendation': {'key': 'recommendation', 'type': 'str'}, - 'decision': {'key': 'decision', 'type': 'str'}, - 'justification': {'key': 'justification', 'type': 'str'}, - 'reviewed_date_time': {'key': 'reviewedDateTime', 'type': 'iso-8601'}, - 'apply_result': {'key': 'applyResult', 'type': 'str'}, - 'applied_date_time': {'key': 'appliedDateTime', 'type': 'iso-8601'}, - 'principal_id_applied_by_principal_id': {'key': 'appliedBy.principalId', 'type': 'str'}, - 'principal_type_applied_by_principal_type': {'key': 'appliedBy.principalType', 'type': 'str'}, - 'principal_name_applied_by_principal_name': {'key': 'appliedBy.principalName', 'type': 'str'}, - 'user_principal_name_applied_by_user_principal_name': {'key': 'appliedBy.userPrincipalName', 'type': 'str'}, - 'principal_id_reviewed_by_principal_id': {'key': 'reviewedBy.principalId', 'type': 'str'}, - 'principal_type_reviewed_by_principal_type': {'key': 'reviewedBy.principalType', 'type': 'str'}, - 'principal_name_reviewed_by_principal_name': {'key': 'reviewedBy.principalName', 'type': 'str'}, - 'user_principal_name_reviewed_by_user_principal_name': {'key': 'reviewedBy.userPrincipalName', 'type': 'str'}, - 'type_resource_type': {'key': 'resource.type', 'type': 'str'}, - 'id_resource_id': {'key': 'resource.id', 'type': 'str'}, - 'display_name_resource_display_name': {'key': 'resource.displayName', 'type': 'str'}, - 'type_principal_type': {'key': 'principal.type', 'type': 'str'}, - 'id_principal_id': {'key': 'principal.id', 'type': 'str'}, - 'display_name_principal_display_name': {'key': 'principal.displayName', 'type': 'str'}, + "recommendation": {"key": "recommendation", "type": "str"}, + "decision": {"key": "decision", "type": "str"}, + "justification": {"key": "justification", "type": "str"}, + "reviewed_date_time": {"key": "reviewedDateTime", "type": "iso-8601"}, + "apply_result": {"key": "applyResult", "type": "str"}, + "applied_date_time": {"key": "appliedDateTime", "type": "iso-8601"}, + "principal_id_applied_by_principal_id": {"key": "appliedBy.principalId", "type": "str"}, + "principal_type_applied_by_principal_type": {"key": "appliedBy.principalType", "type": "str"}, + "principal_name_applied_by_principal_name": {"key": "appliedBy.principalName", "type": "str"}, + "user_principal_name_applied_by_user_principal_name": {"key": "appliedBy.userPrincipalName", "type": "str"}, + "principal_id_reviewed_by_principal_id": {"key": "reviewedBy.principalId", "type": "str"}, + "principal_type_reviewed_by_principal_type": {"key": "reviewedBy.principalType", "type": "str"}, + "principal_name_reviewed_by_principal_name": {"key": "reviewedBy.principalName", "type": "str"}, + "user_principal_name_reviewed_by_user_principal_name": {"key": "reviewedBy.userPrincipalName", "type": "str"}, + "type_resource_type": {"key": "resource.type", "type": "str"}, + "id_resource_id": {"key": "resource.id", "type": "str"}, + "display_name_resource_display_name": {"key": "resource.displayName", "type": "str"}, + "type_principal_type": {"key": "principal.type", "type": "str"}, + "id_principal_id": {"key": "principal.id", "type": "str"}, + "display_name_principal_display_name": {"key": "principal.displayName", "type": "str"}, } def __init__( self, *, - decision: Optional[Union[str, "AccessReviewResult"]] = None, + decision: Optional[Union[str, "_models.AccessReviewResult"]] = None, justification: Optional[str] = None, **kwargs ): - super(AccessReviewDecisionProperties, self).__init__(**kwargs) + """ + :keyword decision: The decision on the approval step. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + "NotReviewed", "DontKnow", and "NotNotified". + :paramtype decision: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewResult + :keyword justification: Justification provided by approvers for their action. + :paramtype justification: str + """ + super().__init__(**kwargs) self.recommendation = None self.decision = decision self.justification = justification @@ -376,19 +417,15 @@ def __init__( self.display_name_principal_display_name = None -class AccessReviewDecisionResource(msrest.serialization.Model): +class AccessReviewDecisionResource(_serialization.Model): """Target of the decision. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: . - Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :param type: Required. The type of resource.Constant filled by server. Possible values - include: "azureRole". - :type type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionResourceType + :ivar type: The type of resource. Required. "azureRole" + :vartype type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionResourceType :ivar id: The id of resource associated with a decision record. :vartype id: str :ivar display_name: The display name of resource associated with a decision record. @@ -396,26 +433,20 @@ class AccessReviewDecisionResource(msrest.serialization.Model): """ _validation = { - 'type': {'required': True}, - 'id': {'readonly': True}, - 'display_name': {'readonly': True}, + "type": {"required": True}, + "id": {"readonly": True}, + "display_name": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - } - - _subtype_map = { - 'type': {} + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionResource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None # type: Optional[str] self.id = None self.display_name = None @@ -428,9 +459,9 @@ class AccessReviewDecisionServicePrincipalIdentity(AccessReviewDecisionIdentity) All required parameters must be populated in order to send to Azure. - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType :ivar id: The id of principal whose access was reviewed. :vartype id: str :ivar display_name: The display name of the user whose access was reviewed. @@ -440,25 +471,23 @@ class AccessReviewDecisionServicePrincipalIdentity(AccessReviewDecisionIdentity) """ _validation = { - 'type': {'required': True}, - 'id': {'readonly': True}, - 'display_name': {'readonly': True}, - 'app_id': {'readonly': True}, + "type": {"required": True}, + "id": {"readonly": True}, + "display_name": {"readonly": True}, + "app_id": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'app_id': {'key': 'appId', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "app_id": {"key": "appId", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionServicePrincipalIdentity, self).__init__(**kwargs) - self.type = 'servicePrincipal' # type: str + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = "servicePrincipal" # type: str self.app_id = None @@ -469,9 +498,9 @@ class AccessReviewDecisionUserIdentity(AccessReviewDecisionIdentity): All required parameters must be populated in order to send to Azure. - :param type: Required. The type of decision target : User/ServicePrincipal.Constant filled by - server. Possible values include: "user", "servicePrincipal". - :type type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DecisionTargetType :ivar id: The id of principal whose access was reviewed. :vartype id: str :ivar display_name: The display name of the user whose access was reviewed. @@ -481,29 +510,27 @@ class AccessReviewDecisionUserIdentity(AccessReviewDecisionIdentity): """ _validation = { - 'type': {'required': True}, - 'id': {'readonly': True}, - 'display_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, + "type": {"required": True}, + "id": {"readonly": True}, + "display_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'user_principal_name': {'key': 'userPrincipalName', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "user_principal_name": {"key": "userPrincipalName", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(AccessReviewDecisionUserIdentity, self).__init__(**kwargs) - self.type = 'user' # type: str + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = "user" # type: str self.user_principal_name = None -class AccessReviewDefaultSettings(msrest.serialization.Model): +class AccessReviewDefaultSettings(_serialization.Model): # pylint: disable=too-many-instance-attributes """Access Review Default Settings. Variables are only populated by the server, and will be ignored when sending a request. @@ -515,76 +542,76 @@ class AccessReviewDefaultSettings(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to automatically change the target object access resource, is enabled. If not enabled, a user must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_properties_recurrence_range_type: The recurrence range type. The possible values - are: endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_properties_recurrence_range_type: str or + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_properties_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_properties_recurrence_range_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. - Possible values include: "weekly", "absoluteMonthly". - :type type_properties_recurrence_pattern_type: str or + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :vartype type_properties_recurrence_pattern_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'mail_notifications_enabled': {'key': 'properties.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'properties.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'properties.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'properties.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'properties.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'properties.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'properties.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'properties.instanceDurationInDays', 'type': 'int'}, - 'type_properties_recurrence_range_type': {'key': 'properties.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'properties.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'properties.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_properties_recurrence_pattern_type': {'key': 'properties.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'properties.recurrence.pattern.interval', 'type': 'int'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "mail_notifications_enabled": {"key": "properties.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "properties.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "properties.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "properties.justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "properties.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "properties.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "properties.recommendationsEnabled", "type": "bool"}, + "instance_duration_in_days": {"key": "properties.instanceDurationInDays", "type": "int"}, + "type_properties_recurrence_range_type": {"key": "properties.recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "properties.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "properties.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.recurrence.range.endDate", "type": "iso-8601"}, + "type_properties_recurrence_pattern_type": {"key": "properties.recurrence.pattern.type", "type": "str"}, + "interval": {"key": "properties.recurrence.pattern.interval", "type": "int"}, } def __init__( @@ -594,19 +621,68 @@ def __init__( reminder_notifications_enabled: Optional[bool] = None, default_decision_enabled: Optional[bool] = None, justification_required_on_approval: Optional[bool] = None, - default_decision: Optional[Union[str, "DefaultDecisionType"]] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, auto_apply_decisions_enabled: Optional[bool] = None, recommendations_enabled: Optional[bool] = None, instance_duration_in_days: Optional[int] = None, - type_properties_recurrence_range_type: Optional[Union[str, "AccessReviewRecurrenceRangeType"]] = None, + type_properties_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, number_of_occurrences: Optional[int] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, - type_properties_recurrence_pattern_type: Optional[Union[str, "AccessReviewRecurrencePatternType"]] = None, + type_properties_recurrence_pattern_type: Optional[ + Union[str, "_models.AccessReviewRecurrencePatternType"] + ] = None, interval: Optional[int] = None, **kwargs ): - super(AccessReviewDefaultSettings, self).__init__(**kwargs) + """ + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_properties_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_properties_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :paramtype type_properties_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -626,7 +702,7 @@ def __init__( self.interval = interval -class AccessReviewInstance(msrest.serialization.Model): +class AccessReviewInstance(_serialization.Model): """Access Review Instance. Variables are only populated by the server, and will be ignored when sending a request. @@ -637,31 +713,31 @@ class AccessReviewInstance(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :ivar status: This read-only field specifies the status of an access review instance. Possible - values include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". + :ivar status: This read-only field specifies the status of an access review instance. Known + values are: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", + "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". :vartype status: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstanceStatus - :param start_date_time: The DateTime when the review instance is scheduled to be start. - :type start_date_time: ~datetime.datetime - :param end_date_time: The DateTime when the review instance is scheduled to end. - :type end_date_time: ~datetime.datetime + :ivar start_date_time: The DateTime when the review instance is scheduled to be start. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: The DateTime when the review instance is scheduled to end. + :vartype end_date_time: ~datetime.datetime """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'status': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "status": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date_time': {'key': 'properties.startDateTime', 'type': 'iso-8601'}, - 'end_date_time': {'key': 'properties.endDateTime', 'type': 'iso-8601'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, } def __init__( @@ -671,7 +747,13 @@ def __init__( end_date_time: Optional[datetime.datetime] = None, **kwargs ): - super(AccessReviewInstance, self).__init__(**kwargs) + """ + :keyword start_date_time: The DateTime when the review instance is scheduled to be start. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: The DateTime when the review instance is scheduled to end. + :paramtype end_date_time: ~datetime.datetime + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -680,66 +762,68 @@ def __init__( self.end_date_time = end_date_time -class AccessReviewInstanceListResult(msrest.serialization.Model): +class AccessReviewInstanceListResult(_serialization.Model): """List of Access Review Instances. - :param value: Access Review Instance list. - :type value: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar value: Access Review Instance list. + :vartype value: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewInstance]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[AccessReviewInstance]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["AccessReviewInstance"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.AccessReviewInstance"]] = None, next_link: Optional[str] = None, **kwargs ): - super(AccessReviewInstanceListResult, self).__init__(**kwargs) + """ + :keyword value: Access Review Instance list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class AccessReviewReviewer(msrest.serialization.Model): +class AccessReviewReviewer(_serialization.Model): """Descriptor for what needs to be reviewed. Variables are only populated by the server, and will be ignored when sending a request. - :param principal_id: The id of the reviewer(user/servicePrincipal). - :type principal_id: str - :ivar principal_type: The identity type : user/servicePrincipal. Possible values include: - "user", "servicePrincipal". + :ivar principal_id: The id of the reviewer(user/servicePrincipal). + :vartype principal_id: str + :ivar principal_type: The identity type : user/servicePrincipal. Known values are: "user" and + "servicePrincipal". :vartype principal_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewerType """ _validation = { - 'principal_type': {'readonly': True}, + "principal_type": {"readonly": True}, } _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'principal_type': {'key': 'principalType', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "principal_type": {"key": "principalType", "type": "str"}, } - def __init__( - self, - *, - principal_id: Optional[str] = None, - **kwargs - ): - super(AccessReviewReviewer, self).__init__(**kwargs) + def __init__(self, *, principal_id: Optional[str] = None, **kwargs): + """ + :keyword principal_id: The id of the reviewer(user/servicePrincipal). + :paramtype principal_id: str + """ + super().__init__(**kwargs) self.principal_id = principal_id self.principal_type = None -class AccessReviewScheduleDefinition(msrest.serialization.Model): +class AccessReviewScheduleDefinition(_serialization.Model): # pylint: disable=too-many-instance-attributes """Access Review Schedule Definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -750,99 +834,99 @@ class AccessReviewScheduleDefinition(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :param display_name: The display name for the schedule definition. - :type display_name: str - :ivar status: This read-only field specifies the status of an accessReview. Possible values - include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". + :ivar display_name: The display name for the schedule definition. + :vartype display_name: str + :ivar status: This read-only field specifies the status of an accessReview. Known values are: + "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", "Completing", + "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". :vartype status: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionStatus - :param description_for_admins: The description provided by the access review creator and - visible to admins. - :type description_for_admins: str - :param description_for_reviewers: The description provided by the access review creator to be + :ivar description_for_admins: The description provided by the access review creator and visible + to admins. + :vartype description_for_admins: str + :ivar description_for_reviewers: The description provided by the access review creator to be shown to reviewers. - :type description_for_reviewers: str - :param reviewers: This is the collection of reviewers. - :type reviewers: + :vartype description_for_reviewers: str + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] - :param backup_reviewers: This is the collection of backup reviewers. - :type backup_reviewers: + :ivar backup_reviewers: This is the collection of backup reviewers. + :vartype backup_reviewers: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be - assigned and instead be chosen dynamically. For example managers review or self review. - Possible values include: "Assigned", "Self", "Managers". + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". :vartype reviewers_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionReviewersType - :param instances: This is the collection of instances returned when one does an expand on it. - :type instances: + :ivar instances: This is the collection of instances returned when one does an expand on it. + :vartype instances: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] :ivar resource_id: ResourceId in which this review is getting created. :vartype resource_id: str :ivar role_definition_id: This is used to indicate the role being reviewed. :vartype role_definition_id: str :ivar principal_type_properties_scope_principal_type: The identity type user/servicePrincipal - to review. Possible values include: "user", "guestUser", "servicePrincipal". + to review. Known values are: "user", "guestUser", and "servicePrincipal". :vartype principal_type_properties_scope_principal_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScopePrincipalType - :ivar assignment_state: The role assignment state eligible/active to review. Possible values - include: "eligible", "active". + :ivar assignment_state: The role assignment state eligible/active to review. Known values are: + "eligible" and "active". :vartype assignment_state: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScopeAssignmentState - :param inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + :ivar inactive_duration: Duration users are inactive for. The value should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, seconds)). - :type inactive_duration: ~datetime.timedelta - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + :vartype inactive_duration: ~datetime.timedelta + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to automatically change the target object access resource, is enabled. If not enabled, a user must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_properties_settings_recurrence_range_type: The recurrence range type. The possible - values are: endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_properties_settings_recurrence_range_type: str or + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_properties_settings_recurrence_range_type: The recurrence range type. The possible + values are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_properties_settings_recurrence_range_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, - etc. Possible values include: "weekly", "absoluteMonthly". - :type type_properties_settings_recurrence_pattern_type: str or + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, + etc. Known values are: "weekly" and "absoluteMonthly". + :vartype type_properties_settings_recurrence_pattern_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int :ivar principal_id: The identity id. :vartype principal_id: str :ivar principal_type_properties_created_by_principal_type: The identity type : - user/servicePrincipal. Possible values include: "user", "servicePrincipal". + user/servicePrincipal. Known values are: "user" and "servicePrincipal". :vartype principal_type_properties_created_by_principal_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType :ivar principal_name: The identity display name. @@ -852,85 +936,171 @@ class AccessReviewScheduleDefinition(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'status': {'readonly': True}, - 'reviewers_type': {'readonly': True}, - 'resource_id': {'readonly': True}, - 'role_definition_id': {'readonly': True}, - 'principal_type_properties_scope_principal_type': {'readonly': True}, - 'assignment_state': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type_properties_created_by_principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + "resource_id": {"readonly": True}, + "role_definition_id": {"readonly": True}, + "principal_type_properties_scope_principal_type": {"readonly": True}, + "assignment_state": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type_properties_created_by_principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'description_for_admins': {'key': 'properties.descriptionForAdmins', 'type': 'str'}, - 'description_for_reviewers': {'key': 'properties.descriptionForReviewers', 'type': 'str'}, - 'reviewers': {'key': 'properties.reviewers', 'type': '[AccessReviewReviewer]'}, - 'backup_reviewers': {'key': 'properties.backupReviewers', 'type': '[AccessReviewReviewer]'}, - 'reviewers_type': {'key': 'properties.reviewersType', 'type': 'str'}, - 'instances': {'key': 'properties.instances', 'type': '[AccessReviewInstance]'}, - 'resource_id': {'key': 'properties.scope.resourceId', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.scope.roleDefinitionId', 'type': 'str'}, - 'principal_type_properties_scope_principal_type': {'key': 'properties.scope.principalType', 'type': 'str'}, - 'assignment_state': {'key': 'properties.scope.assignmentState', 'type': 'str'}, - 'inactive_duration': {'key': 'properties.scope.inactiveDuration', 'type': 'duration'}, - 'mail_notifications_enabled': {'key': 'properties.settings.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'properties.settings.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'properties.settings.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'properties.settings.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'properties.settings.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'properties.settings.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'properties.settings.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'properties.settings.instanceDurationInDays', 'type': 'int'}, - 'type_properties_settings_recurrence_range_type': {'key': 'properties.settings.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'properties.settings.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'properties.settings.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.settings.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_properties_settings_recurrence_pattern_type': {'key': 'properties.settings.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'properties.settings.recurrence.pattern.interval', 'type': 'int'}, - 'principal_id': {'key': 'properties.createdBy.principalId', 'type': 'str'}, - 'principal_type_properties_created_by_principal_type': {'key': 'properties.createdBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'properties.createdBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'properties.createdBy.userPrincipalName', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "description_for_admins": {"key": "properties.descriptionForAdmins", "type": "str"}, + "description_for_reviewers": {"key": "properties.descriptionForReviewers", "type": "str"}, + "reviewers": {"key": "properties.reviewers", "type": "[AccessReviewReviewer]"}, + "backup_reviewers": {"key": "properties.backupReviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "properties.reviewersType", "type": "str"}, + "instances": {"key": "properties.instances", "type": "[AccessReviewInstance]"}, + "resource_id": {"key": "properties.scope.resourceId", "type": "str"}, + "role_definition_id": {"key": "properties.scope.roleDefinitionId", "type": "str"}, + "principal_type_properties_scope_principal_type": {"key": "properties.scope.principalType", "type": "str"}, + "assignment_state": {"key": "properties.scope.assignmentState", "type": "str"}, + "inactive_duration": {"key": "properties.scope.inactiveDuration", "type": "duration"}, + "mail_notifications_enabled": {"key": "properties.settings.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "properties.settings.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "properties.settings.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": { + "key": "properties.settings.justificationRequiredOnApproval", + "type": "bool", + }, + "default_decision": {"key": "properties.settings.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "properties.settings.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "properties.settings.recommendationsEnabled", "type": "bool"}, + "instance_duration_in_days": {"key": "properties.settings.instanceDurationInDays", "type": "int"}, + "type_properties_settings_recurrence_range_type": { + "key": "properties.settings.recurrence.range.type", + "type": "str", + }, + "number_of_occurrences": {"key": "properties.settings.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "properties.settings.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.settings.recurrence.range.endDate", "type": "iso-8601"}, + "type_properties_settings_recurrence_pattern_type": { + "key": "properties.settings.recurrence.pattern.type", + "type": "str", + }, + "interval": {"key": "properties.settings.recurrence.pattern.interval", "type": "int"}, + "principal_id": {"key": "properties.createdBy.principalId", "type": "str"}, + "principal_type_properties_created_by_principal_type": { + "key": "properties.createdBy.principalType", + "type": "str", + }, + "principal_name": {"key": "properties.createdBy.principalName", "type": "str"}, + "user_principal_name": {"key": "properties.createdBy.userPrincipalName", "type": "str"}, } - def __init__( + def __init__( # pylint: disable=too-many-locals self, *, display_name: Optional[str] = None, description_for_admins: Optional[str] = None, description_for_reviewers: Optional[str] = None, - reviewers: Optional[List["AccessReviewReviewer"]] = None, - backup_reviewers: Optional[List["AccessReviewReviewer"]] = None, - instances: Optional[List["AccessReviewInstance"]] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + backup_reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + instances: Optional[List["_models.AccessReviewInstance"]] = None, inactive_duration: Optional[datetime.timedelta] = None, mail_notifications_enabled: Optional[bool] = None, reminder_notifications_enabled: Optional[bool] = None, default_decision_enabled: Optional[bool] = None, justification_required_on_approval: Optional[bool] = None, - default_decision: Optional[Union[str, "DefaultDecisionType"]] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, auto_apply_decisions_enabled: Optional[bool] = None, recommendations_enabled: Optional[bool] = None, instance_duration_in_days: Optional[int] = None, - type_properties_settings_recurrence_range_type: Optional[Union[str, "AccessReviewRecurrenceRangeType"]] = None, + type_properties_settings_recurrence_range_type: Optional[ + Union[str, "_models.AccessReviewRecurrenceRangeType"] + ] = None, number_of_occurrences: Optional[int] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, - type_properties_settings_recurrence_pattern_type: Optional[Union[str, "AccessReviewRecurrencePatternType"]] = None, + type_properties_settings_recurrence_pattern_type: Optional[ + Union[str, "_models.AccessReviewRecurrencePatternType"] + ] = None, interval: Optional[int] = None, **kwargs ): - super(AccessReviewScheduleDefinition, self).__init__(**kwargs) + """ + :keyword display_name: The display name for the schedule definition. + :paramtype display_name: str + :keyword description_for_admins: The description provided by the access review creator and + visible to admins. + :paramtype description_for_admins: str + :keyword description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :paramtype description_for_reviewers: str + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] + :keyword backup_reviewers: This is the collection of backup reviewers. + :paramtype backup_reviewers: + list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] + :keyword instances: This is the collection of instances returned when one does an expand on it. + :paramtype instances: + list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] + :keyword inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :paramtype inactive_duration: ~datetime.timedelta + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_properties_settings_recurrence_range_type: The recurrence range type. The + possible values are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and + "numbered". + :paramtype type_properties_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, + monthly, etc. Known values are: "weekly" and "absoluteMonthly". + :paramtype type_properties_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -967,131 +1137,138 @@ def __init__( self.user_principal_name = None -class AccessReviewScheduleDefinitionListResult(msrest.serialization.Model): +class AccessReviewScheduleDefinitionListResult(_serialization.Model): """List of Access Review Schedule Definitions. - :param value: Access Review Schedule Definition list. - :type value: + :ivar value: Access Review Schedule Definition list. + :vartype value: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition] - :param next_link: The URL to use for getting the next set of results. - :type next_link: str + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[AccessReviewScheduleDefinition]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[AccessReviewScheduleDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["AccessReviewScheduleDefinition"]] = None, + value: Optional[List["_models.AccessReviewScheduleDefinition"]] = None, next_link: Optional[str] = None, **kwargs ): - super(AccessReviewScheduleDefinitionListResult, self).__init__(**kwargs) + """ + :keyword value: Access Review Schedule Definition list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class AccessReviewScheduleDefinitionProperties(msrest.serialization.Model): +class AccessReviewScheduleDefinitionProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes """Access Review. Variables are only populated by the server, and will be ignored when sending a request. - :param display_name: The display name for the schedule definition. - :type display_name: str - :ivar status: This read-only field specifies the status of an accessReview. Possible values - include: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", - "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", "Starting". + :ivar display_name: The display name for the schedule definition. + :vartype display_name: str + :ivar status: This read-only field specifies the status of an accessReview. Known values are: + "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", "Completing", + "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". :vartype status: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionStatus - :param description_for_admins: The description provided by the access review creator and - visible to admins. - :type description_for_admins: str - :param description_for_reviewers: The description provided by the access review creator to be + :ivar description_for_admins: The description provided by the access review creator and visible + to admins. + :vartype description_for_admins: str + :ivar description_for_reviewers: The description provided by the access review creator to be shown to reviewers. - :type description_for_reviewers: str - :param reviewers: This is the collection of reviewers. - :type reviewers: + :vartype description_for_reviewers: str + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] - :param backup_reviewers: This is the collection of backup reviewers. - :type backup_reviewers: + :ivar backup_reviewers: This is the collection of backup reviewers. + :vartype backup_reviewers: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be - assigned and instead be chosen dynamically. For example managers review or self review. - Possible values include: "Assigned", "Self", "Managers". + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". :vartype reviewers_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionReviewersType - :param instances: This is the collection of instances returned when one does an expand on it. - :type instances: + :ivar instances: This is the collection of instances returned when one does an expand on it. + :vartype instances: list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] :ivar resource_id: ResourceId in which this review is getting created. :vartype resource_id: str :ivar role_definition_id: This is used to indicate the role being reviewed. :vartype role_definition_id: str :ivar principal_type_scope_principal_type: The identity type user/servicePrincipal to review. - Possible values include: "user", "guestUser", "servicePrincipal". + Known values are: "user", "guestUser", and "servicePrincipal". :vartype principal_type_scope_principal_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScopePrincipalType - :ivar assignment_state: The role assignment state eligible/active to review. Possible values - include: "eligible", "active". + :ivar assignment_state: The role assignment state eligible/active to review. Known values are: + "eligible" and "active". :vartype assignment_state: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScopeAssignmentState - :param inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + :ivar inactive_duration: Duration users are inactive for. The value should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, seconds)). - :type inactive_duration: ~datetime.timedelta - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + :vartype inactive_duration: ~datetime.timedelta + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to automatically change the target object access resource, is enabled. If not enabled, a user must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_settings_recurrence_range_type: The recurrence range type. The possible values are: - endDate, noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_settings_recurrence_range_type: str or + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_settings_recurrence_range_type: The recurrence range type. The possible values are: + endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_settings_recurrence_range_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. - Possible values include: "weekly", "absoluteMonthly". - :type type_settings_recurrence_pattern_type: str or + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known + values are: "weekly" and "absoluteMonthly". + :vartype type_settings_recurrence_pattern_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int :ivar principal_id: The identity id. :vartype principal_id: str :ivar principal_type_created_by_principal_type: The identity type : user/servicePrincipal. - Possible values include: "user", "servicePrincipal". + Known values are: "user" and "servicePrincipal". :vartype principal_type_created_by_principal_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewActorIdentityType :ivar principal_name: The identity display name. @@ -1101,79 +1278,148 @@ class AccessReviewScheduleDefinitionProperties(msrest.serialization.Model): """ _validation = { - 'status': {'readonly': True}, - 'reviewers_type': {'readonly': True}, - 'resource_id': {'readonly': True}, - 'role_definition_id': {'readonly': True}, - 'principal_type_scope_principal_type': {'readonly': True}, - 'assignment_state': {'readonly': True}, - 'principal_id': {'readonly': True}, - 'principal_type_created_by_principal_type': {'readonly': True}, - 'principal_name': {'readonly': True}, - 'user_principal_name': {'readonly': True}, + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + "resource_id": {"readonly": True}, + "role_definition_id": {"readonly": True}, + "principal_type_scope_principal_type": {"readonly": True}, + "assignment_state": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type_created_by_principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, } _attribute_map = { - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'description_for_admins': {'key': 'descriptionForAdmins', 'type': 'str'}, - 'description_for_reviewers': {'key': 'descriptionForReviewers', 'type': 'str'}, - 'reviewers': {'key': 'reviewers', 'type': '[AccessReviewReviewer]'}, - 'backup_reviewers': {'key': 'backupReviewers', 'type': '[AccessReviewReviewer]'}, - 'reviewers_type': {'key': 'reviewersType', 'type': 'str'}, - 'instances': {'key': 'instances', 'type': '[AccessReviewInstance]'}, - 'resource_id': {'key': 'scope.resourceId', 'type': 'str'}, - 'role_definition_id': {'key': 'scope.roleDefinitionId', 'type': 'str'}, - 'principal_type_scope_principal_type': {'key': 'scope.principalType', 'type': 'str'}, - 'assignment_state': {'key': 'scope.assignmentState', 'type': 'str'}, - 'inactive_duration': {'key': 'scope.inactiveDuration', 'type': 'duration'}, - 'mail_notifications_enabled': {'key': 'settings.mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'settings.reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'settings.defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'settings.justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'settings.defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'settings.autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'settings.recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'settings.instanceDurationInDays', 'type': 'int'}, - 'type_settings_recurrence_range_type': {'key': 'settings.recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'settings.recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'settings.recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'settings.recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_settings_recurrence_pattern_type': {'key': 'settings.recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'settings.recurrence.pattern.interval', 'type': 'int'}, - 'principal_id': {'key': 'createdBy.principalId', 'type': 'str'}, - 'principal_type_created_by_principal_type': {'key': 'createdBy.principalType', 'type': 'str'}, - 'principal_name': {'key': 'createdBy.principalName', 'type': 'str'}, - 'user_principal_name': {'key': 'createdBy.userPrincipalName', 'type': 'str'}, + "display_name": {"key": "displayName", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "description_for_admins": {"key": "descriptionForAdmins", "type": "str"}, + "description_for_reviewers": {"key": "descriptionForReviewers", "type": "str"}, + "reviewers": {"key": "reviewers", "type": "[AccessReviewReviewer]"}, + "backup_reviewers": {"key": "backupReviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "reviewersType", "type": "str"}, + "instances": {"key": "instances", "type": "[AccessReviewInstance]"}, + "resource_id": {"key": "scope.resourceId", "type": "str"}, + "role_definition_id": {"key": "scope.roleDefinitionId", "type": "str"}, + "principal_type_scope_principal_type": {"key": "scope.principalType", "type": "str"}, + "assignment_state": {"key": "scope.assignmentState", "type": "str"}, + "inactive_duration": {"key": "scope.inactiveDuration", "type": "duration"}, + "mail_notifications_enabled": {"key": "settings.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "settings.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "settings.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "settings.justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "settings.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "settings.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "settings.recommendationsEnabled", "type": "bool"}, + "instance_duration_in_days": {"key": "settings.instanceDurationInDays", "type": "int"}, + "type_settings_recurrence_range_type": {"key": "settings.recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "settings.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "settings.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "settings.recurrence.range.endDate", "type": "iso-8601"}, + "type_settings_recurrence_pattern_type": {"key": "settings.recurrence.pattern.type", "type": "str"}, + "interval": {"key": "settings.recurrence.pattern.interval", "type": "int"}, + "principal_id": {"key": "createdBy.principalId", "type": "str"}, + "principal_type_created_by_principal_type": {"key": "createdBy.principalType", "type": "str"}, + "principal_name": {"key": "createdBy.principalName", "type": "str"}, + "user_principal_name": {"key": "createdBy.userPrincipalName", "type": "str"}, } - def __init__( + def __init__( # pylint: disable=too-many-locals self, *, display_name: Optional[str] = None, description_for_admins: Optional[str] = None, description_for_reviewers: Optional[str] = None, - reviewers: Optional[List["AccessReviewReviewer"]] = None, - backup_reviewers: Optional[List["AccessReviewReviewer"]] = None, - instances: Optional[List["AccessReviewInstance"]] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + backup_reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + instances: Optional[List["_models.AccessReviewInstance"]] = None, inactive_duration: Optional[datetime.timedelta] = None, mail_notifications_enabled: Optional[bool] = None, reminder_notifications_enabled: Optional[bool] = None, default_decision_enabled: Optional[bool] = None, justification_required_on_approval: Optional[bool] = None, - default_decision: Optional[Union[str, "DefaultDecisionType"]] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, auto_apply_decisions_enabled: Optional[bool] = None, recommendations_enabled: Optional[bool] = None, instance_duration_in_days: Optional[int] = None, - type_settings_recurrence_range_type: Optional[Union[str, "AccessReviewRecurrenceRangeType"]] = None, + type_settings_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, number_of_occurrences: Optional[int] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, - type_settings_recurrence_pattern_type: Optional[Union[str, "AccessReviewRecurrencePatternType"]] = None, + type_settings_recurrence_pattern_type: Optional[Union[str, "_models.AccessReviewRecurrencePatternType"]] = None, interval: Optional[int] = None, **kwargs ): - super(AccessReviewScheduleDefinitionProperties, self).__init__(**kwargs) + """ + :keyword display_name: The display name for the schedule definition. + :paramtype display_name: str + :keyword description_for_admins: The description provided by the access review creator and + visible to admins. + :paramtype description_for_admins: str + :keyword description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :paramtype description_for_reviewers: str + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] + :keyword backup_reviewers: This is the collection of backup reviewers. + :paramtype backup_reviewers: + list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewReviewer] + :keyword instances: This is the collection of instances returned when one does an expand on it. + :paramtype instances: + list[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] + :keyword inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :paramtype inactive_duration: ~datetime.timedelta + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_settings_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :paramtype type_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) self.display_name = display_name self.status = None self.description_for_admins = description_for_admins @@ -1207,70 +1453,70 @@ def __init__( self.user_principal_name = None -class AccessReviewScheduleSettings(msrest.serialization.Model): +class AccessReviewScheduleSettings(_serialization.Model): # pylint: disable=too-many-instance-attributes """Settings of an Access Review. - :param mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the review creator is enabled. - :type mail_notifications_enabled: bool - :param reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to reviewers are enabled. - :type reminder_notifications_enabled: bool - :param default_decision_enabled: Flag to indicate whether reviewers are required to provide a + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a justification when reviewing access. - :type default_decision_enabled: bool - :param justification_required_on_approval: Flag to indicate whether the reviewer is required to + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to pass justification when recording a decision. - :type justification_required_on_approval: bool - :param default_decision: This specifies the behavior for the autoReview feature when an access - review completes. Possible values include: "Approve", "Deny", "Recommendation". - :type default_decision: str or + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType - :param auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to automatically change the target object access resource, is enabled. If not enabled, a user must, after the review completes, apply the access review. - :type auto_apply_decisions_enabled: bool - :param recommendations_enabled: Flag to indicate whether showing recommendations to reviewers - is enabled. - :type recommendations_enabled: bool - :param instance_duration_in_days: The duration in days for an instance. - :type instance_duration_in_days: int - :param type_recurrence_range_type: The recurrence range type. The possible values are: endDate, - noEnd, numbered. Possible values include: "endDate", "noEnd", "numbered". - :type type_recurrence_range_type: str or + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_recurrence_range_type: The recurrence range type. The possible values are: endDate, + noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_recurrence_range_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType - :param number_of_occurrences: The number of times to repeat the access review. Required and - must be positive if type is numbered. - :type number_of_occurrences: int - :param start_date: The DateTime when the review is scheduled to be start. This could be a date + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date in the future. Required on create. - :type start_date: ~datetime.datetime - :param end_date: The DateTime when the review is scheduled to end. Required if type is endDate. - :type end_date: ~datetime.datetime - :param type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Possible - values include: "weekly", "absoluteMonthly". - :type type_recurrence_pattern_type: str or + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known values + are: "weekly" and "absoluteMonthly". + :vartype type_recurrence_pattern_type: str or ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType - :param interval: The interval for recurrence. For a quarterly review, the interval is 3 for - type : absoluteMonthly. - :type interval: int + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int """ _attribute_map = { - 'mail_notifications_enabled': {'key': 'mailNotificationsEnabled', 'type': 'bool'}, - 'reminder_notifications_enabled': {'key': 'reminderNotificationsEnabled', 'type': 'bool'}, - 'default_decision_enabled': {'key': 'defaultDecisionEnabled', 'type': 'bool'}, - 'justification_required_on_approval': {'key': 'justificationRequiredOnApproval', 'type': 'bool'}, - 'default_decision': {'key': 'defaultDecision', 'type': 'str'}, - 'auto_apply_decisions_enabled': {'key': 'autoApplyDecisionsEnabled', 'type': 'bool'}, - 'recommendations_enabled': {'key': 'recommendationsEnabled', 'type': 'bool'}, - 'instance_duration_in_days': {'key': 'instanceDurationInDays', 'type': 'int'}, - 'type_recurrence_range_type': {'key': 'recurrence.range.type', 'type': 'str'}, - 'number_of_occurrences': {'key': 'recurrence.range.numberOfOccurrences', 'type': 'int'}, - 'start_date': {'key': 'recurrence.range.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'recurrence.range.endDate', 'type': 'iso-8601'}, - 'type_recurrence_pattern_type': {'key': 'recurrence.pattern.type', 'type': 'str'}, - 'interval': {'key': 'recurrence.pattern.interval', 'type': 'int'}, + "mail_notifications_enabled": {"key": "mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "recommendationsEnabled", "type": "bool"}, + "instance_duration_in_days": {"key": "instanceDurationInDays", "type": "int"}, + "type_recurrence_range_type": {"key": "recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "recurrence.range.endDate", "type": "iso-8601"}, + "type_recurrence_pattern_type": {"key": "recurrence.pattern.type", "type": "str"}, + "interval": {"key": "recurrence.pattern.interval", "type": "int"}, } def __init__( @@ -1280,19 +1526,66 @@ def __init__( reminder_notifications_enabled: Optional[bool] = None, default_decision_enabled: Optional[bool] = None, justification_required_on_approval: Optional[bool] = None, - default_decision: Optional[Union[str, "DefaultDecisionType"]] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, auto_apply_decisions_enabled: Optional[bool] = None, recommendations_enabled: Optional[bool] = None, instance_duration_in_days: Optional[int] = None, - type_recurrence_range_type: Optional[Union[str, "AccessReviewRecurrenceRangeType"]] = None, + type_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, number_of_occurrences: Optional[int] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, - type_recurrence_pattern_type: Optional[Union[str, "AccessReviewRecurrencePatternType"]] = None, + type_recurrence_pattern_type: Optional[Union[str, "_models.AccessReviewRecurrencePatternType"]] = None, interval: Optional[int] = None, **kwargs ): - super(AccessReviewScheduleSettings, self).__init__(**kwargs) + """ + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_recurrence_range_type: The recurrence range type. The possible values are: + endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known values + are: "weekly" and "absoluteMonthly". + :paramtype type_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) self.mail_notifications_enabled = mail_notifications_enabled self.reminder_notifications_enabled = reminder_notifications_enabled self.default_decision_enabled = default_decision_enabled @@ -1309,76 +1602,75 @@ def __init__( self.interval = interval -class ErrorDefinition(msrest.serialization.Model): +class ErrorDefinition(_serialization.Model): """Error description and code explaining why an operation failed. - :param error: Error of the list gateway status. - :type error: ~azure.mgmt.authorization.v2021_03_01_preview.models.ErrorDefinitionProperties + :ivar error: Error of the list gateway status. + :vartype error: ~azure.mgmt.authorization.v2021_03_01_preview.models.ErrorDefinitionProperties """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinitionProperties'}, + "error": {"key": "error", "type": "ErrorDefinitionProperties"}, } - def __init__( - self, - *, - error: Optional["ErrorDefinitionProperties"] = None, - **kwargs - ): - super(ErrorDefinition, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDefinitionProperties"] = None, **kwargs): + """ + :keyword error: Error of the list gateway status. + :paramtype error: + ~azure.mgmt.authorization.v2021_03_01_preview.models.ErrorDefinitionProperties + """ + super().__init__(**kwargs) self.error = error -class ErrorDefinitionProperties(msrest.serialization.Model): +class ErrorDefinitionProperties(_serialization.Model): """Error description and code explaining why an operation failed. Variables are only populated by the server, and will be ignored when sending a request. :ivar message: Description of the error. :vartype message: str - :param code: Error code of list gateway. - :type code: str + :ivar code: Error code of list gateway. + :vartype code: str """ _validation = { - 'message': {'readonly': True}, + "message": {"readonly": True}, } _attribute_map = { - 'message': {'key': 'message', 'type': 'str'}, - 'code': {'key': 'code', 'type': 'str'}, + "message": {"key": "message", "type": "str"}, + "code": {"key": "code", "type": "str"}, } - def __init__( - self, - *, - code: Optional[str] = None, - **kwargs - ): - super(ErrorDefinitionProperties, self).__init__(**kwargs) + def __init__(self, *, code: Optional[str] = None, **kwargs): + """ + :keyword code: Error code of list gateway. + :paramtype code: str + """ + super().__init__(**kwargs) self.message = None self.code = code -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """The definition of a Microsoft.Authorization operation. - :param name: Name of the operation. - :type name: str - :param is_data_action: Indicates whether the operation is a data action. - :type is_data_action: bool - :param display: Display of the operation. - :type display: ~azure.mgmt.authorization.v2021_03_01_preview.models.OperationDisplay - :param origin: Origin of the operation. - :type origin: str + :ivar name: Name of the operation. + :vartype name: str + :ivar is_data_action: Indicates whether the operation is a data action. + :vartype is_data_action: bool + :ivar display: Display of the operation. + :vartype display: ~azure.mgmt.authorization.v2021_03_01_preview.models.OperationDisplay + :ivar origin: Origin of the operation. + :vartype origin: str """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'origin': {'key': 'origin', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, } def __init__( @@ -1386,18 +1678,28 @@ def __init__( *, name: Optional[str] = None, is_data_action: Optional[bool] = None, - display: Optional["OperationDisplay"] = None, + display: Optional["_models.OperationDisplay"] = None, origin: Optional[str] = None, **kwargs ): - super(Operation, self).__init__(**kwargs) + """ + :keyword name: Name of the operation. + :paramtype name: str + :keyword is_data_action: Indicates whether the operation is a data action. + :paramtype is_data_action: bool + :keyword display: Display of the operation. + :paramtype display: ~azure.mgmt.authorization.v2021_03_01_preview.models.OperationDisplay + :keyword origin: Origin of the operation. + :paramtype origin: str + """ + super().__init__(**kwargs) self.name = name self.is_data_action = is_data_action self.display = display self.origin = origin -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """The display information for a Microsoft.Authorization operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -1413,51 +1715,49 @@ class OperationDisplay(msrest.serialization.Model): """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """The result of a request to list Microsoft.Authorization operations. - :param value: The collection value. - :type value: list[~azure.mgmt.authorization.v2021_03_01_preview.models.Operation] - :param next_link: The URI that can be used to request the next set of paged results. - :type next_link: str + :ivar value: The collection value. + :vartype value: list[~azure.mgmt.authorization.v2021_03_01_preview.models.Operation] + :ivar next_link: The URI that can be used to request the next set of paged results. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["Operation"]] = None, - next_link: Optional[str] = None, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs): + """ + :keyword value: The collection value. + :paramtype value: list[~azure.mgmt.authorization.v2021_03_01_preview.models.Operation] + :keyword next_link: The URI that can be used to request the next set of paged results. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/__init__.py index 9fe7178064d..2ed7cbae216 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/__init__.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/__init__.py @@ -12,18 +12,28 @@ from ._access_review_instance_operations import AccessReviewInstanceOperations from ._access_review_instance_decisions_operations import AccessReviewInstanceDecisionsOperations from ._access_review_default_settings_operations import AccessReviewDefaultSettingsOperations -from ._access_review_schedule_definitions_assigned_for_my_approval_operations import AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations -from ._access_review_instances_assigned_for_my_approval_operations import AccessReviewInstancesAssignedForMyApprovalOperations +from ._access_review_schedule_definitions_assigned_for_my_approval_operations import ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, +) +from ._access_review_instances_assigned_for_my_approval_operations import ( + AccessReviewInstancesAssignedForMyApprovalOperations, +) from ._access_review_instance_my_decisions_operations import AccessReviewInstanceMyDecisionsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'Operations', - 'AccessReviewScheduleDefinitionsOperations', - 'AccessReviewInstancesOperations', - 'AccessReviewInstanceOperations', - 'AccessReviewInstanceDecisionsOperations', - 'AccessReviewDefaultSettingsOperations', - 'AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations', - 'AccessReviewInstancesAssignedForMyApprovalOperations', - 'AccessReviewInstanceMyDecisionsOperations', + "Operations", + "AccessReviewScheduleDefinitionsOperations", + "AccessReviewInstancesOperations", + "AccessReviewInstanceOperations", + "AccessReviewInstanceDecisionsOperations", + "AccessReviewDefaultSettingsOperations", + "AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations", + "AccessReviewInstancesAssignedForMyApprovalOperations", + "AccessReviewInstanceMyDecisionsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_default_settings_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_default_settings_operations.py index 232c1f8005f..dd90161f275 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_default_settings_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_default_settings_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,153 +6,268 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class AccessReviewDefaultSettingsOperations(object): - """AccessReviewDefaultSettingsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_get_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_put_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewDefaultSettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_default_settings` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def get( - self, - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewDefaultSettings" + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, **kwargs: Any) -> _models.AccessReviewDefaultSettings: """Get access review default settings for the subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDefaultSettings, or the result of cls(response) + :return: AccessReviewDefaultSettings or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDefaultSettings - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDefaultSettings"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDefaultSettings', pipeline_response) + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore + + @overload def put( - self, - properties, # type: "_models.AccessReviewScheduleSettings" - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewDefaultSettings" + self, properties: _models.AccessReviewScheduleSettings, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: """Get access review default settings for the subscription. - :param properties: Access review schedule settings. - :type properties: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleSettings + :param properties: Access review schedule settings. Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleSettings + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDefaultSettings, or the result of cls(response) + :return: AccessReviewDefaultSettings or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDefaultSettings - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put( + self, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put( + self, properties: Union[_models.AccessReviewScheduleSettings, IO], **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleSettings or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDefaultSettings"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.put.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewScheduleSettings') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleSettings") + + request = build_put_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDefaultSettings', pipeline_response) + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default'} # type: ignore + + put.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_decisions_operations.py index 3437cd4606f..0f804c6a526 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_decisions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_decisions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,107 +6,153 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + schedule_definition_id: str, id: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class AccessReviewInstanceDecisionsOperations(object): - """AccessReviewInstanceDecisionsOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class AccessReviewInstanceDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance_decisions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - schedule_definition_id, # type: str - id, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewDecisionListResult"] + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewDecision"]: """Get access review instance decisions. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewDecisionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecisionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecisionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewDecisionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -114,17 +161,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_my_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_my_decisions_operations.py index c48455101f1..9c98e48e737 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_my_decisions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_my_decisions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,106 +6,212 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + schedule_definition_id: str, id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "decisionId": _SERIALIZER.url("decision_id", decision_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class AccessReviewInstanceMyDecisionsOperations(object): - """AccessReviewInstanceMyDecisionsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_patch_request(schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "decisionId": _SERIALIZER.url("decision_id", decision_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceMyDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance_my_decisions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - schedule_definition_id, # type: str - id, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewDecisionListResult"] + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewDecision"]: """Get my access review instance decisions. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewDecisionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecisionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecisionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewDecisionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -113,151 +220,229 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore + @distributed_trace def get_by_id( - self, - schedule_definition_id, # type: str - id, # type: str - decision_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewDecision" + self, schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any + ) -> _models.AccessReviewDecision: """Get my single access review instance decision. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str - :param decision_id: The id of the decision record. + :param decision_id: The id of the decision record. Required. :type decision_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDecision, or the result of cls(response) + :return: AccessReviewDecision or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecision"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'decisionId': self._serialize.url("decision_id", decision_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDecision', pipeline_response) + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}'} # type: ignore + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore + + @overload + def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: _models.AccessReviewDecisionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecisionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload def patch( self, - schedule_definition_id, # type: str - id, # type: str - decision_id, # type: str - properties, # type: "_models.AccessReviewDecisionProperties" - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewDecision" + schedule_definition_id: str, + id: str, + decision_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: """Record a decision. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str - :param decision_id: The id of the decision record. + :param decision_id: The id of the decision record. Required. :type decision_id: str - :param properties: Access review decision properties to patch. - :type properties: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecisionProperties + :param properties: Access review decision properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewDecision, or the result of cls(response) + :return: AccessReviewDecision or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: Union[_models.AccessReviewDecisionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecisionProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewDecision"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.patch.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'decisionId': self._serialize.url("decision_id", decision_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewDecisionProperties') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewDecisionProperties") + + request = build_patch_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewDecision', pipeline_response) + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - patch.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}'} # type: ignore + + patch.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_operations.py index fa1686655fb..04cc3daa106 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instance_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,325 +6,483 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_stop_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reset_decisions_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_apply_decisions_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_send_reminders_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } -class AccessReviewInstanceOperations(object): - """AccessReviewInstanceOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_accept_recommendations_request(schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def stop( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: """An action to stop an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.stop.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - stop.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop'} # type: ignore + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop"} # type: ignore - def reset_decisions( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + @distributed_trace + def reset_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: """An action to reset all decisions for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.reset_decisions.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reset_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.reset_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - reset_decisions.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions'} # type: ignore + reset_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions"} # type: ignore - def apply_decisions( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + @distributed_trace + def apply_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: """An action to apply all decisions for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.apply_decisions.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_apply_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.apply_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - apply_decisions.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions'} # type: ignore + apply_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions"} # type: ignore - def send_reminders( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + @distributed_trace + def send_reminders( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: """An action to send reminders for an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.send_reminders.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_send_reminders_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.send_reminders.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - send_reminders.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders'} # type: ignore + send_reminders.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders"} # type: ignore - def accept_recommendations( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + @distributed_trace + def accept_recommendations( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: """An action to accept recommendations for decision in an access review instance. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.accept_recommendations.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_accept_recommendations_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.accept_recommendations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - accept_recommendations.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations'} # type: ignore + accept_recommendations.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py index 793f7611042..285a25a6175 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,102 +6,173 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class AccessReviewInstancesAssignedForMyApprovalOperations(object): - """AccessReviewInstancesAssignedForMyApprovalOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_list_request(schedule_definition_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstancesAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instances_assigned_for_my_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - schedule_definition_id, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewInstanceListResult"] + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewInstance"]: """Get access review instances assigned for my approval. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewInstanceListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewInstanceListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -109,76 +181,76 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances'} # type: ignore - - def get_by_id( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewInstance" + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: """Get single access review instance assigned for my approval. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewInstance, or the result of cls(response) + :return: AccessReviewInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewInstance', pipeline_response) + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}'} # type: ignore + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instances_operations.py index 4ab41b51436..0219b6dfdec 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instances_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_instances_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,103 +6,178 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class AccessReviewInstancesOperations(object): - """AccessReviewInstancesOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_list_request( + schedule_definition_id: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instances` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - schedule_definition_id, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewInstanceListResult"] + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewInstance"]: """Get access review instances. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewInstanceListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstanceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstanceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewInstanceListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -110,77 +186,77 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances'} # type: ignore - - def get_by_id( - self, - schedule_definition_id, # type: str - id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewInstance" + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: """Get access review instances. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param id: The id of the access review instance. + :param id: The id of the access review instance. Required. :type id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewInstance, or the result of cls(response) + :return: AccessReviewInstance or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewInstance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewInstance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'id': self._serialize.url("id", id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewInstance', pipeline_response) + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}'} # type: ignore + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py index ad4b826a033..bcc73df9975 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,132 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(*, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations(object): - """AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions_assigned_for_my_approval` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewScheduleDefinitionListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.AccessReviewScheduleDefinition"]: """Get access review instances assigned for my approval. :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewScheduleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewScheduleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -102,17 +140,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/accessReviewScheduleDefinitions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_schedule_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_schedule_definitions_operations.py index 53c36160607..abbf64e0904 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_schedule_definitions_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_access_review_schedule_definitions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,99 +6,258 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + _url = _format_url_section(_url, **path_format_arguments) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -class AccessReviewScheduleDefinitionsOperations(object): - """AccessReviewScheduleDefinitionsOperations operations. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + +def build_create_or_update_by_id_request( + schedule_definition_id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_stop_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewScheduleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AccessReviewScheduleDefinitionListResult"] + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.AccessReviewScheduleDefinition"]: """Get access review schedule definitions. :param filter: The filter to apply on the operation. Other than standard filters, one custom filter option is supported : 'assignedToMeToReview()'. When one specified $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are - returned. + returned. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AccessReviewScheduleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str', skip_quote=True) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AccessReviewScheduleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -106,243 +266,307 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions'} # type: ignore + return ItemPaged(get_next, extract_data) - def get_by_id( - self, - schedule_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewScheduleDefinition" + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, **kwargs: Any) -> _models.AccessReviewScheduleDefinition: """Get single access review definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewScheduleDefinition, or the result of cls(response) + :return: AccessReviewScheduleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewScheduleDefinition', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore - def delete_by_id( - self, - schedule_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace + def delete_by_id( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: """Delete access review schedule definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_delete_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore + delete_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @overload + def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: _models.AccessReviewScheduleDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_by_id( + self, schedule_definition_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace def create_or_update_by_id( self, - schedule_definition_id, # type: str - properties, # type: "_models.AccessReviewScheduleDefinitionProperties" - **kwargs # type: Any - ): - # type: (...) -> "_models.AccessReviewScheduleDefinition" + schedule_definition_id: str, + properties: Union[_models.AccessReviewScheduleDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: """Create or Update access review schedule definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str - :param properties: Access review schedule definition properties. - :type properties: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionProperties + :param properties: Access review schedule definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinitionProperties + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessReviewScheduleDefinition, or the result of cls(response) + :return: AccessReviewScheduleDefinition or the result of cls(response) :rtype: ~azure.mgmt.authorization.v2021_03_01_preview.models.AccessReviewScheduleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AccessReviewScheduleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(properties, 'AccessReviewScheduleDefinitionProperties') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleDefinitionProperties") + + request = build_create_or_update_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AccessReviewScheduleDefinition', pipeline_response) + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}'} # type: ignore - def stop( - self, - schedule_definition_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + create_or_update_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace + def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: """Stop access review definition. - :param schedule_definition_id: The id of the access review schedule definition. + :param schedule_definition_id: The id of the access review schedule definition. Required. :type schedule_definition_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.stop.metadata['url'] # type: ignore - path_format_arguments = { - 'scheduleDefinitionId': self._serialize.url("schedule_definition_id", schedule_definition_id, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - stop.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop'} # type: ignore + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_operations.py index 52fa6e32a55..a81299a60bc 100644 --- a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_operations.py +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,123 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") -class Operations(object): - """Operations operations. + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/operations") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.authorization.v2021_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_03_01_preview.AuthorizationManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.OperationListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists the operations available from this provider. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_03_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,17 +131,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Authorization/operations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_03_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/__init__.py new file mode 100644 index 00000000000..9eb8d3ec28c --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/__init__.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._authorization_management_client import AuthorizationManagementClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_authorization_management_client.py new file mode 100644 index 00000000000..f7c1492f1f3 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_authorization_management_client.py @@ -0,0 +1,173 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + AccessReviewDefaultSettingsOperations, + AccessReviewInstanceContactedReviewersOperations, + AccessReviewInstanceDecisionsOperations, + AccessReviewInstanceMyDecisionsOperations, + AccessReviewInstanceOperations, + AccessReviewInstancesAssignedForMyApprovalOperations, + AccessReviewInstancesOperations, + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, + AccessReviewScheduleDefinitionsOperations, + Operations, + TenantLevelAccessReviewInstanceContactedReviewersOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Access reviews service provides the workflow for running access reviews on different kind of + resources. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.authorization.v2021_07_01_preview.operations.Operations + :ivar access_review_schedule_definitions: AccessReviewScheduleDefinitionsOperations operations + :vartype access_review_schedule_definitions: + azure.mgmt.authorization.v2021_07_01_preview.operations.AccessReviewScheduleDefinitionsOperations + :ivar access_review_instances: AccessReviewInstancesOperations operations + :vartype access_review_instances: + azure.mgmt.authorization.v2021_07_01_preview.operations.AccessReviewInstancesOperations + :ivar access_review_instance: AccessReviewInstanceOperations operations + :vartype access_review_instance: + azure.mgmt.authorization.v2021_07_01_preview.operations.AccessReviewInstanceOperations + :ivar access_review_instance_decisions: AccessReviewInstanceDecisionsOperations operations + :vartype access_review_instance_decisions: + azure.mgmt.authorization.v2021_07_01_preview.operations.AccessReviewInstanceDecisionsOperations + :ivar access_review_instance_contacted_reviewers: + AccessReviewInstanceContactedReviewersOperations operations + :vartype access_review_instance_contacted_reviewers: + azure.mgmt.authorization.v2021_07_01_preview.operations.AccessReviewInstanceContactedReviewersOperations + :ivar access_review_default_settings: AccessReviewDefaultSettingsOperations operations + :vartype access_review_default_settings: + azure.mgmt.authorization.v2021_07_01_preview.operations.AccessReviewDefaultSettingsOperations + :ivar access_review_schedule_definitions_assigned_for_my_approval: + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations + :vartype access_review_schedule_definitions_assigned_for_my_approval: + azure.mgmt.authorization.v2021_07_01_preview.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations + :ivar access_review_instances_assigned_for_my_approval: + AccessReviewInstancesAssignedForMyApprovalOperations operations + :vartype access_review_instances_assigned_for_my_approval: + azure.mgmt.authorization.v2021_07_01_preview.operations.AccessReviewInstancesAssignedForMyApprovalOperations + :ivar access_review_instance_my_decisions: AccessReviewInstanceMyDecisionsOperations operations + :vartype access_review_instance_my_decisions: + azure.mgmt.authorization.v2021_07_01_preview.operations.AccessReviewInstanceMyDecisionsOperations + :ivar tenant_level_access_review_instance_contacted_reviewers: + TenantLevelAccessReviewInstanceContactedReviewersOperations operations + :vartype tenant_level_access_review_instance_contacted_reviewers: + azure.mgmt.authorization.v2021_07_01_preview.operations.TenantLevelAccessReviewInstanceContactedReviewersOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2021-07-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.access_review_schedule_definitions = AccessReviewScheduleDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instances = AccessReviewInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance = AccessReviewInstanceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_decisions = AccessReviewInstanceDecisionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_contacted_reviewers = AccessReviewInstanceContactedReviewersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_default_settings = AccessReviewDefaultSettingsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_schedule_definitions_assigned_for_my_approval = ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) + self.access_review_instances_assigned_for_my_approval = AccessReviewInstancesAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_my_decisions = AccessReviewInstanceMyDecisionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.tenant_level_access_review_instance_contacted_reviewers = ( + TenantLevelAccessReviewInstanceContactedReviewersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> AuthorizationManagementClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_configuration.py new file mode 100644 index 00000000000..63ea1a05b64 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_configuration.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for AuthorizationManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2021-07-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2021-07-01-preview") # type: str + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_metadata.json new file mode 100644 index 00000000000..b93a659c734 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_metadata.json @@ -0,0 +1,112 @@ +{ + "chosen_version": "2021-07-01-preview", + "total_api_version_list": ["2021-07-01-preview"], + "client": { + "name": "AuthorizationManagementClient", + "filename": "_authorization_management_client", + "description": "Access reviews service provides the workflow for running access reviews on different kind of resources.", + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, + "azure_arm": true, + "has_lro_operations": false, + "client_side_validation": false, + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "global_parameters": { + "sync": { + "credential": { + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials.TokenCredential", + "required": true + }, + "subscription_id": { + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", + "docstring_type": "str", + "required": true + } + }, + "async": { + "credential": { + "signature": "credential: \"AsyncTokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", + "required": true + }, + "subscription_id": { + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", + "docstring_type": "str", + "required": true + } + }, + "constant": { + }, + "call": "credential, subscription_id", + "service_client_specific": { + "sync": { + "api_version": { + "signature": "api_version=None, # type: Optional[str]", + "description": "API version to use if no profile is provided, or if missing in profile.", + "docstring_type": "str", + "required": false + }, + "base_url": { + "signature": "base_url: str = \"https://management.azure.com\",", + "description": "Service URL", + "docstring_type": "str", + "required": false + }, + "profile": { + "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "description": "A profile definition, from KnownProfiles to dict.", + "docstring_type": "azure.profiles.KnownProfiles", + "required": false + } + }, + "async": { + "api_version": { + "signature": "api_version: Optional[str] = None,", + "description": "API version to use if no profile is provided, or if missing in profile.", + "docstring_type": "str", + "required": false + }, + "base_url": { + "signature": "base_url: str = \"https://management.azure.com\",", + "description": "Service URL", + "docstring_type": "str", + "required": false + }, + "profile": { + "signature": "profile: KnownProfiles = KnownProfiles.default,", + "description": "A profile definition, from KnownProfiles to dict.", + "docstring_type": "azure.profiles.KnownProfiles", + "required": false + } + } + } + }, + "config": { + "credential": true, + "credential_scopes": ["https://management.azure.com/.default"], + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "operation_groups": { + "operations": "Operations", + "access_review_schedule_definitions": "AccessReviewScheduleDefinitionsOperations", + "access_review_instances": "AccessReviewInstancesOperations", + "access_review_instance": "AccessReviewInstanceOperations", + "access_review_instance_decisions": "AccessReviewInstanceDecisionsOperations", + "access_review_instance_contacted_reviewers": "AccessReviewInstanceContactedReviewersOperations", + "access_review_default_settings": "AccessReviewDefaultSettingsOperations", + "access_review_schedule_definitions_assigned_for_my_approval": "AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations", + "access_review_instances_assigned_for_my_approval": "AccessReviewInstancesAssignedForMyApprovalOperations", + "access_review_instance_my_decisions": "AccessReviewInstanceMyDecisionsOperations", + "tenant_level_access_review_instance_contacted_reviewers": "TenantLevelAccessReviewInstanceContactedReviewersOperations" + } +} \ No newline at end of file diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_version.py new file mode 100644 index 00000000000..cac9f5d10f8 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/__init__.py new file mode 100644 index 00000000000..dd28625b36f --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._authorization_management_client import AuthorizationManagementClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_authorization_management_client.py new file mode 100644 index 00000000000..4e6628a6c58 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_authorization_management_client.py @@ -0,0 +1,170 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + AccessReviewDefaultSettingsOperations, + AccessReviewInstanceContactedReviewersOperations, + AccessReviewInstanceDecisionsOperations, + AccessReviewInstanceMyDecisionsOperations, + AccessReviewInstanceOperations, + AccessReviewInstancesAssignedForMyApprovalOperations, + AccessReviewInstancesOperations, + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, + AccessReviewScheduleDefinitionsOperations, + Operations, + TenantLevelAccessReviewInstanceContactedReviewersOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Access reviews service provides the workflow for running access reviews on different kind of + resources. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.authorization.v2021_07_01_preview.aio.operations.Operations + :ivar access_review_schedule_definitions: AccessReviewScheduleDefinitionsOperations operations + :vartype access_review_schedule_definitions: + azure.mgmt.authorization.v2021_07_01_preview.aio.operations.AccessReviewScheduleDefinitionsOperations + :ivar access_review_instances: AccessReviewInstancesOperations operations + :vartype access_review_instances: + azure.mgmt.authorization.v2021_07_01_preview.aio.operations.AccessReviewInstancesOperations + :ivar access_review_instance: AccessReviewInstanceOperations operations + :vartype access_review_instance: + azure.mgmt.authorization.v2021_07_01_preview.aio.operations.AccessReviewInstanceOperations + :ivar access_review_instance_decisions: AccessReviewInstanceDecisionsOperations operations + :vartype access_review_instance_decisions: + azure.mgmt.authorization.v2021_07_01_preview.aio.operations.AccessReviewInstanceDecisionsOperations + :ivar access_review_instance_contacted_reviewers: + AccessReviewInstanceContactedReviewersOperations operations + :vartype access_review_instance_contacted_reviewers: + azure.mgmt.authorization.v2021_07_01_preview.aio.operations.AccessReviewInstanceContactedReviewersOperations + :ivar access_review_default_settings: AccessReviewDefaultSettingsOperations operations + :vartype access_review_default_settings: + azure.mgmt.authorization.v2021_07_01_preview.aio.operations.AccessReviewDefaultSettingsOperations + :ivar access_review_schedule_definitions_assigned_for_my_approval: + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations + :vartype access_review_schedule_definitions_assigned_for_my_approval: + azure.mgmt.authorization.v2021_07_01_preview.aio.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations + :ivar access_review_instances_assigned_for_my_approval: + AccessReviewInstancesAssignedForMyApprovalOperations operations + :vartype access_review_instances_assigned_for_my_approval: + azure.mgmt.authorization.v2021_07_01_preview.aio.operations.AccessReviewInstancesAssignedForMyApprovalOperations + :ivar access_review_instance_my_decisions: AccessReviewInstanceMyDecisionsOperations operations + :vartype access_review_instance_my_decisions: + azure.mgmt.authorization.v2021_07_01_preview.aio.operations.AccessReviewInstanceMyDecisionsOperations + :ivar tenant_level_access_review_instance_contacted_reviewers: + TenantLevelAccessReviewInstanceContactedReviewersOperations operations + :vartype tenant_level_access_review_instance_contacted_reviewers: + azure.mgmt.authorization.v2021_07_01_preview.aio.operations.TenantLevelAccessReviewInstanceContactedReviewersOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2021-07-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.access_review_schedule_definitions = AccessReviewScheduleDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instances = AccessReviewInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance = AccessReviewInstanceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_decisions = AccessReviewInstanceDecisionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_contacted_reviewers = AccessReviewInstanceContactedReviewersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_default_settings = AccessReviewDefaultSettingsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_schedule_definitions_assigned_for_my_approval = ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) + self.access_review_instances_assigned_for_my_approval = AccessReviewInstancesAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_my_decisions = AccessReviewInstanceMyDecisionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.tenant_level_access_review_instance_contacted_reviewers = ( + TenantLevelAccessReviewInstanceContactedReviewersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "AuthorizationManagementClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_configuration.py new file mode 100644 index 00000000000..372648548d3 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_configuration.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for AuthorizationManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2021-07-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2021-07-01-preview") # type: str + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/__init__.py new file mode 100644 index 00000000000..58318912431 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/__init__.py @@ -0,0 +1,45 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import Operations +from ._access_review_schedule_definitions_operations import AccessReviewScheduleDefinitionsOperations +from ._access_review_instances_operations import AccessReviewInstancesOperations +from ._access_review_instance_operations import AccessReviewInstanceOperations +from ._access_review_instance_decisions_operations import AccessReviewInstanceDecisionsOperations +from ._access_review_instance_contacted_reviewers_operations import AccessReviewInstanceContactedReviewersOperations +from ._access_review_default_settings_operations import AccessReviewDefaultSettingsOperations +from ._access_review_schedule_definitions_assigned_for_my_approval_operations import ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, +) +from ._access_review_instances_assigned_for_my_approval_operations import ( + AccessReviewInstancesAssignedForMyApprovalOperations, +) +from ._access_review_instance_my_decisions_operations import AccessReviewInstanceMyDecisionsOperations +from ._tenant_level_access_review_instance_contacted_reviewers_operations import ( + TenantLevelAccessReviewInstanceContactedReviewersOperations, +) + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "AccessReviewScheduleDefinitionsOperations", + "AccessReviewInstancesOperations", + "AccessReviewInstanceOperations", + "AccessReviewInstanceDecisionsOperations", + "AccessReviewInstanceContactedReviewersOperations", + "AccessReviewDefaultSettingsOperations", + "AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations", + "AccessReviewInstancesAssignedForMyApprovalOperations", + "AccessReviewInstanceMyDecisionsOperations", + "TenantLevelAccessReviewInstanceContactedReviewersOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_default_settings_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_default_settings_operations.py new file mode 100644 index 00000000000..4ca7c165661 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_default_settings_operations.py @@ -0,0 +1,213 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_default_settings_operations import build_get_request, build_put_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewDefaultSettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_default_settings` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, **kwargs: Any) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + request = build_get_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore + + @overload + async def put( + self, properties: _models.AccessReviewScheduleSettings, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleSettings + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put( + self, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put( + self, properties: Union[_models.AccessReviewScheduleSettings, IO], **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleSettings or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleSettings") + + request = build_put_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + put.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_contacted_reviewers_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_contacted_reviewers_operations.py new file mode 100644 index 00000000000..80af2c9056f --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_contacted_reviewers_operations.py @@ -0,0 +1,136 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instance_contacted_reviewers_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstanceContactedReviewersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance_contacted_reviewers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewContactedReviewer"]: + """Get access review instance contacted reviewers. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewContactedReviewer or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewContactedReviewer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewContactedReviewerListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewContactedReviewerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_decisions_operations.py new file mode 100644 index 00000000000..49af0f09b99 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_decisions_operations.py @@ -0,0 +1,142 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instance_decisions_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstanceDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance_decisions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewDecision"]: + """Get access review instance decisions. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py new file mode 100644 index 00000000000..4088dd2bb2c --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py @@ -0,0 +1,357 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instance_my_decisions_operations import ( + build_get_by_id_request, + build_list_request, + build_patch_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstanceMyDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance_my_decisions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewDecision"]: + """Get my access review instance decisions. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore + + @distributed_trace_async + async def get_by_id( + self, schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any + ) -> _models.AccessReviewDecision: + """Get my single access review instance decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore + + @overload + async def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: _models.AccessReviewDecisionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecisionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: Union[_models.AccessReviewDecisionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecisionProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewDecisionProperties") + + request = build_patch_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + patch.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_operations.py new file mode 100644 index 00000000000..2ba6c31ec8e --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instance_operations.py @@ -0,0 +1,341 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instance_operations import ( + build_accept_recommendations_request, + build_apply_decisions_request, + build_reset_decisions_request, + build_send_reminders_request, + build_stop_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to stop an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop"} # type: ignore + + @distributed_trace_async + async def reset_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to reset all decisions for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reset_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.reset_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + reset_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions"} # type: ignore + + @distributed_trace_async + async def apply_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to apply all decisions for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_apply_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.apply_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + apply_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions"} # type: ignore + + @distributed_trace_async + async def send_reminders( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to send reminders for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_send_reminders_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.send_reminders.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + send_reminders.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders"} # type: ignore + + @distributed_trace_async + async def accept_recommendations( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to accept recommendations for decision in an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_accept_recommendations_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.accept_recommendations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + accept_recommendations.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py new file mode 100644 index 00000000000..5fe768eed11 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py @@ -0,0 +1,200 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instances_assigned_for_my_approval_operations import ( + build_get_by_id_request, + build_list_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstancesAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instances_assigned_for_my_approval` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewInstance"]: + """Get access review instances assigned for my approval. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: + """Get single access review instance assigned for my approval. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instances_operations.py new file mode 100644 index 00000000000..6aafd08331e --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_instances_operations.py @@ -0,0 +1,342 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instances_operations import ( + build_create_request, + build_get_by_id_request, + build_list_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewInstance"]: + """Get access review instances. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: + """Get access review instances. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore + + @overload + async def create( + self, + schedule_definition_id: str, + id: str, + properties: _models.AccessReviewInstanceProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstanceProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + schedule_definition_id: str, + id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + schedule_definition_id: str, + id: str, + properties: Union[_models.AccessReviewInstanceProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstanceProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewInstanceProperties") + + request = build_create_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py new file mode 100644 index 00000000000..25f1a48c5e1 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py @@ -0,0 +1,135 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_schedule_definitions_assigned_for_my_approval_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions_assigned_for_my_approval` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewScheduleDefinition"]: + """Get access review instances assigned for my approval. + + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_schedule_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_schedule_definitions_operations.py new file mode 100644 index 00000000000..6c4552a738d --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_access_review_schedule_definitions_operations.py @@ -0,0 +1,432 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_schedule_definitions_operations import ( + build_create_or_update_by_id_request, + build_delete_by_id_request, + build_get_by_id_request, + build_list_request, + build_stop_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewScheduleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewScheduleDefinition"]: + """Get access review schedule definitions. + + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, **kwargs: Any) -> _models.AccessReviewScheduleDefinition: + """Get single access review definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def delete_by_id( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Delete access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @overload + async def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: _models.AccessReviewScheduleDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_by_id( + self, schedule_definition_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: Union[_models.AccessReviewScheduleDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinitionProperties + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleDefinitionProperties") + + request = build_create_or_update_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Stop access review definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_operations.py new file mode 100644 index 00000000000..aa665255ab1 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_operations.py @@ -0,0 +1,126 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + """Lists the operations available from this provider. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py new file mode 100644 index 00000000000..18f37c2fc82 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/aio/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py @@ -0,0 +1,135 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._tenant_level_access_review_instance_contacted_reviewers_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class TenantLevelAccessReviewInstanceContactedReviewersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.aio.AuthorizationManagementClient`'s + :attr:`tenant_level_access_review_instance_contacted_reviewers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewContactedReviewer"]: + """Get access review instance contacted reviewers. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewContactedReviewer or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewContactedReviewer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewContactedReviewerListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewContactedReviewerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/__init__.py new file mode 100644 index 00000000000..71ce66bf7d0 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/__init__.py @@ -0,0 +1,95 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import AccessReviewContactedReviewer +from ._models_py3 import AccessReviewContactedReviewerListResult +from ._models_py3 import AccessReviewDecision +from ._models_py3 import AccessReviewDecisionIdentity +from ._models_py3 import AccessReviewDecisionListResult +from ._models_py3 import AccessReviewDecisionProperties +from ._models_py3 import AccessReviewDecisionResource +from ._models_py3 import AccessReviewDecisionServicePrincipalIdentity +from ._models_py3 import AccessReviewDecisionUserIdentity +from ._models_py3 import AccessReviewDefaultSettings +from ._models_py3 import AccessReviewInstance +from ._models_py3 import AccessReviewInstanceListResult +from ._models_py3 import AccessReviewInstanceProperties +from ._models_py3 import AccessReviewReviewer +from ._models_py3 import AccessReviewScheduleDefinition +from ._models_py3 import AccessReviewScheduleDefinitionListResult +from ._models_py3 import AccessReviewScheduleDefinitionProperties +from ._models_py3 import AccessReviewScheduleSettings +from ._models_py3 import ErrorDefinition +from ._models_py3 import ErrorDefinitionProperties +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult + +from ._authorization_management_client_enums import AccessRecommendationType +from ._authorization_management_client_enums import AccessReviewActorIdentityType +from ._authorization_management_client_enums import AccessReviewApplyResult +from ._authorization_management_client_enums import AccessReviewInstanceReviewersType +from ._authorization_management_client_enums import AccessReviewInstanceStatus +from ._authorization_management_client_enums import AccessReviewRecurrencePatternType +from ._authorization_management_client_enums import AccessReviewRecurrenceRangeType +from ._authorization_management_client_enums import AccessReviewResult +from ._authorization_management_client_enums import AccessReviewReviewerType +from ._authorization_management_client_enums import AccessReviewScheduleDefinitionReviewersType +from ._authorization_management_client_enums import AccessReviewScheduleDefinitionStatus +from ._authorization_management_client_enums import AccessReviewScopeAssignmentState +from ._authorization_management_client_enums import AccessReviewScopePrincipalType +from ._authorization_management_client_enums import DecisionResourceType +from ._authorization_management_client_enums import DecisionTargetType +from ._authorization_management_client_enums import DefaultDecisionType +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AccessReviewContactedReviewer", + "AccessReviewContactedReviewerListResult", + "AccessReviewDecision", + "AccessReviewDecisionIdentity", + "AccessReviewDecisionListResult", + "AccessReviewDecisionProperties", + "AccessReviewDecisionResource", + "AccessReviewDecisionServicePrincipalIdentity", + "AccessReviewDecisionUserIdentity", + "AccessReviewDefaultSettings", + "AccessReviewInstance", + "AccessReviewInstanceListResult", + "AccessReviewInstanceProperties", + "AccessReviewReviewer", + "AccessReviewScheduleDefinition", + "AccessReviewScheduleDefinitionListResult", + "AccessReviewScheduleDefinitionProperties", + "AccessReviewScheduleSettings", + "ErrorDefinition", + "ErrorDefinitionProperties", + "Operation", + "OperationDisplay", + "OperationListResult", + "AccessRecommendationType", + "AccessReviewActorIdentityType", + "AccessReviewApplyResult", + "AccessReviewInstanceReviewersType", + "AccessReviewInstanceStatus", + "AccessReviewRecurrencePatternType", + "AccessReviewRecurrenceRangeType", + "AccessReviewResult", + "AccessReviewReviewerType", + "AccessReviewScheduleDefinitionReviewersType", + "AccessReviewScheduleDefinitionStatus", + "AccessReviewScopeAssignmentState", + "AccessReviewScopePrincipalType", + "DecisionResourceType", + "DecisionTargetType", + "DefaultDecisionType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_authorization_management_client_enums.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_authorization_management_client_enums.py new file mode 100644 index 00000000000..978ae5ca2ba --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_authorization_management_client_enums.py @@ -0,0 +1,162 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AccessRecommendationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The feature- generated recommendation shown to the reviewer.""" + + APPROVE = "Approve" + DENY = "Deny" + NO_INFO_AVAILABLE = "NoInfoAvailable" + + +class AccessReviewActorIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type : user/servicePrincipal.""" + + USER = "user" + SERVICE_PRINCIPAL = "servicePrincipal" + + +class AccessReviewApplyResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The outcome of applying the decision.""" + + NEW = "New" + APPLYING = "Applying" + APPLIED_SUCCESSFULLY = "AppliedSuccessfully" + APPLIED_WITH_UNKNOWN_FAILURE = "AppliedWithUnknownFailure" + APPLIED_SUCCESSFULLY_BUT_OBJECT_NOT_FOUND = "AppliedSuccessfullyButObjectNotFound" + APPLY_NOT_SUPPORTED = "ApplyNotSupported" + + +class AccessReviewInstanceReviewersType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This field specifies the type of reviewers for a review. Usually for a review, reviewers are + explicitly assigned. However, in some cases, the reviewers may not be assigned and instead be + chosen dynamically. For example managers review or self review. + """ + + ASSIGNED = "Assigned" + SELF = "Self" + MANAGERS = "Managers" + + +class AccessReviewInstanceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This read-only field specifies the status of an access review instance.""" + + NOT_STARTED = "NotStarted" + IN_PROGRESS = "InProgress" + COMPLETED = "Completed" + APPLIED = "Applied" + INITIALIZING = "Initializing" + APPLYING = "Applying" + COMPLETING = "Completing" + SCHEDULED = "Scheduled" + AUTO_REVIEWING = "AutoReviewing" + AUTO_REVIEWED = "AutoReviewed" + STARTING = "Starting" + + +class AccessReviewRecurrencePatternType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The recurrence type : weekly, monthly, etc.""" + + WEEKLY = "weekly" + ABSOLUTE_MONTHLY = "absoluteMonthly" + + +class AccessReviewRecurrenceRangeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The recurrence range type. The possible values are: endDate, noEnd, numbered.""" + + END_DATE = "endDate" + NO_END = "noEnd" + NUMBERED = "numbered" + + +class AccessReviewResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The decision on the approval step. This value is initially set to NotReviewed. Approvers can + take action of Approve/Deny. + """ + + APPROVE = "Approve" + DENY = "Deny" + NOT_REVIEWED = "NotReviewed" + DONT_KNOW = "DontKnow" + NOT_NOTIFIED = "NotNotified" + + +class AccessReviewReviewerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type : user/servicePrincipal.""" + + USER = "user" + SERVICE_PRINCIPAL = "servicePrincipal" + + +class AccessReviewScheduleDefinitionReviewersType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This field specifies the type of reviewers for a review. Usually for a review, reviewers are + explicitly assigned. However, in some cases, the reviewers may not be assigned and instead be + chosen dynamically. For example managers review or self review. + """ + + ASSIGNED = "Assigned" + SELF = "Self" + MANAGERS = "Managers" + + +class AccessReviewScheduleDefinitionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This read-only field specifies the status of an accessReview.""" + + NOT_STARTED = "NotStarted" + IN_PROGRESS = "InProgress" + COMPLETED = "Completed" + APPLIED = "Applied" + INITIALIZING = "Initializing" + APPLYING = "Applying" + COMPLETING = "Completing" + SCHEDULED = "Scheduled" + AUTO_REVIEWING = "AutoReviewing" + AUTO_REVIEWED = "AutoReviewed" + STARTING = "Starting" + + +class AccessReviewScopeAssignmentState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The role assignment state eligible/active to review.""" + + ELIGIBLE = "eligible" + ACTIVE = "active" + + +class AccessReviewScopePrincipalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type user/servicePrincipal to review.""" + + USER = "user" + GUEST_USER = "guestUser" + SERVICE_PRINCIPAL = "servicePrincipal" + USER_GROUP = "user,group" + REDEEMED_GUEST_USER = "redeemedGuestUser" + + +class DecisionResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of resource.""" + + AZURE_ROLE = "azureRole" + + +class DecisionTargetType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of decision target : User/ServicePrincipal.""" + + USER = "user" + SERVICE_PRINCIPAL = "servicePrincipal" + + +class DefaultDecisionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This specifies the behavior for the autoReview feature when an access review completes.""" + + APPROVE = "Approve" + DENY = "Deny" + RECOMMENDATION = "Recommendation" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_models_py3.py new file mode 100644 index 00000000000..cf216148920 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_models_py3.py @@ -0,0 +1,2041 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class AccessReviewContactedReviewer(_serialization.Model): + """Access Review Contacted Reviewer. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review reviewer id. + :vartype id: str + :ivar name: The access review reviewer id. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar user_display_name: The display name of the reviewer. + :vartype user_display_name: str + :ivar user_principal_name: The user principal name of the reviewer. + :vartype user_principal_name: str + :ivar created_date_time: Date Time when the reviewer was contacted. + :vartype created_date_time: ~datetime.datetime + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "user_display_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, + "created_date_time": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "user_display_name": {"key": "properties.userDisplayName", "type": "str"}, + "user_principal_name": {"key": "properties.userPrincipalName", "type": "str"}, + "created_date_time": {"key": "properties.createdDateTime", "type": "iso-8601"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.user_display_name = None + self.user_principal_name = None + self.created_date_time = None + + +class AccessReviewContactedReviewerListResult(_serialization.Model): + """List of access review contacted reviewers. + + :ivar value: Access Review Contacted Reviewer. + :vartype value: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewContactedReviewer] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AccessReviewContactedReviewer]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.AccessReviewContactedReviewer"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Access Review Contacted Reviewer. + :paramtype value: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewContactedReviewer] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AccessReviewDecision(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Access Review. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review decision id. + :vartype id: str + :ivar name: The access review decision name. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar recommendation: The feature- generated recommendation shown to the reviewer. Known values + are: "Approve", "Deny", and "NoInfoAvailable". + :vartype recommendation: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessRecommendationType + :ivar decision: The decision on the approval step. This value is initially set to NotReviewed. + Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", "NotReviewed", + "DontKnow", and "NotNotified". + :vartype decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewResult + :ivar justification: Justification provided by approvers for their action. + :vartype justification: str + :ivar reviewed_date_time: Date Time when a decision was taken. + :vartype reviewed_date_time: ~datetime.datetime + :ivar apply_result: The outcome of applying the decision. Known values are: "New", "Applying", + "AppliedSuccessfully", "AppliedWithUnknownFailure", "AppliedSuccessfullyButObjectNotFound", and + "ApplyNotSupported". + :vartype apply_result: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewApplyResult + :ivar applied_date_time: The date and time when the review decision was applied. + :vartype applied_date_time: ~datetime.datetime + :ivar principal_id_properties_applied_by_principal_id: The identity id. + :vartype principal_id_properties_applied_by_principal_id: str + :ivar principal_type_properties_applied_by_principal_type: The identity type : + user/servicePrincipal. Known values are: "user" and "servicePrincipal". + :vartype principal_type_properties_applied_by_principal_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name_properties_applied_by_principal_name: The identity display name. + :vartype principal_name_properties_applied_by_principal_name: str + :ivar user_principal_name_properties_applied_by_user_principal_name: The user principal name(if + valid). + :vartype user_principal_name_properties_applied_by_user_principal_name: str + :ivar principal_id_properties_reviewed_by_principal_id: The identity id. + :vartype principal_id_properties_reviewed_by_principal_id: str + :ivar principal_type_properties_reviewed_by_principal_type: The identity type : + user/servicePrincipal. Known values are: "user" and "servicePrincipal". + :vartype principal_type_properties_reviewed_by_principal_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name_properties_reviewed_by_principal_name: The identity display name. + :vartype principal_name_properties_reviewed_by_principal_name: str + :ivar user_principal_name_properties_reviewed_by_user_principal_name: The user principal + name(if valid). + :vartype user_principal_name_properties_reviewed_by_user_principal_name: str + :ivar type_properties_resource_type: The type of resource. "azureRole" + :vartype type_properties_resource_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DecisionResourceType + :ivar id_properties_resource_id: The id of resource associated with a decision record. + :vartype id_properties_resource_id: str + :ivar display_name_properties_resource_display_name: The display name of resource associated + with a decision record. + :vartype display_name_properties_resource_display_name: str + :ivar type_properties_principal_type: The type of decision target : User/ServicePrincipal. + Known values are: "user" and "servicePrincipal". + :vartype type_properties_principal_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DecisionTargetType + :ivar id_properties_principal_id: The id of principal whose access was reviewed. + :vartype id_properties_principal_id: str + :ivar display_name_properties_principal_display_name: The display name of the user whose access + was reviewed. + :vartype display_name_properties_principal_display_name: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "recommendation": {"readonly": True}, + "reviewed_date_time": {"readonly": True}, + "apply_result": {"readonly": True}, + "applied_date_time": {"readonly": True}, + "principal_id_properties_applied_by_principal_id": {"readonly": True}, + "principal_type_properties_applied_by_principal_type": {"readonly": True}, + "principal_name_properties_applied_by_principal_name": {"readonly": True}, + "user_principal_name_properties_applied_by_user_principal_name": {"readonly": True}, + "principal_id_properties_reviewed_by_principal_id": {"readonly": True}, + "principal_type_properties_reviewed_by_principal_type": {"readonly": True}, + "principal_name_properties_reviewed_by_principal_name": {"readonly": True}, + "user_principal_name_properties_reviewed_by_user_principal_name": {"readonly": True}, + "id_properties_resource_id": {"readonly": True}, + "display_name_properties_resource_display_name": {"readonly": True}, + "id_properties_principal_id": {"readonly": True}, + "display_name_properties_principal_display_name": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "recommendation": {"key": "properties.recommendation", "type": "str"}, + "decision": {"key": "properties.decision", "type": "str"}, + "justification": {"key": "properties.justification", "type": "str"}, + "reviewed_date_time": {"key": "properties.reviewedDateTime", "type": "iso-8601"}, + "apply_result": {"key": "properties.applyResult", "type": "str"}, + "applied_date_time": {"key": "properties.appliedDateTime", "type": "iso-8601"}, + "principal_id_properties_applied_by_principal_id": {"key": "properties.appliedBy.principalId", "type": "str"}, + "principal_type_properties_applied_by_principal_type": { + "key": "properties.appliedBy.principalType", + "type": "str", + }, + "principal_name_properties_applied_by_principal_name": { + "key": "properties.appliedBy.principalName", + "type": "str", + }, + "user_principal_name_properties_applied_by_user_principal_name": { + "key": "properties.appliedBy.userPrincipalName", + "type": "str", + }, + "principal_id_properties_reviewed_by_principal_id": {"key": "properties.reviewedBy.principalId", "type": "str"}, + "principal_type_properties_reviewed_by_principal_type": { + "key": "properties.reviewedBy.principalType", + "type": "str", + }, + "principal_name_properties_reviewed_by_principal_name": { + "key": "properties.reviewedBy.principalName", + "type": "str", + }, + "user_principal_name_properties_reviewed_by_user_principal_name": { + "key": "properties.reviewedBy.userPrincipalName", + "type": "str", + }, + "type_properties_resource_type": {"key": "properties.resource.type", "type": "str"}, + "id_properties_resource_id": {"key": "properties.resource.id", "type": "str"}, + "display_name_properties_resource_display_name": {"key": "properties.resource.displayName", "type": "str"}, + "type_properties_principal_type": {"key": "properties.principal.type", "type": "str"}, + "id_properties_principal_id": {"key": "properties.principal.id", "type": "str"}, + "display_name_properties_principal_display_name": {"key": "properties.principal.displayName", "type": "str"}, + } + + def __init__( + self, + *, + decision: Optional[Union[str, "_models.AccessReviewResult"]] = None, + justification: Optional[str] = None, + **kwargs + ): + """ + :keyword decision: The decision on the approval step. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + "NotReviewed", "DontKnow", and "NotNotified". + :paramtype decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewResult + :keyword justification: Justification provided by approvers for their action. + :paramtype justification: str + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.recommendation = None + self.decision = decision + self.justification = justification + self.reviewed_date_time = None + self.apply_result = None + self.applied_date_time = None + self.principal_id_properties_applied_by_principal_id = None + self.principal_type_properties_applied_by_principal_type = None + self.principal_name_properties_applied_by_principal_name = None + self.user_principal_name_properties_applied_by_user_principal_name = None + self.principal_id_properties_reviewed_by_principal_id = None + self.principal_type_properties_reviewed_by_principal_type = None + self.principal_name_properties_reviewed_by_principal_name = None + self.user_principal_name_properties_reviewed_by_user_principal_name = None + self.type_properties_resource_type = None # type: Optional[str] + self.id_properties_resource_id = None + self.display_name_properties_resource_display_name = None + self.type_properties_principal_type = None # type: Optional[str] + self.id_properties_principal_id = None + self.display_name_properties_principal_display_name = None + + +class AccessReviewDecisionIdentity(_serialization.Model): + """Target of the decision. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AccessReviewDecisionServicePrincipalIdentity, AccessReviewDecisionUserIdentity + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2021_07_01_preview.models.DecisionTargetType + :ivar id: The id of principal whose access was reviewed. + :vartype id: str + :ivar display_name: The display name of the user whose access was reviewed. + :vartype display_name: str + """ + + _validation = { + "type": {"required": True}, + "id": {"readonly": True}, + "display_name": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + } + + _subtype_map = { + "type": { + "servicePrincipal": "AccessReviewDecisionServicePrincipalIdentity", + "user": "AccessReviewDecisionUserIdentity", + } + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = None # type: Optional[str] + self.id = None + self.display_name = None + + +class AccessReviewDecisionListResult(_serialization.Model): + """List of access review decisions. + + :ivar value: Access Review Decision list. + :vartype value: list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AccessReviewDecision]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.AccessReviewDecision"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: Access Review Decision list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AccessReviewDecisionProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Approval Step. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar recommendation: The feature- generated recommendation shown to the reviewer. Known values + are: "Approve", "Deny", and "NoInfoAvailable". + :vartype recommendation: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessRecommendationType + :ivar decision: The decision on the approval step. This value is initially set to NotReviewed. + Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", "NotReviewed", + "DontKnow", and "NotNotified". + :vartype decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewResult + :ivar justification: Justification provided by approvers for their action. + :vartype justification: str + :ivar reviewed_date_time: Date Time when a decision was taken. + :vartype reviewed_date_time: ~datetime.datetime + :ivar apply_result: The outcome of applying the decision. Known values are: "New", "Applying", + "AppliedSuccessfully", "AppliedWithUnknownFailure", "AppliedSuccessfullyButObjectNotFound", and + "ApplyNotSupported". + :vartype apply_result: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewApplyResult + :ivar applied_date_time: The date and time when the review decision was applied. + :vartype applied_date_time: ~datetime.datetime + :ivar principal_id_applied_by_principal_id: The identity id. + :vartype principal_id_applied_by_principal_id: str + :ivar principal_type_applied_by_principal_type: The identity type : user/servicePrincipal. + Known values are: "user" and "servicePrincipal". + :vartype principal_type_applied_by_principal_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name_applied_by_principal_name: The identity display name. + :vartype principal_name_applied_by_principal_name: str + :ivar user_principal_name_applied_by_user_principal_name: The user principal name(if valid). + :vartype user_principal_name_applied_by_user_principal_name: str + :ivar principal_id_reviewed_by_principal_id: The identity id. + :vartype principal_id_reviewed_by_principal_id: str + :ivar principal_type_reviewed_by_principal_type: The identity type : user/servicePrincipal. + Known values are: "user" and "servicePrincipal". + :vartype principal_type_reviewed_by_principal_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name_reviewed_by_principal_name: The identity display name. + :vartype principal_name_reviewed_by_principal_name: str + :ivar user_principal_name_reviewed_by_user_principal_name: The user principal name(if valid). + :vartype user_principal_name_reviewed_by_user_principal_name: str + :ivar type_resource_type: The type of resource. "azureRole" + :vartype type_resource_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DecisionResourceType + :ivar id_resource_id: The id of resource associated with a decision record. + :vartype id_resource_id: str + :ivar display_name_resource_display_name: The display name of resource associated with a + decision record. + :vartype display_name_resource_display_name: str + :ivar type_principal_type: The type of decision target : User/ServicePrincipal. Known values + are: "user" and "servicePrincipal". + :vartype type_principal_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DecisionTargetType + :ivar id_principal_id: The id of principal whose access was reviewed. + :vartype id_principal_id: str + :ivar display_name_principal_display_name: The display name of the user whose access was + reviewed. + :vartype display_name_principal_display_name: str + """ + + _validation = { + "recommendation": {"readonly": True}, + "reviewed_date_time": {"readonly": True}, + "apply_result": {"readonly": True}, + "applied_date_time": {"readonly": True}, + "principal_id_applied_by_principal_id": {"readonly": True}, + "principal_type_applied_by_principal_type": {"readonly": True}, + "principal_name_applied_by_principal_name": {"readonly": True}, + "user_principal_name_applied_by_user_principal_name": {"readonly": True}, + "principal_id_reviewed_by_principal_id": {"readonly": True}, + "principal_type_reviewed_by_principal_type": {"readonly": True}, + "principal_name_reviewed_by_principal_name": {"readonly": True}, + "user_principal_name_reviewed_by_user_principal_name": {"readonly": True}, + "id_resource_id": {"readonly": True}, + "display_name_resource_display_name": {"readonly": True}, + "id_principal_id": {"readonly": True}, + "display_name_principal_display_name": {"readonly": True}, + } + + _attribute_map = { + "recommendation": {"key": "recommendation", "type": "str"}, + "decision": {"key": "decision", "type": "str"}, + "justification": {"key": "justification", "type": "str"}, + "reviewed_date_time": {"key": "reviewedDateTime", "type": "iso-8601"}, + "apply_result": {"key": "applyResult", "type": "str"}, + "applied_date_time": {"key": "appliedDateTime", "type": "iso-8601"}, + "principal_id_applied_by_principal_id": {"key": "appliedBy.principalId", "type": "str"}, + "principal_type_applied_by_principal_type": {"key": "appliedBy.principalType", "type": "str"}, + "principal_name_applied_by_principal_name": {"key": "appliedBy.principalName", "type": "str"}, + "user_principal_name_applied_by_user_principal_name": {"key": "appliedBy.userPrincipalName", "type": "str"}, + "principal_id_reviewed_by_principal_id": {"key": "reviewedBy.principalId", "type": "str"}, + "principal_type_reviewed_by_principal_type": {"key": "reviewedBy.principalType", "type": "str"}, + "principal_name_reviewed_by_principal_name": {"key": "reviewedBy.principalName", "type": "str"}, + "user_principal_name_reviewed_by_user_principal_name": {"key": "reviewedBy.userPrincipalName", "type": "str"}, + "type_resource_type": {"key": "resource.type", "type": "str"}, + "id_resource_id": {"key": "resource.id", "type": "str"}, + "display_name_resource_display_name": {"key": "resource.displayName", "type": "str"}, + "type_principal_type": {"key": "principal.type", "type": "str"}, + "id_principal_id": {"key": "principal.id", "type": "str"}, + "display_name_principal_display_name": {"key": "principal.displayName", "type": "str"}, + } + + def __init__( + self, + *, + decision: Optional[Union[str, "_models.AccessReviewResult"]] = None, + justification: Optional[str] = None, + **kwargs + ): + """ + :keyword decision: The decision on the approval step. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + "NotReviewed", "DontKnow", and "NotNotified". + :paramtype decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewResult + :keyword justification: Justification provided by approvers for their action. + :paramtype justification: str + """ + super().__init__(**kwargs) + self.recommendation = None + self.decision = decision + self.justification = justification + self.reviewed_date_time = None + self.apply_result = None + self.applied_date_time = None + self.principal_id_applied_by_principal_id = None + self.principal_type_applied_by_principal_type = None + self.principal_name_applied_by_principal_name = None + self.user_principal_name_applied_by_user_principal_name = None + self.principal_id_reviewed_by_principal_id = None + self.principal_type_reviewed_by_principal_type = None + self.principal_name_reviewed_by_principal_name = None + self.user_principal_name_reviewed_by_user_principal_name = None + self.type_resource_type = None # type: Optional[str] + self.id_resource_id = None + self.display_name_resource_display_name = None + self.type_principal_type = None # type: Optional[str] + self.id_principal_id = None + self.display_name_principal_display_name = None + + +class AccessReviewDecisionResource(_serialization.Model): + """Target of the decision. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of resource. Required. "azureRole" + :vartype type: str or ~azure.mgmt.authorization.v2021_07_01_preview.models.DecisionResourceType + :ivar id: The id of resource associated with a decision record. + :vartype id: str + :ivar display_name: The display name of resource associated with a decision record. + :vartype display_name: str + """ + + _validation = { + "type": {"required": True}, + "id": {"readonly": True}, + "display_name": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = None # type: Optional[str] + self.id = None + self.display_name = None + + +class AccessReviewDecisionServicePrincipalIdentity(AccessReviewDecisionIdentity): + """Service Principal Decision Target. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2021_07_01_preview.models.DecisionTargetType + :ivar id: The id of principal whose access was reviewed. + :vartype id: str + :ivar display_name: The display name of the user whose access was reviewed. + :vartype display_name: str + :ivar app_id: The appId for the service principal entity being reviewed. + :vartype app_id: str + """ + + _validation = { + "type": {"required": True}, + "id": {"readonly": True}, + "display_name": {"readonly": True}, + "app_id": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "app_id": {"key": "appId", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = "servicePrincipal" # type: str + self.app_id = None + + +class AccessReviewDecisionUserIdentity(AccessReviewDecisionIdentity): + """User Decision Target. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2021_07_01_preview.models.DecisionTargetType + :ivar id: The id of principal whose access was reviewed. + :vartype id: str + :ivar display_name: The display name of the user whose access was reviewed. + :vartype display_name: str + :ivar user_principal_name: The user principal name of the user whose access was reviewed. + :vartype user_principal_name: str + """ + + _validation = { + "type": {"required": True}, + "id": {"readonly": True}, + "display_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "user_principal_name": {"key": "userPrincipalName", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = "user" # type: str + self.user_principal_name = None + + +class AccessReviewDefaultSettings(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Access Review Default Settings. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review default settings id. This is only going to be default. + :vartype id: str + :ivar name: The access review default settings name. This is always going to be Access Review + Default Settings. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + review creator is enabled. + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to + pass justification when recording a decision. + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DefaultDecisionType + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar recommendation_look_back_duration: Recommendations for access reviews are calculated by + looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :vartype recommendation_look_back_duration: ~datetime.timedelta + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_properties_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_properties_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrenceRangeType + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date + in the future. Required on create. + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :vartype type_properties_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrencePatternType + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "mail_notifications_enabled": {"key": "properties.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "properties.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "properties.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "properties.justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "properties.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "properties.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "properties.recommendationsEnabled", "type": "bool"}, + "recommendation_look_back_duration": {"key": "properties.recommendationLookBackDuration", "type": "duration"}, + "instance_duration_in_days": {"key": "properties.instanceDurationInDays", "type": "int"}, + "type_properties_recurrence_range_type": {"key": "properties.recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "properties.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "properties.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.recurrence.range.endDate", "type": "iso-8601"}, + "type_properties_recurrence_pattern_type": {"key": "properties.recurrence.pattern.type", "type": "str"}, + "interval": {"key": "properties.recurrence.pattern.interval", "type": "int"}, + } + + def __init__( + self, + *, + mail_notifications_enabled: Optional[bool] = None, + reminder_notifications_enabled: Optional[bool] = None, + default_decision_enabled: Optional[bool] = None, + justification_required_on_approval: Optional[bool] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, + auto_apply_decisions_enabled: Optional[bool] = None, + recommendations_enabled: Optional[bool] = None, + recommendation_look_back_duration: Optional[datetime.timedelta] = None, + instance_duration_in_days: Optional[int] = None, + type_properties_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, + number_of_occurrences: Optional[int] = None, + start_date: Optional[datetime.datetime] = None, + end_date: Optional[datetime.datetime] = None, + type_properties_recurrence_pattern_type: Optional[ + Union[str, "_models.AccessReviewRecurrencePatternType"] + ] = None, + interval: Optional[int] = None, + **kwargs + ): + """ + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword recommendation_look_back_duration: Recommendations for access reviews are calculated + by looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :paramtype recommendation_look_back_duration: ~datetime.timedelta + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_properties_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_properties_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :paramtype type_properties_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.mail_notifications_enabled = mail_notifications_enabled + self.reminder_notifications_enabled = reminder_notifications_enabled + self.default_decision_enabled = default_decision_enabled + self.justification_required_on_approval = justification_required_on_approval + self.default_decision = default_decision + self.auto_apply_decisions_enabled = auto_apply_decisions_enabled + self.recommendations_enabled = recommendations_enabled + self.recommendation_look_back_duration = recommendation_look_back_duration + self.instance_duration_in_days = instance_duration_in_days + self.type_properties_recurrence_range_type = type_properties_recurrence_range_type + self.number_of_occurrences = number_of_occurrences + self.start_date = start_date + self.end_date = end_date + self.type_properties_recurrence_pattern_type = type_properties_recurrence_pattern_type + self.interval = interval + + +class AccessReviewInstance(_serialization.Model): + """Access Review Instance. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review instance id. + :vartype id: str + :ivar name: The access review instance name. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar status: This read-only field specifies the status of an access review instance. Known + values are: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", + "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". + :vartype status: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstanceStatus + :ivar start_date_time: The DateTime when the review instance is scheduled to be start. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: The DateTime when the review instance is scheduled to end. + :vartype end_date_time: ~datetime.datetime + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :ivar backup_reviewers: This is the collection of backup reviewers. + :vartype backup_reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a + review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". + :vartype reviewers_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstanceReviewersType + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, + "reviewers": {"key": "properties.reviewers", "type": "[AccessReviewReviewer]"}, + "backup_reviewers": {"key": "properties.backupReviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "properties.reviewersType", "type": "str"}, + } + + def __init__( + self, + *, + start_date_time: Optional[datetime.datetime] = None, + end_date_time: Optional[datetime.datetime] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + backup_reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + **kwargs + ): + """ + :keyword start_date_time: The DateTime when the review instance is scheduled to be start. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: The DateTime when the review instance is scheduled to end. + :paramtype end_date_time: ~datetime.datetime + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :keyword backup_reviewers: This is the collection of backup reviewers. + :paramtype backup_reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.status = None + self.start_date_time = start_date_time + self.end_date_time = end_date_time + self.reviewers = reviewers + self.backup_reviewers = backup_reviewers + self.reviewers_type = None + + +class AccessReviewInstanceListResult(_serialization.Model): + """List of Access Review Instances. + + :ivar value: Access Review Instance list. + :vartype value: list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AccessReviewInstance]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.AccessReviewInstance"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: Access Review Instance list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AccessReviewInstanceProperties(_serialization.Model): + """Access Review Instance properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar status: This read-only field specifies the status of an access review instance. Known + values are: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", + "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". + :vartype status: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstanceStatus + :ivar start_date_time: The DateTime when the review instance is scheduled to be start. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: The DateTime when the review instance is scheduled to end. + :vartype end_date_time: ~datetime.datetime + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :ivar backup_reviewers: This is the collection of backup reviewers. + :vartype backup_reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a + review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". + :vartype reviewers_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstanceReviewersType + """ + + _validation = { + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + } + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + "start_date_time": {"key": "startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "endDateTime", "type": "iso-8601"}, + "reviewers": {"key": "reviewers", "type": "[AccessReviewReviewer]"}, + "backup_reviewers": {"key": "backupReviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "reviewersType", "type": "str"}, + } + + def __init__( + self, + *, + start_date_time: Optional[datetime.datetime] = None, + end_date_time: Optional[datetime.datetime] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + backup_reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + **kwargs + ): + """ + :keyword start_date_time: The DateTime when the review instance is scheduled to be start. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: The DateTime when the review instance is scheduled to end. + :paramtype end_date_time: ~datetime.datetime + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :keyword backup_reviewers: This is the collection of backup reviewers. + :paramtype backup_reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + """ + super().__init__(**kwargs) + self.status = None + self.start_date_time = start_date_time + self.end_date_time = end_date_time + self.reviewers = reviewers + self.backup_reviewers = backup_reviewers + self.reviewers_type = None + + +class AccessReviewReviewer(_serialization.Model): + """Descriptor for what needs to be reviewed. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The id of the reviewer(user/servicePrincipal). + :vartype principal_id: str + :ivar principal_type: The identity type : user/servicePrincipal. Known values are: "user" and + "servicePrincipal". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewerType + """ + + _validation = { + "principal_type": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "principal_type": {"key": "principalType", "type": "str"}, + } + + def __init__(self, *, principal_id: Optional[str] = None, **kwargs): + """ + :keyword principal_id: The id of the reviewer(user/servicePrincipal). + :paramtype principal_id: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.principal_type = None + + +class AccessReviewScheduleDefinition(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Access Review Schedule Definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review schedule definition id. + :vartype id: str + :ivar name: The access review schedule definition unique id. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar display_name: The display name for the schedule definition. + :vartype display_name: str + :ivar status: This read-only field specifies the status of an accessReview. Known values are: + "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", "Completing", + "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". + :vartype status: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinitionStatus + :ivar description_for_admins: The description provided by the access review creator and visible + to admins. + :vartype description_for_admins: str + :ivar description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :vartype description_for_reviewers: str + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :ivar backup_reviewers: This is the collection of backup reviewers. + :vartype backup_reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a + review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". + :vartype reviewers_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinitionReviewersType + :ivar instances: This is the collection of instances returned when one does an expand on it. + :vartype instances: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance] + :ivar resource_id: ResourceId in which this review is getting created. + :vartype resource_id: str + :ivar role_definition_id: This is used to indicate the role being reviewed. + :vartype role_definition_id: str + :ivar principal_type_properties_scope_principal_type: The identity type user/servicePrincipal + to review. Known values are: "user", "guestUser", "servicePrincipal", "user,group", and + "redeemedGuestUser". + :vartype principal_type_properties_scope_principal_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScopePrincipalType + :ivar assignment_state: The role assignment state eligible/active to review. Known values are: + "eligible" and "active". + :vartype assignment_state: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScopeAssignmentState + :ivar inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :vartype inactive_duration: ~datetime.timedelta + :ivar expand_nested_memberships: Flag to indicate whether to expand nested memberships or not. + :vartype expand_nested_memberships: bool + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + review creator is enabled. + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to + pass justification when recording a decision. + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DefaultDecisionType + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar recommendation_look_back_duration: Recommendations for access reviews are calculated by + looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :vartype recommendation_look_back_duration: ~datetime.timedelta + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_properties_settings_recurrence_range_type: The recurrence range type. The possible + values are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_properties_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrenceRangeType + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date + in the future. Required on create. + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, + etc. Known values are: "weekly" and "absoluteMonthly". + :vartype type_properties_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrencePatternType + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int + :ivar principal_id: The identity id. + :vartype principal_id: str + :ivar principal_type_properties_created_by_principal_type: The identity type : + user/servicePrincipal. Known values are: "user" and "servicePrincipal". + :vartype principal_type_properties_created_by_principal_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name: The identity display name. + :vartype principal_name: str + :ivar user_principal_name: The user principal name(if valid). + :vartype user_principal_name: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + "resource_id": {"readonly": True}, + "role_definition_id": {"readonly": True}, + "principal_type_properties_scope_principal_type": {"readonly": True}, + "assignment_state": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type_properties_created_by_principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "description_for_admins": {"key": "properties.descriptionForAdmins", "type": "str"}, + "description_for_reviewers": {"key": "properties.descriptionForReviewers", "type": "str"}, + "reviewers": {"key": "properties.reviewers", "type": "[AccessReviewReviewer]"}, + "backup_reviewers": {"key": "properties.backupReviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "properties.reviewersType", "type": "str"}, + "instances": {"key": "properties.instances", "type": "[AccessReviewInstance]"}, + "resource_id": {"key": "properties.scope.resourceId", "type": "str"}, + "role_definition_id": {"key": "properties.scope.roleDefinitionId", "type": "str"}, + "principal_type_properties_scope_principal_type": {"key": "properties.scope.principalType", "type": "str"}, + "assignment_state": {"key": "properties.scope.assignmentState", "type": "str"}, + "inactive_duration": {"key": "properties.scope.inactiveDuration", "type": "duration"}, + "expand_nested_memberships": {"key": "properties.scope.expandNestedMemberships", "type": "bool"}, + "mail_notifications_enabled": {"key": "properties.settings.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "properties.settings.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "properties.settings.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": { + "key": "properties.settings.justificationRequiredOnApproval", + "type": "bool", + }, + "default_decision": {"key": "properties.settings.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "properties.settings.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "properties.settings.recommendationsEnabled", "type": "bool"}, + "recommendation_look_back_duration": { + "key": "properties.settings.recommendationLookBackDuration", + "type": "duration", + }, + "instance_duration_in_days": {"key": "properties.settings.instanceDurationInDays", "type": "int"}, + "type_properties_settings_recurrence_range_type": { + "key": "properties.settings.recurrence.range.type", + "type": "str", + }, + "number_of_occurrences": {"key": "properties.settings.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "properties.settings.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.settings.recurrence.range.endDate", "type": "iso-8601"}, + "type_properties_settings_recurrence_pattern_type": { + "key": "properties.settings.recurrence.pattern.type", + "type": "str", + }, + "interval": {"key": "properties.settings.recurrence.pattern.interval", "type": "int"}, + "principal_id": {"key": "properties.createdBy.principalId", "type": "str"}, + "principal_type_properties_created_by_principal_type": { + "key": "properties.createdBy.principalType", + "type": "str", + }, + "principal_name": {"key": "properties.createdBy.principalName", "type": "str"}, + "user_principal_name": {"key": "properties.createdBy.userPrincipalName", "type": "str"}, + } + + def __init__( # pylint: disable=too-many-locals + self, + *, + display_name: Optional[str] = None, + description_for_admins: Optional[str] = None, + description_for_reviewers: Optional[str] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + backup_reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + instances: Optional[List["_models.AccessReviewInstance"]] = None, + inactive_duration: Optional[datetime.timedelta] = None, + expand_nested_memberships: Optional[bool] = None, + mail_notifications_enabled: Optional[bool] = None, + reminder_notifications_enabled: Optional[bool] = None, + default_decision_enabled: Optional[bool] = None, + justification_required_on_approval: Optional[bool] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, + auto_apply_decisions_enabled: Optional[bool] = None, + recommendations_enabled: Optional[bool] = None, + recommendation_look_back_duration: Optional[datetime.timedelta] = None, + instance_duration_in_days: Optional[int] = None, + type_properties_settings_recurrence_range_type: Optional[ + Union[str, "_models.AccessReviewRecurrenceRangeType"] + ] = None, + number_of_occurrences: Optional[int] = None, + start_date: Optional[datetime.datetime] = None, + end_date: Optional[datetime.datetime] = None, + type_properties_settings_recurrence_pattern_type: Optional[ + Union[str, "_models.AccessReviewRecurrencePatternType"] + ] = None, + interval: Optional[int] = None, + **kwargs + ): + """ + :keyword display_name: The display name for the schedule definition. + :paramtype display_name: str + :keyword description_for_admins: The description provided by the access review creator and + visible to admins. + :paramtype description_for_admins: str + :keyword description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :paramtype description_for_reviewers: str + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :keyword backup_reviewers: This is the collection of backup reviewers. + :paramtype backup_reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :keyword instances: This is the collection of instances returned when one does an expand on it. + :paramtype instances: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance] + :keyword inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :paramtype inactive_duration: ~datetime.timedelta + :keyword expand_nested_memberships: Flag to indicate whether to expand nested memberships or + not. + :paramtype expand_nested_memberships: bool + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword recommendation_look_back_duration: Recommendations for access reviews are calculated + by looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :paramtype recommendation_look_back_duration: ~datetime.timedelta + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_properties_settings_recurrence_range_type: The recurrence range type. The + possible values are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and + "numbered". + :paramtype type_properties_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, + monthly, etc. Known values are: "weekly" and "absoluteMonthly". + :paramtype type_properties_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.display_name = display_name + self.status = None + self.description_for_admins = description_for_admins + self.description_for_reviewers = description_for_reviewers + self.reviewers = reviewers + self.backup_reviewers = backup_reviewers + self.reviewers_type = None + self.instances = instances + self.resource_id = None + self.role_definition_id = None + self.principal_type_properties_scope_principal_type = None + self.assignment_state = None + self.inactive_duration = inactive_duration + self.expand_nested_memberships = expand_nested_memberships + self.mail_notifications_enabled = mail_notifications_enabled + self.reminder_notifications_enabled = reminder_notifications_enabled + self.default_decision_enabled = default_decision_enabled + self.justification_required_on_approval = justification_required_on_approval + self.default_decision = default_decision + self.auto_apply_decisions_enabled = auto_apply_decisions_enabled + self.recommendations_enabled = recommendations_enabled + self.recommendation_look_back_duration = recommendation_look_back_duration + self.instance_duration_in_days = instance_duration_in_days + self.type_properties_settings_recurrence_range_type = type_properties_settings_recurrence_range_type + self.number_of_occurrences = number_of_occurrences + self.start_date = start_date + self.end_date = end_date + self.type_properties_settings_recurrence_pattern_type = type_properties_settings_recurrence_pattern_type + self.interval = interval + self.principal_id = None + self.principal_type_properties_created_by_principal_type = None + self.principal_name = None + self.user_principal_name = None + + +class AccessReviewScheduleDefinitionListResult(_serialization.Model): + """List of Access Review Schedule Definitions. + + :ivar value: Access Review Schedule Definition list. + :vartype value: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AccessReviewScheduleDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.AccessReviewScheduleDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Access Review Schedule Definition list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AccessReviewScheduleDefinitionProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Access Review. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar display_name: The display name for the schedule definition. + :vartype display_name: str + :ivar status: This read-only field specifies the status of an accessReview. Known values are: + "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", "Completing", + "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". + :vartype status: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinitionStatus + :ivar description_for_admins: The description provided by the access review creator and visible + to admins. + :vartype description_for_admins: str + :ivar description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :vartype description_for_reviewers: str + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :ivar backup_reviewers: This is the collection of backup reviewers. + :vartype backup_reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a + review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". + :vartype reviewers_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinitionReviewersType + :ivar instances: This is the collection of instances returned when one does an expand on it. + :vartype instances: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance] + :ivar resource_id: ResourceId in which this review is getting created. + :vartype resource_id: str + :ivar role_definition_id: This is used to indicate the role being reviewed. + :vartype role_definition_id: str + :ivar principal_type_scope_principal_type: The identity type user/servicePrincipal to review. + Known values are: "user", "guestUser", "servicePrincipal", "user,group", and + "redeemedGuestUser". + :vartype principal_type_scope_principal_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScopePrincipalType + :ivar assignment_state: The role assignment state eligible/active to review. Known values are: + "eligible" and "active". + :vartype assignment_state: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScopeAssignmentState + :ivar inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :vartype inactive_duration: ~datetime.timedelta + :ivar expand_nested_memberships: Flag to indicate whether to expand nested memberships or not. + :vartype expand_nested_memberships: bool + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + review creator is enabled. + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to + pass justification when recording a decision. + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DefaultDecisionType + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar recommendation_look_back_duration: Recommendations for access reviews are calculated by + looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :vartype recommendation_look_back_duration: ~datetime.timedelta + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_settings_recurrence_range_type: The recurrence range type. The possible values are: + endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrenceRangeType + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date + in the future. Required on create. + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known + values are: "weekly" and "absoluteMonthly". + :vartype type_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrencePatternType + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int + :ivar principal_id: The identity id. + :vartype principal_id: str + :ivar principal_type_created_by_principal_type: The identity type : user/servicePrincipal. + Known values are: "user" and "servicePrincipal". + :vartype principal_type_created_by_principal_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name: The identity display name. + :vartype principal_name: str + :ivar user_principal_name: The user principal name(if valid). + :vartype user_principal_name: str + """ + + _validation = { + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + "resource_id": {"readonly": True}, + "role_definition_id": {"readonly": True}, + "principal_type_scope_principal_type": {"readonly": True}, + "assignment_state": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type_created_by_principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, + } + + _attribute_map = { + "display_name": {"key": "displayName", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "description_for_admins": {"key": "descriptionForAdmins", "type": "str"}, + "description_for_reviewers": {"key": "descriptionForReviewers", "type": "str"}, + "reviewers": {"key": "reviewers", "type": "[AccessReviewReviewer]"}, + "backup_reviewers": {"key": "backupReviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "reviewersType", "type": "str"}, + "instances": {"key": "instances", "type": "[AccessReviewInstance]"}, + "resource_id": {"key": "scope.resourceId", "type": "str"}, + "role_definition_id": {"key": "scope.roleDefinitionId", "type": "str"}, + "principal_type_scope_principal_type": {"key": "scope.principalType", "type": "str"}, + "assignment_state": {"key": "scope.assignmentState", "type": "str"}, + "inactive_duration": {"key": "scope.inactiveDuration", "type": "duration"}, + "expand_nested_memberships": {"key": "scope.expandNestedMemberships", "type": "bool"}, + "mail_notifications_enabled": {"key": "settings.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "settings.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "settings.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "settings.justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "settings.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "settings.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "settings.recommendationsEnabled", "type": "bool"}, + "recommendation_look_back_duration": {"key": "settings.recommendationLookBackDuration", "type": "duration"}, + "instance_duration_in_days": {"key": "settings.instanceDurationInDays", "type": "int"}, + "type_settings_recurrence_range_type": {"key": "settings.recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "settings.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "settings.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "settings.recurrence.range.endDate", "type": "iso-8601"}, + "type_settings_recurrence_pattern_type": {"key": "settings.recurrence.pattern.type", "type": "str"}, + "interval": {"key": "settings.recurrence.pattern.interval", "type": "int"}, + "principal_id": {"key": "createdBy.principalId", "type": "str"}, + "principal_type_created_by_principal_type": {"key": "createdBy.principalType", "type": "str"}, + "principal_name": {"key": "createdBy.principalName", "type": "str"}, + "user_principal_name": {"key": "createdBy.userPrincipalName", "type": "str"}, + } + + def __init__( # pylint: disable=too-many-locals + self, + *, + display_name: Optional[str] = None, + description_for_admins: Optional[str] = None, + description_for_reviewers: Optional[str] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + backup_reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + instances: Optional[List["_models.AccessReviewInstance"]] = None, + inactive_duration: Optional[datetime.timedelta] = None, + expand_nested_memberships: Optional[bool] = None, + mail_notifications_enabled: Optional[bool] = None, + reminder_notifications_enabled: Optional[bool] = None, + default_decision_enabled: Optional[bool] = None, + justification_required_on_approval: Optional[bool] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, + auto_apply_decisions_enabled: Optional[bool] = None, + recommendations_enabled: Optional[bool] = None, + recommendation_look_back_duration: Optional[datetime.timedelta] = None, + instance_duration_in_days: Optional[int] = None, + type_settings_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, + number_of_occurrences: Optional[int] = None, + start_date: Optional[datetime.datetime] = None, + end_date: Optional[datetime.datetime] = None, + type_settings_recurrence_pattern_type: Optional[Union[str, "_models.AccessReviewRecurrencePatternType"]] = None, + interval: Optional[int] = None, + **kwargs + ): + """ + :keyword display_name: The display name for the schedule definition. + :paramtype display_name: str + :keyword description_for_admins: The description provided by the access review creator and + visible to admins. + :paramtype description_for_admins: str + :keyword description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :paramtype description_for_reviewers: str + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :keyword backup_reviewers: This is the collection of backup reviewers. + :paramtype backup_reviewers: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewReviewer] + :keyword instances: This is the collection of instances returned when one does an expand on it. + :paramtype instances: + list[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance] + :keyword inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :paramtype inactive_duration: ~datetime.timedelta + :keyword expand_nested_memberships: Flag to indicate whether to expand nested memberships or + not. + :paramtype expand_nested_memberships: bool + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword recommendation_look_back_duration: Recommendations for access reviews are calculated + by looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :paramtype recommendation_look_back_duration: ~datetime.timedelta + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_settings_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :paramtype type_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) + self.display_name = display_name + self.status = None + self.description_for_admins = description_for_admins + self.description_for_reviewers = description_for_reviewers + self.reviewers = reviewers + self.backup_reviewers = backup_reviewers + self.reviewers_type = None + self.instances = instances + self.resource_id = None + self.role_definition_id = None + self.principal_type_scope_principal_type = None + self.assignment_state = None + self.inactive_duration = inactive_duration + self.expand_nested_memberships = expand_nested_memberships + self.mail_notifications_enabled = mail_notifications_enabled + self.reminder_notifications_enabled = reminder_notifications_enabled + self.default_decision_enabled = default_decision_enabled + self.justification_required_on_approval = justification_required_on_approval + self.default_decision = default_decision + self.auto_apply_decisions_enabled = auto_apply_decisions_enabled + self.recommendations_enabled = recommendations_enabled + self.recommendation_look_back_duration = recommendation_look_back_duration + self.instance_duration_in_days = instance_duration_in_days + self.type_settings_recurrence_range_type = type_settings_recurrence_range_type + self.number_of_occurrences = number_of_occurrences + self.start_date = start_date + self.end_date = end_date + self.type_settings_recurrence_pattern_type = type_settings_recurrence_pattern_type + self.interval = interval + self.principal_id = None + self.principal_type_created_by_principal_type = None + self.principal_name = None + self.user_principal_name = None + + +class AccessReviewScheduleSettings(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Settings of an Access Review. + + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + review creator is enabled. + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to + pass justification when recording a decision. + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DefaultDecisionType + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar recommendation_look_back_duration: Recommendations for access reviews are calculated by + looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :vartype recommendation_look_back_duration: ~datetime.timedelta + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_recurrence_range_type: The recurrence range type. The possible values are: endDate, + noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrenceRangeType + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date + in the future. Required on create. + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known values + are: "weekly" and "absoluteMonthly". + :vartype type_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrencePatternType + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int + """ + + _attribute_map = { + "mail_notifications_enabled": {"key": "mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "recommendationsEnabled", "type": "bool"}, + "recommendation_look_back_duration": {"key": "recommendationLookBackDuration", "type": "duration"}, + "instance_duration_in_days": {"key": "instanceDurationInDays", "type": "int"}, + "type_recurrence_range_type": {"key": "recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "recurrence.range.endDate", "type": "iso-8601"}, + "type_recurrence_pattern_type": {"key": "recurrence.pattern.type", "type": "str"}, + "interval": {"key": "recurrence.pattern.interval", "type": "int"}, + } + + def __init__( + self, + *, + mail_notifications_enabled: Optional[bool] = None, + reminder_notifications_enabled: Optional[bool] = None, + default_decision_enabled: Optional[bool] = None, + justification_required_on_approval: Optional[bool] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, + auto_apply_decisions_enabled: Optional[bool] = None, + recommendations_enabled: Optional[bool] = None, + recommendation_look_back_duration: Optional[datetime.timedelta] = None, + instance_duration_in_days: Optional[int] = None, + type_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, + number_of_occurrences: Optional[int] = None, + start_date: Optional[datetime.datetime] = None, + end_date: Optional[datetime.datetime] = None, + type_recurrence_pattern_type: Optional[Union[str, "_models.AccessReviewRecurrencePatternType"]] = None, + interval: Optional[int] = None, + **kwargs + ): + """ + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword recommendation_look_back_duration: Recommendations for access reviews are calculated + by looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :paramtype recommendation_look_back_duration: ~datetime.timedelta + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_recurrence_range_type: The recurrence range type. The possible values are: + endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known values + are: "weekly" and "absoluteMonthly". + :paramtype type_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) + self.mail_notifications_enabled = mail_notifications_enabled + self.reminder_notifications_enabled = reminder_notifications_enabled + self.default_decision_enabled = default_decision_enabled + self.justification_required_on_approval = justification_required_on_approval + self.default_decision = default_decision + self.auto_apply_decisions_enabled = auto_apply_decisions_enabled + self.recommendations_enabled = recommendations_enabled + self.recommendation_look_back_duration = recommendation_look_back_duration + self.instance_duration_in_days = instance_duration_in_days + self.type_recurrence_range_type = type_recurrence_range_type + self.number_of_occurrences = number_of_occurrences + self.start_date = start_date + self.end_date = end_date + self.type_recurrence_pattern_type = type_recurrence_pattern_type + self.interval = interval + + +class ErrorDefinition(_serialization.Model): + """Error description and code explaining why an operation failed. + + :ivar error: Error of the list gateway status. + :vartype error: ~azure.mgmt.authorization.v2021_07_01_preview.models.ErrorDefinitionProperties + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDefinitionProperties"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDefinitionProperties"] = None, **kwargs): + """ + :keyword error: Error of the list gateway status. + :paramtype error: + ~azure.mgmt.authorization.v2021_07_01_preview.models.ErrorDefinitionProperties + """ + super().__init__(**kwargs) + self.error = error + + +class ErrorDefinitionProperties(_serialization.Model): + """Error description and code explaining why an operation failed. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar message: Description of the error. + :vartype message: str + :ivar code: Error code of list gateway. + :vartype code: str + """ + + _validation = { + "message": {"readonly": True}, + } + + _attribute_map = { + "message": {"key": "message", "type": "str"}, + "code": {"key": "code", "type": "str"}, + } + + def __init__(self, *, code: Optional[str] = None, **kwargs): + """ + :keyword code: Error code of list gateway. + :paramtype code: str + """ + super().__init__(**kwargs) + self.message = None + self.code = code + + +class Operation(_serialization.Model): + """The definition of a Microsoft.Authorization operation. + + :ivar name: Name of the operation. + :vartype name: str + :ivar is_data_action: Indicates whether the operation is a data action. + :vartype is_data_action: bool + :ivar display: Display of the operation. + :vartype display: ~azure.mgmt.authorization.v2021_07_01_preview.models.OperationDisplay + :ivar origin: Origin of the operation. + :vartype origin: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + is_data_action: Optional[bool] = None, + display: Optional["_models.OperationDisplay"] = None, + origin: Optional[str] = None, + **kwargs + ): + """ + :keyword name: Name of the operation. + :paramtype name: str + :keyword is_data_action: Indicates whether the operation is a data action. + :paramtype is_data_action: bool + :keyword display: Display of the operation. + :paramtype display: ~azure.mgmt.authorization.v2021_07_01_preview.models.OperationDisplay + :keyword origin: Origin of the operation. + :paramtype origin: str + """ + super().__init__(**kwargs) + self.name = name + self.is_data_action = is_data_action + self.display = display + self.origin = origin + + +class OperationDisplay(_serialization.Model): + """The display information for a Microsoft.Authorization operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: The resource provider name: Microsoft.Authorization. + :vartype provider: str + :ivar resource: The resource on which the operation is performed. + :vartype resource: str + :ivar operation: The operation that users can perform. + :vartype operation: str + :ivar description: The description for the operation. + :vartype description: str + """ + + _validation = { + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, + } + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(_serialization.Model): + """The result of a request to list Microsoft.Authorization operations. + + :ivar value: The collection value. + :vartype value: list[~azure.mgmt.authorization.v2021_07_01_preview.models.Operation] + :ivar next_link: The URI that can be used to request the next set of paged results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs): + """ + :keyword value: The collection value. + :paramtype value: list[~azure.mgmt.authorization.v2021_07_01_preview.models.Operation] + :keyword next_link: The URI that can be used to request the next set of paged results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/__init__.py new file mode 100644 index 00000000000..58318912431 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/__init__.py @@ -0,0 +1,45 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import Operations +from ._access_review_schedule_definitions_operations import AccessReviewScheduleDefinitionsOperations +from ._access_review_instances_operations import AccessReviewInstancesOperations +from ._access_review_instance_operations import AccessReviewInstanceOperations +from ._access_review_instance_decisions_operations import AccessReviewInstanceDecisionsOperations +from ._access_review_instance_contacted_reviewers_operations import AccessReviewInstanceContactedReviewersOperations +from ._access_review_default_settings_operations import AccessReviewDefaultSettingsOperations +from ._access_review_schedule_definitions_assigned_for_my_approval_operations import ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, +) +from ._access_review_instances_assigned_for_my_approval_operations import ( + AccessReviewInstancesAssignedForMyApprovalOperations, +) +from ._access_review_instance_my_decisions_operations import AccessReviewInstanceMyDecisionsOperations +from ._tenant_level_access_review_instance_contacted_reviewers_operations import ( + TenantLevelAccessReviewInstanceContactedReviewersOperations, +) + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "AccessReviewScheduleDefinitionsOperations", + "AccessReviewInstancesOperations", + "AccessReviewInstanceOperations", + "AccessReviewInstanceDecisionsOperations", + "AccessReviewInstanceContactedReviewersOperations", + "AccessReviewDefaultSettingsOperations", + "AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations", + "AccessReviewInstancesAssignedForMyApprovalOperations", + "AccessReviewInstanceMyDecisionsOperations", + "TenantLevelAccessReviewInstanceContactedReviewersOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_default_settings_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_default_settings_operations.py new file mode 100644 index 00000000000..484bc54b7fe --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_default_settings_operations.py @@ -0,0 +1,273 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_put_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewDefaultSettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_default_settings` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, **kwargs: Any) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + request = build_get_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore + + @overload + def put( + self, properties: _models.AccessReviewScheduleSettings, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleSettings + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put( + self, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put( + self, properties: Union[_models.AccessReviewScheduleSettings, IO], **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleSettings or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleSettings") + + request = build_put_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + put.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_contacted_reviewers_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_contacted_reviewers_operations.py new file mode 100644 index 00000000000..8acb39896ba --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_contacted_reviewers_operations.py @@ -0,0 +1,168 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceContactedReviewersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance_contacted_reviewers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> Iterable["_models.AccessReviewContactedReviewer"]: + """Get access review instance contacted reviewers. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewContactedReviewer or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewContactedReviewer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewContactedReviewerListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewContactedReviewerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_decisions_operations.py new file mode 100644 index 00000000000..e7e4db26119 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_decisions_operations.py @@ -0,0 +1,178 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + schedule_definition_id: str, id: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance_decisions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewDecision"]: + """Get access review instance decisions. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_my_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_my_decisions_operations.py new file mode 100644 index 00000000000..1d47910242d --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_my_decisions_operations.py @@ -0,0 +1,448 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + schedule_definition_id: str, id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "decisionId": _SERIALIZER.url("decision_id", decision_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_patch_request(schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "decisionId": _SERIALIZER.url("decision_id", decision_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceMyDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance_my_decisions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewDecision"]: + """Get my access review instance decisions. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore + + @distributed_trace + def get_by_id( + self, schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any + ) -> _models.AccessReviewDecision: + """Get my single access review instance decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore + + @overload + def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: _models.AccessReviewDecisionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecisionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: Union[_models.AccessReviewDecisionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecisionProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewDecisionProperties") + + request = build_patch_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + patch.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_operations.py new file mode 100644 index 00000000000..6a2882f894f --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instance_operations.py @@ -0,0 +1,488 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_stop_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reset_decisions_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_apply_decisions_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_send_reminders_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_accept_recommendations_request(schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to stop an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop"} # type: ignore + + @distributed_trace + def reset_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to reset all decisions for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reset_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.reset_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + reset_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions"} # type: ignore + + @distributed_trace + def apply_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to apply all decisions for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_apply_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.apply_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + apply_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions"} # type: ignore + + @distributed_trace + def send_reminders( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to send reminders for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_send_reminders_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.send_reminders.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + send_reminders.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders"} # type: ignore + + @distributed_trace + def accept_recommendations( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to accept recommendations for decision in an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_accept_recommendations_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.accept_recommendations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + accept_recommendations.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py new file mode 100644 index 00000000000..12ac7d26e5b --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py @@ -0,0 +1,256 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(schedule_definition_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstancesAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instances_assigned_for_my_approval` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewInstance"]: + """Get access review instances assigned for my approval. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: + """Get single access review instance assigned for my approval. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instances_operations.py new file mode 100644 index 00000000000..7242fd35f82 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_instances_operations.py @@ -0,0 +1,433 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + schedule_definition_id: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewInstance"]: + """Get access review instances. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: + """Get access review instances. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore + + @overload + def create( + self, + schedule_definition_id: str, + id: str, + properties: _models.AccessReviewInstanceProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstanceProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + schedule_definition_id: str, + id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + schedule_definition_id: str, + id: str, + properties: Union[_models.AccessReviewInstanceProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstanceProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewInstanceProperties") + + request = build_create_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py new file mode 100644 index 00000000000..1cd2a71810c --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py @@ -0,0 +1,157 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(*, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions_assigned_for_my_approval` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.AccessReviewScheduleDefinition"]: + """Get access review instances assigned for my approval. + + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_schedule_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_schedule_definitions_operations.py new file mode 100644 index 00000000000..025df9b6ca7 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_access_review_schedule_definitions_operations.py @@ -0,0 +1,572 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_by_id_request( + schedule_definition_id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_stop_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewScheduleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.AccessReviewScheduleDefinition"]: + """Get access review schedule definitions. + + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, **kwargs: Any) -> _models.AccessReviewScheduleDefinition: + """Get single access review definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace + def delete_by_id( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Delete access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @overload + def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: _models.AccessReviewScheduleDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_by_id( + self, schedule_definition_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: Union[_models.AccessReviewScheduleDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinitionProperties + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleDefinitionProperties") + + request = build_create_or_update_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace + def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Stop access review definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_operations.py new file mode 100644 index 00000000000..3e67c27cbd0 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_operations.py @@ -0,0 +1,148 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.AuthorizationManagementClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: + """Lists the operations available from this provider. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py new file mode 100644 index 00000000000..2d1375870b0 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py @@ -0,0 +1,166 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class TenantLevelAccessReviewInstanceContactedReviewersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_07_01_preview.AuthorizationManagementClient`'s + :attr:`tenant_level_access_review_instance_contacted_reviewers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> Iterable["_models.AccessReviewContactedReviewer"]: + """Get access review instance contacted reviewers. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewContactedReviewer or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_07_01_preview.models.AccessReviewContactedReviewer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewContactedReviewerListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewContactedReviewerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/py.typed b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/py.typed new file mode 100644 index 00000000000..e5aff4f83af --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_07_01_preview/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/__init__.py new file mode 100644 index 00000000000..9eb8d3ec28c --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/__init__.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._authorization_management_client import AuthorizationManagementClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_authorization_management_client.py new file mode 100644 index 00000000000..d0e22addc8c --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_authorization_management_client.py @@ -0,0 +1,308 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + AccessReviewDefaultSettingsOperations, + AccessReviewHistoryDefinitionInstanceOperations, + AccessReviewHistoryDefinitionInstancesOperations, + AccessReviewHistoryDefinitionOperations, + AccessReviewHistoryDefinitionsOperations, + AccessReviewInstanceContactedReviewersOperations, + AccessReviewInstanceDecisionsOperations, + AccessReviewInstanceMyDecisionsOperations, + AccessReviewInstanceOperations, + AccessReviewInstancesAssignedForMyApprovalOperations, + AccessReviewInstancesOperations, + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, + AccessReviewScheduleDefinitionsOperations, + AlertConfigurationsOperations, + AlertDefinitionsOperations, + AlertIncidentsOperations, + AlertOperationOperations, + AlertsOperations, + Operations, + ScopeAccessReviewDefaultSettingsOperations, + ScopeAccessReviewHistoryDefinitionInstanceOperations, + ScopeAccessReviewHistoryDefinitionInstancesOperations, + ScopeAccessReviewHistoryDefinitionOperations, + ScopeAccessReviewHistoryDefinitionsOperations, + ScopeAccessReviewInstanceContactedReviewersOperations, + ScopeAccessReviewInstanceDecisionsOperations, + ScopeAccessReviewInstanceOperations, + ScopeAccessReviewInstancesOperations, + ScopeAccessReviewScheduleDefinitionsOperations, + TenantLevelAccessReviewInstanceContactedReviewersOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Access reviews service provides the workflow for running access reviews on different kind of + resources. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.authorization.v2021_12_01_preview.operations.Operations + :ivar access_review_history_definitions: AccessReviewHistoryDefinitionsOperations operations + :vartype access_review_history_definitions: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewHistoryDefinitionsOperations + :ivar access_review_history_definition: AccessReviewHistoryDefinitionOperations operations + :vartype access_review_history_definition: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewHistoryDefinitionOperations + :ivar access_review_history_definition_instance: + AccessReviewHistoryDefinitionInstanceOperations operations + :vartype access_review_history_definition_instance: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewHistoryDefinitionInstanceOperations + :ivar access_review_history_definition_instances: + AccessReviewHistoryDefinitionInstancesOperations operations + :vartype access_review_history_definition_instances: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewHistoryDefinitionInstancesOperations + :ivar access_review_schedule_definitions: AccessReviewScheduleDefinitionsOperations operations + :vartype access_review_schedule_definitions: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewScheduleDefinitionsOperations + :ivar access_review_instances: AccessReviewInstancesOperations operations + :vartype access_review_instances: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewInstancesOperations + :ivar access_review_instance: AccessReviewInstanceOperations operations + :vartype access_review_instance: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewInstanceOperations + :ivar access_review_instance_decisions: AccessReviewInstanceDecisionsOperations operations + :vartype access_review_instance_decisions: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewInstanceDecisionsOperations + :ivar access_review_instance_contacted_reviewers: + AccessReviewInstanceContactedReviewersOperations operations + :vartype access_review_instance_contacted_reviewers: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewInstanceContactedReviewersOperations + :ivar access_review_default_settings: AccessReviewDefaultSettingsOperations operations + :vartype access_review_default_settings: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewDefaultSettingsOperations + :ivar scope_access_review_history_definitions: ScopeAccessReviewHistoryDefinitionsOperations + operations + :vartype scope_access_review_history_definitions: + azure.mgmt.authorization.v2021_12_01_preview.operations.ScopeAccessReviewHistoryDefinitionsOperations + :ivar scope_access_review_history_definition: ScopeAccessReviewHistoryDefinitionOperations + operations + :vartype scope_access_review_history_definition: + azure.mgmt.authorization.v2021_12_01_preview.operations.ScopeAccessReviewHistoryDefinitionOperations + :ivar scope_access_review_history_definition_instance: + ScopeAccessReviewHistoryDefinitionInstanceOperations operations + :vartype scope_access_review_history_definition_instance: + azure.mgmt.authorization.v2021_12_01_preview.operations.ScopeAccessReviewHistoryDefinitionInstanceOperations + :ivar scope_access_review_history_definition_instances: + ScopeAccessReviewHistoryDefinitionInstancesOperations operations + :vartype scope_access_review_history_definition_instances: + azure.mgmt.authorization.v2021_12_01_preview.operations.ScopeAccessReviewHistoryDefinitionInstancesOperations + :ivar scope_access_review_schedule_definitions: ScopeAccessReviewScheduleDefinitionsOperations + operations + :vartype scope_access_review_schedule_definitions: + azure.mgmt.authorization.v2021_12_01_preview.operations.ScopeAccessReviewScheduleDefinitionsOperations + :ivar scope_access_review_instances: ScopeAccessReviewInstancesOperations operations + :vartype scope_access_review_instances: + azure.mgmt.authorization.v2021_12_01_preview.operations.ScopeAccessReviewInstancesOperations + :ivar scope_access_review_instance: ScopeAccessReviewInstanceOperations operations + :vartype scope_access_review_instance: + azure.mgmt.authorization.v2021_12_01_preview.operations.ScopeAccessReviewInstanceOperations + :ivar scope_access_review_instance_decisions: ScopeAccessReviewInstanceDecisionsOperations + operations + :vartype scope_access_review_instance_decisions: + azure.mgmt.authorization.v2021_12_01_preview.operations.ScopeAccessReviewInstanceDecisionsOperations + :ivar scope_access_review_instance_contacted_reviewers: + ScopeAccessReviewInstanceContactedReviewersOperations operations + :vartype scope_access_review_instance_contacted_reviewers: + azure.mgmt.authorization.v2021_12_01_preview.operations.ScopeAccessReviewInstanceContactedReviewersOperations + :ivar scope_access_review_default_settings: ScopeAccessReviewDefaultSettingsOperations + operations + :vartype scope_access_review_default_settings: + azure.mgmt.authorization.v2021_12_01_preview.operations.ScopeAccessReviewDefaultSettingsOperations + :ivar access_review_schedule_definitions_assigned_for_my_approval: + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations + :vartype access_review_schedule_definitions_assigned_for_my_approval: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations + :ivar access_review_instances_assigned_for_my_approval: + AccessReviewInstancesAssignedForMyApprovalOperations operations + :vartype access_review_instances_assigned_for_my_approval: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewInstancesAssignedForMyApprovalOperations + :ivar access_review_instance_my_decisions: AccessReviewInstanceMyDecisionsOperations operations + :vartype access_review_instance_my_decisions: + azure.mgmt.authorization.v2021_12_01_preview.operations.AccessReviewInstanceMyDecisionsOperations + :ivar tenant_level_access_review_instance_contacted_reviewers: + TenantLevelAccessReviewInstanceContactedReviewersOperations operations + :vartype tenant_level_access_review_instance_contacted_reviewers: + azure.mgmt.authorization.v2021_12_01_preview.operations.TenantLevelAccessReviewInstanceContactedReviewersOperations + :ivar alerts: AlertsOperations operations + :vartype alerts: azure.mgmt.authorization.v2021_12_01_preview.operations.AlertsOperations + :ivar alert_configurations: AlertConfigurationsOperations operations + :vartype alert_configurations: + azure.mgmt.authorization.v2021_12_01_preview.operations.AlertConfigurationsOperations + :ivar alert_definitions: AlertDefinitionsOperations operations + :vartype alert_definitions: + azure.mgmt.authorization.v2021_12_01_preview.operations.AlertDefinitionsOperations + :ivar alert_incidents: AlertIncidentsOperations operations + :vartype alert_incidents: + azure.mgmt.authorization.v2021_12_01_preview.operations.AlertIncidentsOperations + :ivar alert_operation: AlertOperationOperations operations + :vartype alert_operation: + azure.mgmt.authorization.v2021_12_01_preview.operations.AlertOperationOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.access_review_history_definitions = AccessReviewHistoryDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_history_definition = AccessReviewHistoryDefinitionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_history_definition_instance = AccessReviewHistoryDefinitionInstanceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_history_definition_instances = AccessReviewHistoryDefinitionInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_schedule_definitions = AccessReviewScheduleDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instances = AccessReviewInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance = AccessReviewInstanceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_decisions = AccessReviewInstanceDecisionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_contacted_reviewers = AccessReviewInstanceContactedReviewersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_default_settings = AccessReviewDefaultSettingsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_history_definitions = ScopeAccessReviewHistoryDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_history_definition = ScopeAccessReviewHistoryDefinitionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_history_definition_instance = ScopeAccessReviewHistoryDefinitionInstanceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_history_definition_instances = ScopeAccessReviewHistoryDefinitionInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_schedule_definitions = ScopeAccessReviewScheduleDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_instances = ScopeAccessReviewInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_instance = ScopeAccessReviewInstanceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_instance_decisions = ScopeAccessReviewInstanceDecisionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_instance_contacted_reviewers = ScopeAccessReviewInstanceContactedReviewersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_default_settings = ScopeAccessReviewDefaultSettingsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_schedule_definitions_assigned_for_my_approval = ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) + self.access_review_instances_assigned_for_my_approval = AccessReviewInstancesAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_my_decisions = AccessReviewInstanceMyDecisionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.tenant_level_access_review_instance_contacted_reviewers = ( + TenantLevelAccessReviewInstanceContactedReviewersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) + self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alert_configurations = AlertConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.alert_definitions = AlertDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.alert_incidents = AlertIncidentsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alert_operation = AlertOperationOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> AuthorizationManagementClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_configuration.py new file mode 100644 index 00000000000..6f0f7d89833 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_configuration.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for AuthorizationManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_metadata.json new file mode 100644 index 00000000000..96baefa219b --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_metadata.json @@ -0,0 +1,131 @@ +{ + "chosen_version": "2021-12-01-preview", + "total_api_version_list": ["2021-12-01-preview", "2022-08-01-preview"], + "client": { + "name": "AuthorizationManagementClient", + "filename": "_authorization_management_client", + "description": "Access reviews service provides the workflow for running access reviews on different kind of resources.", + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, + "azure_arm": true, + "has_lro_operations": true, + "client_side_validation": false, + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "global_parameters": { + "sync": { + "credential": { + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials.TokenCredential", + "required": true + }, + "subscription_id": { + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", + "docstring_type": "str", + "required": true + } + }, + "async": { + "credential": { + "signature": "credential: \"AsyncTokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", + "required": true + }, + "subscription_id": { + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", + "docstring_type": "str", + "required": true + } + }, + "constant": { + }, + "call": "credential, subscription_id", + "service_client_specific": { + "sync": { + "api_version": { + "signature": "api_version=None, # type: Optional[str]", + "description": "API version to use if no profile is provided, or if missing in profile.", + "docstring_type": "str", + "required": false + }, + "base_url": { + "signature": "base_url: str = \"https://management.azure.com\",", + "description": "Service URL", + "docstring_type": "str", + "required": false + }, + "profile": { + "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "description": "A profile definition, from KnownProfiles to dict.", + "docstring_type": "azure.profiles.KnownProfiles", + "required": false + } + }, + "async": { + "api_version": { + "signature": "api_version: Optional[str] = None,", + "description": "API version to use if no profile is provided, or if missing in profile.", + "docstring_type": "str", + "required": false + }, + "base_url": { + "signature": "base_url: str = \"https://management.azure.com\",", + "description": "Service URL", + "docstring_type": "str", + "required": false + }, + "profile": { + "signature": "profile: KnownProfiles = KnownProfiles.default,", + "description": "A profile definition, from KnownProfiles to dict.", + "docstring_type": "azure.profiles.KnownProfiles", + "required": false + } + } + } + }, + "config": { + "credential": true, + "credential_scopes": ["https://management.azure.com/.default"], + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "operation_groups": { + "operations": "Operations", + "access_review_history_definitions": "AccessReviewHistoryDefinitionsOperations", + "access_review_history_definition": "AccessReviewHistoryDefinitionOperations", + "access_review_history_definition_instance": "AccessReviewHistoryDefinitionInstanceOperations", + "access_review_history_definition_instances": "AccessReviewHistoryDefinitionInstancesOperations", + "access_review_schedule_definitions": "AccessReviewScheduleDefinitionsOperations", + "access_review_instances": "AccessReviewInstancesOperations", + "access_review_instance": "AccessReviewInstanceOperations", + "access_review_instance_decisions": "AccessReviewInstanceDecisionsOperations", + "access_review_instance_contacted_reviewers": "AccessReviewInstanceContactedReviewersOperations", + "access_review_default_settings": "AccessReviewDefaultSettingsOperations", + "scope_access_review_history_definitions": "ScopeAccessReviewHistoryDefinitionsOperations", + "scope_access_review_history_definition": "ScopeAccessReviewHistoryDefinitionOperations", + "scope_access_review_history_definition_instance": "ScopeAccessReviewHistoryDefinitionInstanceOperations", + "scope_access_review_history_definition_instances": "ScopeAccessReviewHistoryDefinitionInstancesOperations", + "scope_access_review_schedule_definitions": "ScopeAccessReviewScheduleDefinitionsOperations", + "scope_access_review_instances": "ScopeAccessReviewInstancesOperations", + "scope_access_review_instance": "ScopeAccessReviewInstanceOperations", + "scope_access_review_instance_decisions": "ScopeAccessReviewInstanceDecisionsOperations", + "scope_access_review_instance_contacted_reviewers": "ScopeAccessReviewInstanceContactedReviewersOperations", + "scope_access_review_default_settings": "ScopeAccessReviewDefaultSettingsOperations", + "access_review_schedule_definitions_assigned_for_my_approval": "AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations", + "access_review_instances_assigned_for_my_approval": "AccessReviewInstancesAssignedForMyApprovalOperations", + "access_review_instance_my_decisions": "AccessReviewInstanceMyDecisionsOperations", + "tenant_level_access_review_instance_contacted_reviewers": "TenantLevelAccessReviewInstanceContactedReviewersOperations", + "alerts": "AlertsOperations", + "alert_configurations": "AlertConfigurationsOperations", + "alert_definitions": "AlertDefinitionsOperations", + "alert_incidents": "AlertIncidentsOperations", + "alert_operation": "AlertOperationOperations" + } +} \ No newline at end of file diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_version.py new file mode 100644 index 00000000000..cac9f5d10f8 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/__init__.py new file mode 100644 index 00000000000..dd28625b36f --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._authorization_management_client import AuthorizationManagementClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_authorization_management_client.py new file mode 100644 index 00000000000..f5571412e0f --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_authorization_management_client.py @@ -0,0 +1,305 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + AccessReviewDefaultSettingsOperations, + AccessReviewHistoryDefinitionInstanceOperations, + AccessReviewHistoryDefinitionInstancesOperations, + AccessReviewHistoryDefinitionOperations, + AccessReviewHistoryDefinitionsOperations, + AccessReviewInstanceContactedReviewersOperations, + AccessReviewInstanceDecisionsOperations, + AccessReviewInstanceMyDecisionsOperations, + AccessReviewInstanceOperations, + AccessReviewInstancesAssignedForMyApprovalOperations, + AccessReviewInstancesOperations, + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, + AccessReviewScheduleDefinitionsOperations, + AlertConfigurationsOperations, + AlertDefinitionsOperations, + AlertIncidentsOperations, + AlertOperationOperations, + AlertsOperations, + Operations, + ScopeAccessReviewDefaultSettingsOperations, + ScopeAccessReviewHistoryDefinitionInstanceOperations, + ScopeAccessReviewHistoryDefinitionInstancesOperations, + ScopeAccessReviewHistoryDefinitionOperations, + ScopeAccessReviewHistoryDefinitionsOperations, + ScopeAccessReviewInstanceContactedReviewersOperations, + ScopeAccessReviewInstanceDecisionsOperations, + ScopeAccessReviewInstanceOperations, + ScopeAccessReviewInstancesOperations, + ScopeAccessReviewScheduleDefinitionsOperations, + TenantLevelAccessReviewInstanceContactedReviewersOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Access reviews service provides the workflow for running access reviews on different kind of + resources. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.authorization.v2021_12_01_preview.aio.operations.Operations + :ivar access_review_history_definitions: AccessReviewHistoryDefinitionsOperations operations + :vartype access_review_history_definitions: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewHistoryDefinitionsOperations + :ivar access_review_history_definition: AccessReviewHistoryDefinitionOperations operations + :vartype access_review_history_definition: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewHistoryDefinitionOperations + :ivar access_review_history_definition_instance: + AccessReviewHistoryDefinitionInstanceOperations operations + :vartype access_review_history_definition_instance: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewHistoryDefinitionInstanceOperations + :ivar access_review_history_definition_instances: + AccessReviewHistoryDefinitionInstancesOperations operations + :vartype access_review_history_definition_instances: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewHistoryDefinitionInstancesOperations + :ivar access_review_schedule_definitions: AccessReviewScheduleDefinitionsOperations operations + :vartype access_review_schedule_definitions: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewScheduleDefinitionsOperations + :ivar access_review_instances: AccessReviewInstancesOperations operations + :vartype access_review_instances: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewInstancesOperations + :ivar access_review_instance: AccessReviewInstanceOperations operations + :vartype access_review_instance: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewInstanceOperations + :ivar access_review_instance_decisions: AccessReviewInstanceDecisionsOperations operations + :vartype access_review_instance_decisions: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewInstanceDecisionsOperations + :ivar access_review_instance_contacted_reviewers: + AccessReviewInstanceContactedReviewersOperations operations + :vartype access_review_instance_contacted_reviewers: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewInstanceContactedReviewersOperations + :ivar access_review_default_settings: AccessReviewDefaultSettingsOperations operations + :vartype access_review_default_settings: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewDefaultSettingsOperations + :ivar scope_access_review_history_definitions: ScopeAccessReviewHistoryDefinitionsOperations + operations + :vartype scope_access_review_history_definitions: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.ScopeAccessReviewHistoryDefinitionsOperations + :ivar scope_access_review_history_definition: ScopeAccessReviewHistoryDefinitionOperations + operations + :vartype scope_access_review_history_definition: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.ScopeAccessReviewHistoryDefinitionOperations + :ivar scope_access_review_history_definition_instance: + ScopeAccessReviewHistoryDefinitionInstanceOperations operations + :vartype scope_access_review_history_definition_instance: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.ScopeAccessReviewHistoryDefinitionInstanceOperations + :ivar scope_access_review_history_definition_instances: + ScopeAccessReviewHistoryDefinitionInstancesOperations operations + :vartype scope_access_review_history_definition_instances: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.ScopeAccessReviewHistoryDefinitionInstancesOperations + :ivar scope_access_review_schedule_definitions: ScopeAccessReviewScheduleDefinitionsOperations + operations + :vartype scope_access_review_schedule_definitions: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.ScopeAccessReviewScheduleDefinitionsOperations + :ivar scope_access_review_instances: ScopeAccessReviewInstancesOperations operations + :vartype scope_access_review_instances: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.ScopeAccessReviewInstancesOperations + :ivar scope_access_review_instance: ScopeAccessReviewInstanceOperations operations + :vartype scope_access_review_instance: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.ScopeAccessReviewInstanceOperations + :ivar scope_access_review_instance_decisions: ScopeAccessReviewInstanceDecisionsOperations + operations + :vartype scope_access_review_instance_decisions: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.ScopeAccessReviewInstanceDecisionsOperations + :ivar scope_access_review_instance_contacted_reviewers: + ScopeAccessReviewInstanceContactedReviewersOperations operations + :vartype scope_access_review_instance_contacted_reviewers: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.ScopeAccessReviewInstanceContactedReviewersOperations + :ivar scope_access_review_default_settings: ScopeAccessReviewDefaultSettingsOperations + operations + :vartype scope_access_review_default_settings: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.ScopeAccessReviewDefaultSettingsOperations + :ivar access_review_schedule_definitions_assigned_for_my_approval: + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations operations + :vartype access_review_schedule_definitions_assigned_for_my_approval: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations + :ivar access_review_instances_assigned_for_my_approval: + AccessReviewInstancesAssignedForMyApprovalOperations operations + :vartype access_review_instances_assigned_for_my_approval: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewInstancesAssignedForMyApprovalOperations + :ivar access_review_instance_my_decisions: AccessReviewInstanceMyDecisionsOperations operations + :vartype access_review_instance_my_decisions: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AccessReviewInstanceMyDecisionsOperations + :ivar tenant_level_access_review_instance_contacted_reviewers: + TenantLevelAccessReviewInstanceContactedReviewersOperations operations + :vartype tenant_level_access_review_instance_contacted_reviewers: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.TenantLevelAccessReviewInstanceContactedReviewersOperations + :ivar alerts: AlertsOperations operations + :vartype alerts: azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AlertsOperations + :ivar alert_configurations: AlertConfigurationsOperations operations + :vartype alert_configurations: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AlertConfigurationsOperations + :ivar alert_definitions: AlertDefinitionsOperations operations + :vartype alert_definitions: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AlertDefinitionsOperations + :ivar alert_incidents: AlertIncidentsOperations operations + :vartype alert_incidents: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AlertIncidentsOperations + :ivar alert_operation: AlertOperationOperations operations + :vartype alert_operation: + azure.mgmt.authorization.v2021_12_01_preview.aio.operations.AlertOperationOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.access_review_history_definitions = AccessReviewHistoryDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_history_definition = AccessReviewHistoryDefinitionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_history_definition_instance = AccessReviewHistoryDefinitionInstanceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_history_definition_instances = AccessReviewHistoryDefinitionInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_schedule_definitions = AccessReviewScheduleDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instances = AccessReviewInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance = AccessReviewInstanceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_decisions = AccessReviewInstanceDecisionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_contacted_reviewers = AccessReviewInstanceContactedReviewersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_default_settings = AccessReviewDefaultSettingsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_history_definitions = ScopeAccessReviewHistoryDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_history_definition = ScopeAccessReviewHistoryDefinitionOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_history_definition_instance = ScopeAccessReviewHistoryDefinitionInstanceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_history_definition_instances = ScopeAccessReviewHistoryDefinitionInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_schedule_definitions = ScopeAccessReviewScheduleDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_instances = ScopeAccessReviewInstancesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_instance = ScopeAccessReviewInstanceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_instance_decisions = ScopeAccessReviewInstanceDecisionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_instance_contacted_reviewers = ScopeAccessReviewInstanceContactedReviewersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.scope_access_review_default_settings = ScopeAccessReviewDefaultSettingsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_schedule_definitions_assigned_for_my_approval = ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) + self.access_review_instances_assigned_for_my_approval = AccessReviewInstancesAssignedForMyApprovalOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.access_review_instance_my_decisions = AccessReviewInstanceMyDecisionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.tenant_level_access_review_instance_contacted_reviewers = ( + TenantLevelAccessReviewInstanceContactedReviewersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + ) + self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alert_configurations = AlertConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.alert_definitions = AlertDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.alert_incidents = AlertIncidentsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alert_operation = AlertOperationOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "AuthorizationManagementClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_configuration.py new file mode 100644 index 00000000000..2d187691a27 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_configuration.py @@ -0,0 +1,60 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for AuthorizationManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/__init__.py new file mode 100644 index 00000000000..96a5dd0f695 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/__init__.py @@ -0,0 +1,89 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import Operations +from ._access_review_history_definitions_operations import AccessReviewHistoryDefinitionsOperations +from ._access_review_history_definition_operations import AccessReviewHistoryDefinitionOperations +from ._access_review_history_definition_instance_operations import AccessReviewHistoryDefinitionInstanceOperations +from ._access_review_history_definition_instances_operations import AccessReviewHistoryDefinitionInstancesOperations +from ._access_review_schedule_definitions_operations import AccessReviewScheduleDefinitionsOperations +from ._access_review_instances_operations import AccessReviewInstancesOperations +from ._access_review_instance_operations import AccessReviewInstanceOperations +from ._access_review_instance_decisions_operations import AccessReviewInstanceDecisionsOperations +from ._access_review_instance_contacted_reviewers_operations import AccessReviewInstanceContactedReviewersOperations +from ._access_review_default_settings_operations import AccessReviewDefaultSettingsOperations +from ._scope_access_review_history_definitions_operations import ScopeAccessReviewHistoryDefinitionsOperations +from ._scope_access_review_history_definition_operations import ScopeAccessReviewHistoryDefinitionOperations +from ._scope_access_review_history_definition_instance_operations import ( + ScopeAccessReviewHistoryDefinitionInstanceOperations, +) +from ._scope_access_review_history_definition_instances_operations import ( + ScopeAccessReviewHistoryDefinitionInstancesOperations, +) +from ._scope_access_review_schedule_definitions_operations import ScopeAccessReviewScheduleDefinitionsOperations +from ._scope_access_review_instances_operations import ScopeAccessReviewInstancesOperations +from ._scope_access_review_instance_operations import ScopeAccessReviewInstanceOperations +from ._scope_access_review_instance_decisions_operations import ScopeAccessReviewInstanceDecisionsOperations +from ._scope_access_review_instance_contacted_reviewers_operations import ( + ScopeAccessReviewInstanceContactedReviewersOperations, +) +from ._scope_access_review_default_settings_operations import ScopeAccessReviewDefaultSettingsOperations +from ._access_review_schedule_definitions_assigned_for_my_approval_operations import ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, +) +from ._access_review_instances_assigned_for_my_approval_operations import ( + AccessReviewInstancesAssignedForMyApprovalOperations, +) +from ._access_review_instance_my_decisions_operations import AccessReviewInstanceMyDecisionsOperations +from ._tenant_level_access_review_instance_contacted_reviewers_operations import ( + TenantLevelAccessReviewInstanceContactedReviewersOperations, +) +from ._alerts_operations import AlertsOperations +from ._alert_configurations_operations import AlertConfigurationsOperations +from ._alert_definitions_operations import AlertDefinitionsOperations +from ._alert_incidents_operations import AlertIncidentsOperations +from ._alert_operation_operations import AlertOperationOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "AccessReviewHistoryDefinitionsOperations", + "AccessReviewHistoryDefinitionOperations", + "AccessReviewHistoryDefinitionInstanceOperations", + "AccessReviewHistoryDefinitionInstancesOperations", + "AccessReviewScheduleDefinitionsOperations", + "AccessReviewInstancesOperations", + "AccessReviewInstanceOperations", + "AccessReviewInstanceDecisionsOperations", + "AccessReviewInstanceContactedReviewersOperations", + "AccessReviewDefaultSettingsOperations", + "ScopeAccessReviewHistoryDefinitionsOperations", + "ScopeAccessReviewHistoryDefinitionOperations", + "ScopeAccessReviewHistoryDefinitionInstanceOperations", + "ScopeAccessReviewHistoryDefinitionInstancesOperations", + "ScopeAccessReviewScheduleDefinitionsOperations", + "ScopeAccessReviewInstancesOperations", + "ScopeAccessReviewInstanceOperations", + "ScopeAccessReviewInstanceDecisionsOperations", + "ScopeAccessReviewInstanceContactedReviewersOperations", + "ScopeAccessReviewDefaultSettingsOperations", + "AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations", + "AccessReviewInstancesAssignedForMyApprovalOperations", + "AccessReviewInstanceMyDecisionsOperations", + "TenantLevelAccessReviewInstanceContactedReviewersOperations", + "AlertsOperations", + "AlertConfigurationsOperations", + "AlertDefinitionsOperations", + "AlertIncidentsOperations", + "AlertOperationOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_default_settings_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_default_settings_operations.py new file mode 100644 index 00000000000..905e72c0e6c --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_default_settings_operations.py @@ -0,0 +1,213 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_default_settings_operations import build_get_request, build_put_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewDefaultSettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_default_settings` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, **kwargs: Any) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + request = build_get_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore + + @overload + async def put( + self, properties: _models.AccessReviewScheduleSettings, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleSettings + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put( + self, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put( + self, properties: Union[_models.AccessReviewScheduleSettings, IO], **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleSettings or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleSettings") + + request = build_put_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + put.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_instance_operations.py new file mode 100644 index 00000000000..9e96b11d337 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_instance_operations.py @@ -0,0 +1,114 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_history_definition_instance_operations import build_generate_download_uri_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewHistoryDefinitionInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_history_definition_instance` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def generate_download_uri( + self, history_definition_id: str, instance_id: str, **kwargs: Any + ) -> _models.AccessReviewHistoryInstance: + """Generates a uri which can be used to retrieve review history data. This URI has a TTL of 1 day + and can be retrieved by fetching the accessReviewHistoryDefinition object. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param instance_id: The id of the access review history definition instance to generate a URI + for. Required. + :type instance_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryInstance] + + request = build_generate_download_uri_request( + history_definition_id=history_definition_id, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.generate_download_uri.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + generate_download_uri.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances/{instanceId}/generateDownloadUri"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_instances_operations.py new file mode 100644 index 00000000000..a7666222800 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_instances_operations.py @@ -0,0 +1,126 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_history_definition_instances_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewHistoryDefinitionInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_history_definition_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, history_definition_id: str, **kwargs: Any) -> AsyncIterable["_models.AccessReviewHistoryInstance"]: + """Get access review history definition instances by definition Id. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewHistoryInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinitionInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + history_definition_id=history_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewHistoryDefinitionInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_operations.py new file mode 100644 index 00000000000..3f2e22e82e9 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definition_operations.py @@ -0,0 +1,230 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_history_definition_operations import build_create_request, build_delete_by_id_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewHistoryDefinitionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_history_definition` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create( + self, + history_definition_id: str, + properties: _models.AccessReviewHistoryDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, history_definition_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + history_definition_id: str, + properties: Union[_models.AccessReviewHistoryDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinitionProperties or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewHistoryDefinitionProperties") + + request = build_create_request( + history_definition_id=history_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore + + @distributed_trace_async + async def delete_by_id( # pylint: disable=inconsistent-return-statements + self, history_definition_id: str, **kwargs: Any + ) -> None: + """Delete an access review history definition. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_id_request( + history_definition_id=history_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definitions_operations.py new file mode 100644 index 00000000000..231d3e5291a --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_history_definitions_operations.py @@ -0,0 +1,187 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_history_definitions_operations import build_get_by_id_request, build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewHistoryDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_history_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewHistoryDefinition"]: + """Lists the accessReviewHistoryDefinitions available from this provider, definition instances are + only available for 30 days after creation. + + :param filter: The filter to apply on the operation. Only standard filters on definition name + and created date are supported. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewHistoryDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewHistoryDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, history_definition_id: str, **kwargs: Any) -> _models.AccessReviewHistoryDefinition: + """Get access review history definition by definition Id. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinition] + + request = build_get_by_id_request( + history_definition_id=history_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_contacted_reviewers_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_contacted_reviewers_operations.py new file mode 100644 index 00000000000..11aeca60f19 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_contacted_reviewers_operations.py @@ -0,0 +1,131 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instance_contacted_reviewers_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstanceContactedReviewersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance_contacted_reviewers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewContactedReviewer"]: + """Get access review instance contacted reviewers. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewContactedReviewer or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewContactedReviewer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewContactedReviewerListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewContactedReviewerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_decisions_operations.py new file mode 100644 index 00000000000..830efb11953 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_decisions_operations.py @@ -0,0 +1,137 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instance_decisions_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstanceDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance_decisions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewDecision"]: + """Get access review instance decisions. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py new file mode 100644 index 00000000000..17980d37452 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_my_decisions_operations.py @@ -0,0 +1,352 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instance_my_decisions_operations import ( + build_get_by_id_request, + build_list_request, + build_patch_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstanceMyDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance_my_decisions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewDecision"]: + """Get my access review instance decisions. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore + + @distributed_trace_async + async def get_by_id( + self, schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any + ) -> _models.AccessReviewDecision: + """Get my single access review instance decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore + + @overload + async def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: _models.AccessReviewDecisionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: Union[_models.AccessReviewDecisionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewDecisionProperties") + + request = build_patch_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + patch.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_operations.py new file mode 100644 index 00000000000..378596af3f8 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instance_operations.py @@ -0,0 +1,341 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instance_operations import ( + build_accept_recommendations_request, + build_apply_decisions_request, + build_reset_decisions_request, + build_send_reminders_request, + build_stop_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instance` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to stop an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop"} # type: ignore + + @distributed_trace_async + async def reset_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to reset all decisions for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reset_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.reset_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + reset_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions"} # type: ignore + + @distributed_trace_async + async def apply_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to apply all decisions for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_apply_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.apply_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + apply_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions"} # type: ignore + + @distributed_trace_async + async def send_reminders( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to send reminders for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_send_reminders_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.send_reminders.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + send_reminders.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders"} # type: ignore + + @distributed_trace_async + async def accept_recommendations( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to accept recommendations for decision in an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_accept_recommendations_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.accept_recommendations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + accept_recommendations.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py new file mode 100644 index 00000000000..d18174fb420 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instances_assigned_for_my_approval_operations.py @@ -0,0 +1,195 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instances_assigned_for_my_approval_operations import ( + build_get_by_id_request, + build_list_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstancesAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instances_assigned_for_my_approval` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewInstance"]: + """Get access review instances assigned for my approval. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: + """Get single access review instance assigned for my approval. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instances_operations.py new file mode 100644 index 00000000000..2b546a853b6 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_instances_operations.py @@ -0,0 +1,337 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_instances_operations import ( + build_create_request, + build_get_by_id_request, + build_list_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewInstance"]: + """Get access review instances. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: + """Get access review instances. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore + + @overload + async def create( + self, + schedule_definition_id: str, + id: str, + properties: _models.AccessReviewInstanceProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + schedule_definition_id: str, + id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + schedule_definition_id: str, + id: str, + properties: Union[_models.AccessReviewInstanceProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewInstanceProperties") + + request = build_create_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py new file mode 100644 index 00000000000..8dc9c55cc68 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py @@ -0,0 +1,130 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_schedule_definitions_assigned_for_my_approval_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions_assigned_for_my_approval` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewScheduleDefinition"]: + """Get access review instances assigned for my approval. + + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_schedule_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_schedule_definitions_operations.py new file mode 100644 index 00000000000..6bbc963e623 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_access_review_schedule_definitions_operations.py @@ -0,0 +1,427 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._access_review_schedule_definitions_operations import ( + build_create_or_update_by_id_request, + build_delete_by_id_request, + build_get_by_id_request, + build_list_request, + build_stop_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AccessReviewScheduleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewScheduleDefinition"]: + """Get access review schedule definitions. + + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, schedule_definition_id: str, **kwargs: Any) -> _models.AccessReviewScheduleDefinition: + """Get single access review definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def delete_by_id( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Delete access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @overload + async def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: _models.AccessReviewScheduleDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_by_id( + self, schedule_definition_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: Union[_models.AccessReviewScheduleDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionProperties + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleDefinitionProperties") + + request = build_create_or_update_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Stop access review definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_configurations_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_configurations_operations.py new file mode 100644 index 00000000000..024cacb776b --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_configurations_operations.py @@ -0,0 +1,316 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._alert_configurations_operations import ( + build_get_request, + build_list_for_scope_request, + build_update_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AlertConfigurationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`alert_configurations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.AlertConfiguration: + """Get the specified alert configuration. + + :param scope: The scope of the alert configuration. The scope can be any REST resource + instance. For example, use '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' + for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param alert_id: The name of the alert configuration to get. Required. + :type alert_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertConfiguration] + + request = build_get_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertConfiguration", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertConfigurations/{alertId}"} # type: ignore + + @overload + async def update( + self, + scope: str, + alert_id: str, + parameters: _models.AlertConfiguration, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AlertConfiguration: + """Update an alert configuration. + + :param scope: The scope of the alert configuration. Required. + :type scope: str + :param alert_id: The name of the alert configuration to update. Required. + :type alert_id: str + :param parameters: Parameters for the alert configuration. Required. + :type parameters: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, scope: str, alert_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AlertConfiguration: + """Update an alert configuration. + + :param scope: The scope of the alert configuration. Required. + :type scope: str + :param alert_id: The name of the alert configuration to update. Required. + :type alert_id: str + :param parameters: Parameters for the alert configuration. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, scope: str, alert_id: str, parameters: Union[_models.AlertConfiguration, IO], **kwargs: Any + ) -> _models.AlertConfiguration: + """Update an alert configuration. + + :param scope: The scope of the alert configuration. Required. + :type scope: str + :param alert_id: The name of the alert configuration to update. Required. + :type alert_id: str + :param parameters: Parameters for the alert configuration. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertConfiguration] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "AlertConfiguration") + + request = build_update_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertConfiguration", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertConfigurations/{alertId}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.AlertConfiguration"]: + """Gets alert configurations for a resource scope. + + :param scope: The scope of the alert configuration. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AlertConfiguration or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertConfigurationListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AlertConfigurationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertConfigurations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_definitions_operations.py new file mode 100644 index 00000000000..0464db6778a --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_definitions_operations.py @@ -0,0 +1,187 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._alert_definitions_operations import build_get_request, build_list_for_scope_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AlertDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`alert_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, scope: str, alert_definition_id: str, **kwargs: Any) -> _models.AlertDefinition: + """Get the specified alert definition. + + :param scope: The scope of the alert definition. The scope can be any REST resource instance. + For example, use '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a + subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param alert_definition_id: The name of the alert definition to get. Required. + :type alert_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertDefinition] + + request = build_get_request( + scope=scope, + alert_definition_id=alert_definition_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertDefinitions/{alertDefinitionId}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.AlertDefinition"]: + """Gets alert definitions for a resource scope. + + :param scope: The scope of the alert definition. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AlertDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AlertDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertDefinitions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_incidents_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_incidents_operations.py new file mode 100644 index 00000000000..803f81a0706 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_incidents_operations.py @@ -0,0 +1,255 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._alert_incidents_operations import ( + build_get_request, + build_list_for_scope_request, + build_remediate_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AlertIncidentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`alert_incidents` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, scope: str, alert_id: str, alert_incident_id: str, **kwargs: Any) -> _models.AlertIncident: + """Get the specified alert incident. + + :param scope: The scope of the alert incident. The scope can be any REST resource instance. For + example, use '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a + subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param alert_id: The name of the alert. Required. + :type alert_id: str + :param alert_incident_id: The name of the alert incident to get. Required. + :type alert_incident_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertIncident or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertIncident + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertIncident] + + request = build_get_request( + scope=scope, + alert_id=alert_id, + alert_incident_id=alert_incident_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertIncident", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/alertIncidents/{alertIncidentId}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, alert_id: str, **kwargs: Any) -> AsyncIterable["_models.AlertIncident"]: + """Gets alert incidents for a resource scope. + + :param scope: The scope of the alert incident. Required. + :type scope: str + :param alert_id: The name of the alert. Required. + :type alert_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AlertIncident or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertIncident] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertIncidentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AlertIncidentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/alertIncidents"} # type: ignore + + @distributed_trace_async + async def remediate( # pylint: disable=inconsistent-return-statements + self, scope: str, alert_id: str, alert_incident_id: str, **kwargs: Any + ) -> None: + """Remediate an alert incident. + + :param scope: The scope of the alert incident. Required. + :type scope: str + :param alert_id: The name of the alert. Required. + :type alert_id: str + :param alert_incident_id: The name of the alert incident to remediate. Required. + :type alert_incident_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_remediate_request( + scope=scope, + alert_id=alert_id, + alert_incident_id=alert_incident_id, + api_version=api_version, + template_url=self.remediate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + remediate.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/alertIncidents/{alertIncidentId}/remediate"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_operation_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_operation_operations.py new file mode 100644 index 00000000000..a4e26fd4754 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alert_operation_operations.py @@ -0,0 +1,162 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._alert_operation_operations import build_get_request, build_list_for_scope_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AlertOperationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`alert_operation` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, scope: str, operation_id: str, **kwargs: Any) -> _models.AlertOperationResult: + """Get the specified alert operation. + + :param scope: The scope of the alert operation. Required. + :type scope: str + :param operation_id: The id of the alert operation. Required. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertOperationResult or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertOperationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationResult] + + request = build_get_request( + scope=scope, + operation_id=operation_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertOperationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/operations/{operationId}"} # type: ignore + + @distributed_trace_async + async def list_for_scope(self, scope: str, **kwargs: Any) -> _models.AlertOperationListResult: + """Gets alert operations for a resource scope. + + :param scope: The scope of the alert operation. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertOperationListResult or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertOperationListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationListResult] + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertOperationListResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alerts_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alerts_operations.py new file mode 100644 index 00000000000..8b9859bb793 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_alerts_operations.py @@ -0,0 +1,549 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._alerts_operations import ( + build_get_request, + build_list_for_scope_request, + build_refresh_all_request, + build_refresh_request, + build_update_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AlertsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`alerts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: + """Get the specified alert. + + :param scope: The scope of the alert. The scope can be any REST resource instance. For example, + use '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param alert_id: The name of the alert to get. Required. + :type alert_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Alert] + + request = build_get_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Alert", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}"} # type: ignore + + @overload + async def update( + self, + scope: str, + alert_id: str, + parameters: _models.Alert, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Alert: + """Update an alert. + + :param scope: The scope of the alert. Required. + :type scope: str + :param alert_id: The name of the alert to dismiss. Required. + :type alert_id: str + :param parameters: Parameters for the alert. Required. + :type parameters: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, scope: str, alert_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Alert: + """Update an alert. + + :param scope: The scope of the alert. Required. + :type scope: str + :param alert_id: The name of the alert to dismiss. Required. + :type alert_id: str + :param parameters: Parameters for the alert. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, scope: str, alert_id: str, parameters: Union[_models.Alert, IO], **kwargs: Any + ) -> _models.Alert: + """Update an alert. + + :param scope: The scope of the alert. Required. + :type scope: str + :param alert_id: The name of the alert to dismiss. Required. + :type alert_id: str + :param parameters: Parameters for the alert. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Alert] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Alert") + + request = build_update_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Alert", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.Alert"]: + """Gets alerts for a resource scope. + + :param scope: The scope of the alert. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Alert or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.Alert] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AlertListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts"} # type: ignore + + async def _refresh_initial(self, scope: str, alert_id: str, **kwargs: Any) -> _models.AlertOperationResult: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationResult] + + request = build_refresh_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self._refresh_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("AlertOperationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _refresh_initial.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/refresh"} # type: ignore + + @distributed_trace_async + async def begin_refresh( + self, scope: str, alert_id: str, **kwargs: Any + ) -> AsyncLROPoller[_models.AlertOperationResult]: + """Refresh an alert. + + :param scope: The scope of the alert. Required. + :type scope: str + :param alert_id: The name of the alert to refresh. Required. + :type alert_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either AlertOperationResult or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationResult] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._refresh_initial( # type: ignore + scope=scope, + alert_id=alert_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("AlertOperationResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, response_headers) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_refresh.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/refresh"} # type: ignore + + async def _refresh_all_initial(self, scope: str, **kwargs: Any) -> _models.AlertOperationResult: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationResult] + + request = build_refresh_all_request( + scope=scope, + api_version=api_version, + template_url=self._refresh_all_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("AlertOperationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _refresh_all_initial.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/refresh"} # type: ignore + + @distributed_trace_async + async def begin_refresh_all(self, scope: str, **kwargs: Any) -> AsyncLROPoller[_models.AlertOperationResult]: + """Refresh all alerts for a resource scope. + + :param scope: The scope of the alert. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either AlertOperationResult or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationResult] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._refresh_all_initial( # type: ignore + scope=scope, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("AlertOperationResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, response_headers) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_refresh_all.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/refresh"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_operations.py new file mode 100644 index 00000000000..c91866fefb8 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_operations.py @@ -0,0 +1,121 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + """Lists the operations available from this provider. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_default_settings_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_default_settings_operations.py new file mode 100644 index 00000000000..bb72f9e6131 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_default_settings_operations.py @@ -0,0 +1,226 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_access_review_default_settings_operations import build_get_request, build_put_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ScopeAccessReviewDefaultSettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_access_review_default_settings` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, scope: str, **kwargs: Any) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param scope: The scope of the resource. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + request = build_get_request( + scope=scope, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore + + @overload + async def put( + self, + scope: str, + properties: _models.AccessReviewScheduleSettings, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Access review schedule settings. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleSettings + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put( + self, scope: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Access review schedule settings. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put( + self, scope: str, properties: Union[_models.AccessReviewScheduleSettings, IO], **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Access review schedule settings. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleSettings or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleSettings") + + request = build_put_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + put.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_instance_operations.py new file mode 100644 index 00000000000..bdee04f37e0 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_instance_operations.py @@ -0,0 +1,118 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_access_review_history_definition_instance_operations import ( + build_generate_download_uri_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ScopeAccessReviewHistoryDefinitionInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_access_review_history_definition_instance` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def generate_download_uri( + self, scope: str, history_definition_id: str, instance_id: str, **kwargs: Any + ) -> _models.AccessReviewHistoryInstance: + """Generates a uri which can be used to retrieve review history data. This URI has a TTL of 1 day + and can be retrieved by fetching the accessReviewHistoryDefinition object. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param instance_id: The id of the access review history definition instance to generate a URI + for. Required. + :type instance_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryInstance] + + request = build_generate_download_uri_request( + scope=scope, + history_definition_id=history_definition_id, + instance_id=instance_id, + api_version=api_version, + template_url=self.generate_download_uri.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + generate_download_uri.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances/{instanceId}/generateDownloadUri"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_instances_operations.py new file mode 100644 index 00000000000..6e2711f432a --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_instances_operations.py @@ -0,0 +1,130 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_access_review_history_definition_instances_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ScopeAccessReviewHistoryDefinitionInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_access_review_history_definition_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, history_definition_id: str, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewHistoryInstance"]: + """Get access review history definition instances by definition Id. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewHistoryInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinitionInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + history_definition_id=history_definition_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewHistoryDefinitionInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_operations.py new file mode 100644 index 00000000000..ba58dfb1c05 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definition_operations.py @@ -0,0 +1,249 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_access_review_history_definition_operations import ( + build_create_request, + build_delete_by_id_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ScopeAccessReviewHistoryDefinitionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_access_review_history_definition` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create( + self, + scope: str, + history_definition_id: str, + properties: _models.AccessReviewHistoryDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + history_definition_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + history_definition_id: str, + properties: Union[_models.AccessReviewHistoryDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinitionProperties or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewHistoryDefinitionProperties") + + request = build_create_request( + scope=scope, + history_definition_id=history_definition_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore + + @distributed_trace_async + async def delete_by_id( # pylint: disable=inconsistent-return-statements + self, scope: str, history_definition_id: str, **kwargs: Any + ) -> None: + """Delete an access review history definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_id_request( + scope=scope, + history_definition_id=history_definition_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definitions_operations.py new file mode 100644 index 00000000000..dcb54bce26c --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_history_definitions_operations.py @@ -0,0 +1,196 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_access_review_history_definitions_operations import ( + build_get_by_id_request, + build_list_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ScopeAccessReviewHistoryDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_access_review_history_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewHistoryDefinition"]: + """Lists the accessReviewHistoryDefinitions available from this provider, definition instances are + only available for 30 days after creation. + + :param scope: The scope of the resource. Required. + :type scope: str + :param filter: The filter to apply on the operation. Only standard filters on definition name + and created date are supported. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewHistoryDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewHistoryDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions"} # type: ignore + + @distributed_trace_async + async def get_by_id( + self, scope: str, history_definition_id: str, **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Get access review history definition by definition Id. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinition] + + request = build_get_by_id_request( + scope=scope, + history_definition_id=history_definition_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_contacted_reviewers_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_contacted_reviewers_operations.py new file mode 100644 index 00000000000..8f4106c0564 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_contacted_reviewers_operations.py @@ -0,0 +1,133 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_access_review_instance_contacted_reviewers_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ScopeAccessReviewInstanceContactedReviewersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_access_review_instance_contacted_reviewers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewContactedReviewer"]: + """Get access review instance contacted reviewers. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewContactedReviewer or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewContactedReviewer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewContactedReviewerListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewContactedReviewerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_decisions_operations.py new file mode 100644 index 00000000000..8cd5d24f3f0 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_decisions_operations.py @@ -0,0 +1,139 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_access_review_instance_decisions_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ScopeAccessReviewInstanceDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_access_review_instance_decisions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewDecision"]: + """Get access review instance decisions. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_operations.py new file mode 100644 index 00000000000..c2c5b31b79e --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instance_operations.py @@ -0,0 +1,436 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_access_review_instance_operations import ( + build_apply_decisions_request, + build_record_all_decisions_request, + build_reset_decisions_request, + build_send_reminders_request, + build_stop_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ScopeAccessReviewInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_access_review_instance` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def stop( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to stop an access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop"} # type: ignore + + @overload + async def record_all_decisions( # pylint: disable=inconsistent-return-statements + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: _models.RecordAllDecisionsProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """An action to approve/deny all decisions for a review with certain filters. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Record all decisions payload. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.RecordAllDecisionsProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def record_all_decisions( # pylint: disable=inconsistent-return-statements + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """An action to approve/deny all decisions for a review with certain filters. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Record all decisions payload. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def record_all_decisions( # pylint: disable=inconsistent-return-statements + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: Union[_models.RecordAllDecisionsProperties, IO], + **kwargs: Any + ) -> None: + """An action to approve/deny all decisions for a review with certain filters. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Record all decisions payload. Is either a model type or a IO type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.RecordAllDecisionsProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "RecordAllDecisionsProperties") + + request = build_record_all_decisions_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.record_all_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + record_all_decisions.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/recordAllDecisions"} # type: ignore + + @distributed_trace_async + async def reset_decisions( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to reset all decisions for an access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reset_decisions_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.reset_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + reset_decisions.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions"} # type: ignore + + @distributed_trace_async + async def apply_decisions( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to apply all decisions for an access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_apply_decisions_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.apply_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + apply_decisions.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions"} # type: ignore + + @distributed_trace_async + async def send_reminders( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to send reminders for an access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_send_reminders_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.send_reminders.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + send_reminders.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instances_operations.py new file mode 100644 index 00000000000..cd92e225850 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_instances_operations.py @@ -0,0 +1,352 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_access_review_instances_operations import ( + build_create_request, + build_get_by_id_request, + build_list_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ScopeAccessReviewInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_access_review_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewInstance"]: + """Get access review instances. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace_async + async def get_by_id( + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> _models.AccessReviewInstance: + """Get access review instances. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore + + @overload + async def create( + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: _models.AccessReviewInstanceProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: Union[_models.AccessReviewInstanceProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewInstanceProperties") + + request = build_create_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_schedule_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_schedule_definitions_operations.py new file mode 100644 index 00000000000..3a1405d342f --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_scope_access_review_schedule_definitions_operations.py @@ -0,0 +1,451 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scope_access_review_schedule_definitions_operations import ( + build_create_or_update_by_id_request, + build_delete_by_id_request, + build_get_by_id_request, + build_list_request, + build_stop_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ScopeAccessReviewScheduleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`scope_access_review_schedule_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewScheduleDefinition"]: + """Get access review schedule definitions. + + :param scope: The scope of the resource. Required. + :type scope: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore + + @distributed_trace_async + async def get_by_id( + self, scope: str, schedule_definition_id: str, **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Get single access review definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + request = build_get_by_id_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def delete_by_id( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Delete access review schedule definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_id_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @overload + async def create_or_update_by_id( + self, + scope: str, + schedule_definition_id: str, + properties: _models.AccessReviewScheduleDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_by_id( + self, + scope: str, + schedule_definition_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_by_id( + self, + scope: str, + schedule_definition_id: str, + properties: Union[_models.AccessReviewScheduleDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionProperties + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleDefinitionProperties") + + request = build_create_or_update_by_id_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def stop( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Stop access review definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py new file mode 100644 index 00000000000..7822f74f459 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/aio/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py @@ -0,0 +1,130 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._tenant_level_access_review_instance_contacted_reviewers_operations import build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class TenantLevelAccessReviewInstanceContactedReviewersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.aio.AuthorizationManagementClient`'s + :attr:`tenant_level_access_review_instance_contacted_reviewers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> AsyncIterable["_models.AccessReviewContactedReviewer"]: + """Get access review instance contacted reviewers. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewContactedReviewer or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewContactedReviewer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewContactedReviewerListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewContactedReviewerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/__init__.py new file mode 100644 index 00000000000..e75f1ded6c0 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/__init__.py @@ -0,0 +1,165 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import AccessReviewContactedReviewer +from ._models_py3 import AccessReviewContactedReviewerListResult +from ._models_py3 import AccessReviewDecision +from ._models_py3 import AccessReviewDecisionIdentity +from ._models_py3 import AccessReviewDecisionInsight +from ._models_py3 import AccessReviewDecisionInsightProperties +from ._models_py3 import AccessReviewDecisionListResult +from ._models_py3 import AccessReviewDecisionProperties +from ._models_py3 import AccessReviewDecisionServicePrincipalIdentity +from ._models_py3 import AccessReviewDecisionUserIdentity +from ._models_py3 import AccessReviewDecisionUserSignInInsightProperties +from ._models_py3 import AccessReviewDefaultSettings +from ._models_py3 import AccessReviewHistoryDefinition +from ._models_py3 import AccessReviewHistoryDefinitionInstanceListResult +from ._models_py3 import AccessReviewHistoryDefinitionListResult +from ._models_py3 import AccessReviewHistoryDefinitionProperties +from ._models_py3 import AccessReviewHistoryInstance +from ._models_py3 import AccessReviewInstance +from ._models_py3 import AccessReviewInstanceListResult +from ._models_py3 import AccessReviewInstanceProperties +from ._models_py3 import AccessReviewReviewer +from ._models_py3 import AccessReviewScheduleDefinition +from ._models_py3 import AccessReviewScheduleDefinitionListResult +from ._models_py3 import AccessReviewScheduleDefinitionProperties +from ._models_py3 import AccessReviewScheduleSettings +from ._models_py3 import AccessReviewScope +from ._models_py3 import Alert +from ._models_py3 import AlertConfiguration +from ._models_py3 import AlertConfigurationListResult +from ._models_py3 import AlertConfigurationProperties +from ._models_py3 import AlertDefinition +from ._models_py3 import AlertDefinitionListResult +from ._models_py3 import AlertIncident +from ._models_py3 import AlertIncidentListResult +from ._models_py3 import AlertIncidentProperties +from ._models_py3 import AlertListResult +from ._models_py3 import AlertOperationListResult +from ._models_py3 import AlertOperationResult +from ._models_py3 import AzureRolesAssignedOutsidePimAlertConfigurationProperties +from ._models_py3 import AzureRolesAssignedOutsidePimAlertIncidentProperties +from ._models_py3 import CloudErrorBody +from ._models_py3 import DuplicateRoleCreatedAlertConfigurationProperties +from ._models_py3 import DuplicateRoleCreatedAlertIncidentProperties +from ._models_py3 import ErrorDefinition +from ._models_py3 import ErrorDefinitionProperties +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import RecordAllDecisionsProperties +from ._models_py3 import TooManyOwnersAssignedToResourceAlertConfigurationProperties +from ._models_py3 import TooManyOwnersAssignedToResourceAlertIncidentProperties +from ._models_py3 import TooManyPermanentOwnersAssignedToResourceAlertConfigurationProperties +from ._models_py3 import TooManyPermanentOwnersAssignedToResourceAlertIncidentProperties + +from ._authorization_management_client_enums import AccessRecommendationType +from ._authorization_management_client_enums import AccessReviewActorIdentityType +from ._authorization_management_client_enums import AccessReviewApplyResult +from ._authorization_management_client_enums import AccessReviewDecisionInsightType +from ._authorization_management_client_enums import AccessReviewDecisionPrincipalResourceMembershipType +from ._authorization_management_client_enums import AccessReviewHistoryDefinitionStatus +from ._authorization_management_client_enums import AccessReviewInstanceReviewersType +from ._authorization_management_client_enums import AccessReviewInstanceStatus +from ._authorization_management_client_enums import AccessReviewRecurrencePatternType +from ._authorization_management_client_enums import AccessReviewRecurrenceRangeType +from ._authorization_management_client_enums import AccessReviewResult +from ._authorization_management_client_enums import AccessReviewReviewerType +from ._authorization_management_client_enums import AccessReviewScheduleDefinitionReviewersType +from ._authorization_management_client_enums import AccessReviewScheduleDefinitionStatus +from ._authorization_management_client_enums import AccessReviewScopeAssignmentState +from ._authorization_management_client_enums import AccessReviewScopePrincipalType +from ._authorization_management_client_enums import DecisionResourceType +from ._authorization_management_client_enums import DecisionTargetType +from ._authorization_management_client_enums import DefaultDecisionType +from ._authorization_management_client_enums import RecordAllDecisionsResult +from ._authorization_management_client_enums import SeverityLevel +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AccessReviewContactedReviewer", + "AccessReviewContactedReviewerListResult", + "AccessReviewDecision", + "AccessReviewDecisionIdentity", + "AccessReviewDecisionInsight", + "AccessReviewDecisionInsightProperties", + "AccessReviewDecisionListResult", + "AccessReviewDecisionProperties", + "AccessReviewDecisionServicePrincipalIdentity", + "AccessReviewDecisionUserIdentity", + "AccessReviewDecisionUserSignInInsightProperties", + "AccessReviewDefaultSettings", + "AccessReviewHistoryDefinition", + "AccessReviewHistoryDefinitionInstanceListResult", + "AccessReviewHistoryDefinitionListResult", + "AccessReviewHistoryDefinitionProperties", + "AccessReviewHistoryInstance", + "AccessReviewInstance", + "AccessReviewInstanceListResult", + "AccessReviewInstanceProperties", + "AccessReviewReviewer", + "AccessReviewScheduleDefinition", + "AccessReviewScheduleDefinitionListResult", + "AccessReviewScheduleDefinitionProperties", + "AccessReviewScheduleSettings", + "AccessReviewScope", + "Alert", + "AlertConfiguration", + "AlertConfigurationListResult", + "AlertConfigurationProperties", + "AlertDefinition", + "AlertDefinitionListResult", + "AlertIncident", + "AlertIncidentListResult", + "AlertIncidentProperties", + "AlertListResult", + "AlertOperationListResult", + "AlertOperationResult", + "AzureRolesAssignedOutsidePimAlertConfigurationProperties", + "AzureRolesAssignedOutsidePimAlertIncidentProperties", + "CloudErrorBody", + "DuplicateRoleCreatedAlertConfigurationProperties", + "DuplicateRoleCreatedAlertIncidentProperties", + "ErrorDefinition", + "ErrorDefinitionProperties", + "Operation", + "OperationDisplay", + "OperationListResult", + "RecordAllDecisionsProperties", + "TooManyOwnersAssignedToResourceAlertConfigurationProperties", + "TooManyOwnersAssignedToResourceAlertIncidentProperties", + "TooManyPermanentOwnersAssignedToResourceAlertConfigurationProperties", + "TooManyPermanentOwnersAssignedToResourceAlertIncidentProperties", + "AccessRecommendationType", + "AccessReviewActorIdentityType", + "AccessReviewApplyResult", + "AccessReviewDecisionInsightType", + "AccessReviewDecisionPrincipalResourceMembershipType", + "AccessReviewHistoryDefinitionStatus", + "AccessReviewInstanceReviewersType", + "AccessReviewInstanceStatus", + "AccessReviewRecurrencePatternType", + "AccessReviewRecurrenceRangeType", + "AccessReviewResult", + "AccessReviewReviewerType", + "AccessReviewScheduleDefinitionReviewersType", + "AccessReviewScheduleDefinitionStatus", + "AccessReviewScopeAssignmentState", + "AccessReviewScopePrincipalType", + "DecisionResourceType", + "DecisionTargetType", + "DefaultDecisionType", + "RecordAllDecisionsResult", + "SeverityLevel", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_authorization_management_client_enums.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_authorization_management_client_enums.py new file mode 100644 index 00000000000..32897d1dcd9 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_authorization_management_client_enums.py @@ -0,0 +1,199 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AccessRecommendationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The feature- generated recommendation shown to the reviewer.""" + + APPROVE = "Approve" + DENY = "Deny" + NO_INFO_AVAILABLE = "NoInfoAvailable" + + +class AccessReviewActorIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type : user/servicePrincipal.""" + + USER = "user" + SERVICE_PRINCIPAL = "servicePrincipal" + + +class AccessReviewApplyResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The outcome of applying the decision.""" + + NEW = "New" + APPLYING = "Applying" + APPLIED_SUCCESSFULLY = "AppliedSuccessfully" + APPLIED_WITH_UNKNOWN_FAILURE = "AppliedWithUnknownFailure" + APPLIED_SUCCESSFULLY_BUT_OBJECT_NOT_FOUND = "AppliedSuccessfullyButObjectNotFound" + APPLY_NOT_SUPPORTED = "ApplyNotSupported" + + +class AccessReviewDecisionInsightType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of insight.""" + + USER_SIGN_IN_INSIGHT = "userSignInInsight" + + +class AccessReviewDecisionPrincipalResourceMembershipType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """AccessReviewDecisionPrincipalResourceMembershipType.""" + + DIRECT = "direct" + INDIRECT = "indirect" + + +class AccessReviewHistoryDefinitionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This read-only field specifies the of the requested review history data. This is either + requested, in-progress, done or error. + """ + + REQUESTED = "Requested" + IN_PROGRESS = "InProgress" + DONE = "Done" + ERROR = "Error" + + +class AccessReviewInstanceReviewersType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This field specifies the type of reviewers for a review. Usually for a review, reviewers are + explicitly assigned. However, in some cases, the reviewers may not be assigned and instead be + chosen dynamically. For example managers review or self review. + """ + + ASSIGNED = "Assigned" + SELF = "Self" + MANAGERS = "Managers" + + +class AccessReviewInstanceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This read-only field specifies the status of an access review instance.""" + + NOT_STARTED = "NotStarted" + IN_PROGRESS = "InProgress" + COMPLETED = "Completed" + APPLIED = "Applied" + INITIALIZING = "Initializing" + APPLYING = "Applying" + COMPLETING = "Completing" + SCHEDULED = "Scheduled" + AUTO_REVIEWING = "AutoReviewing" + AUTO_REVIEWED = "AutoReviewed" + STARTING = "Starting" + + +class AccessReviewRecurrencePatternType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The recurrence type : weekly, monthly, etc.""" + + WEEKLY = "weekly" + ABSOLUTE_MONTHLY = "absoluteMonthly" + + +class AccessReviewRecurrenceRangeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The recurrence range type. The possible values are: endDate, noEnd, numbered.""" + + END_DATE = "endDate" + NO_END = "noEnd" + NUMBERED = "numbered" + + +class AccessReviewResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Represents a reviewer's decision for a given review.""" + + APPROVE = "Approve" + DENY = "Deny" + NOT_REVIEWED = "NotReviewed" + DONT_KNOW = "DontKnow" + NOT_NOTIFIED = "NotNotified" + + +class AccessReviewReviewerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type : user/servicePrincipal.""" + + USER = "user" + SERVICE_PRINCIPAL = "servicePrincipal" + + +class AccessReviewScheduleDefinitionReviewersType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This field specifies the type of reviewers for a review. Usually for a review, reviewers are + explicitly assigned. However, in some cases, the reviewers may not be assigned and instead be + chosen dynamically. For example managers review or self review. + """ + + ASSIGNED = "Assigned" + SELF = "Self" + MANAGERS = "Managers" + + +class AccessReviewScheduleDefinitionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This read-only field specifies the status of an accessReview.""" + + NOT_STARTED = "NotStarted" + IN_PROGRESS = "InProgress" + COMPLETED = "Completed" + APPLIED = "Applied" + INITIALIZING = "Initializing" + APPLYING = "Applying" + COMPLETING = "Completing" + SCHEDULED = "Scheduled" + AUTO_REVIEWING = "AutoReviewing" + AUTO_REVIEWED = "AutoReviewed" + STARTING = "Starting" + + +class AccessReviewScopeAssignmentState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The role assignment state eligible/active to review.""" + + ELIGIBLE = "eligible" + ACTIVE = "active" + + +class AccessReviewScopePrincipalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type user/servicePrincipal to review.""" + + USER = "user" + GUEST_USER = "guestUser" + SERVICE_PRINCIPAL = "servicePrincipal" + USER_GROUP = "user,group" + REDEEMED_GUEST_USER = "redeemedGuestUser" + + +class DecisionResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of resource.""" + + AZURE_ROLE = "azureRole" + + +class DecisionTargetType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of decision target : User/ServicePrincipal.""" + + USER = "user" + SERVICE_PRINCIPAL = "servicePrincipal" + + +class DefaultDecisionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This specifies the behavior for the autoReview feature when an access review completes.""" + + APPROVE = "Approve" + DENY = "Deny" + RECOMMENDATION = "Recommendation" + + +class RecordAllDecisionsResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The decision to make. Approvers can take action of Approve/Deny.""" + + APPROVE = "Approve" + DENY = "Deny" + + +class SeverityLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Severity level of the alert.""" + + LOW = "Low" + MEDIUM = "Medium" + HIGH = "High" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_models_py3.py new file mode 100644 index 00000000000..da9605ab33a --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_models_py3.py @@ -0,0 +1,3868 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class AccessReviewContactedReviewer(_serialization.Model): + """Access Review Contacted Reviewer. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review reviewer id. + :vartype id: str + :ivar name: The access review reviewer id. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar user_display_name: The display name of the reviewer. + :vartype user_display_name: str + :ivar user_principal_name: The user principal name of the reviewer. + :vartype user_principal_name: str + :ivar created_date_time: Date Time when the reviewer was contacted. + :vartype created_date_time: ~datetime.datetime + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "user_display_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, + "created_date_time": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "user_display_name": {"key": "properties.userDisplayName", "type": "str"}, + "user_principal_name": {"key": "properties.userPrincipalName", "type": "str"}, + "created_date_time": {"key": "properties.createdDateTime", "type": "iso-8601"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.user_display_name = None + self.user_principal_name = None + self.created_date_time = None + + +class AccessReviewContactedReviewerListResult(_serialization.Model): + """List of access review contacted reviewers. + + :ivar value: Access Review Contacted Reviewer. + :vartype value: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewContactedReviewer] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AccessReviewContactedReviewer]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.AccessReviewContactedReviewer"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Access Review Contacted Reviewer. + :paramtype value: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewContactedReviewer] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AccessReviewDecision(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Access Review. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review decision id. + :vartype id: str + :ivar name: The access review decision name. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar recommendation: The feature- generated recommendation shown to the reviewer. Known values + are: "Approve", "Deny", and "NoInfoAvailable". + :vartype recommendation: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessRecommendationType + :ivar decision: The decision on the approval step. This value is initially set to NotReviewed. + Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", "NotReviewed", + "DontKnow", and "NotNotified". + :vartype decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewResult + :ivar justification: Justification provided by approvers for their action. + :vartype justification: str + :ivar reviewed_date_time: Date Time when a decision was taken. + :vartype reviewed_date_time: ~datetime.datetime + :ivar apply_result: The outcome of applying the decision. Known values are: "New", "Applying", + "AppliedSuccessfully", "AppliedWithUnknownFailure", "AppliedSuccessfullyButObjectNotFound", and + "ApplyNotSupported". + :vartype apply_result: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewApplyResult + :ivar applied_date_time: The date and time when the review decision was applied. + :vartype applied_date_time: ~datetime.datetime + :ivar insights: This is the collection of insights for this decision item. + :vartype insights: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionInsight] + :ivar membership_types: Every decision item in an access review represents a principal's + membership to a resource. This property represents details of the membership. Examples of this + detail might be whether the principal has direct access or indirect access. + :vartype membership_types: list[str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionPrincipalResourceMembershipType] + :ivar principal_id_properties_applied_by_principal_id: The identity id. + :vartype principal_id_properties_applied_by_principal_id: str + :ivar principal_type_properties_applied_by_principal_type: The identity type : + user/servicePrincipal. Known values are: "user" and "servicePrincipal". + :vartype principal_type_properties_applied_by_principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name_properties_applied_by_principal_name: The identity display name. + :vartype principal_name_properties_applied_by_principal_name: str + :ivar user_principal_name_properties_applied_by_user_principal_name: The user principal name(if + valid). + :vartype user_principal_name_properties_applied_by_user_principal_name: str + :ivar principal_id_properties_reviewed_by_principal_id: The identity id. + :vartype principal_id_properties_reviewed_by_principal_id: str + :ivar principal_type_properties_reviewed_by_principal_type: The identity type : + user/servicePrincipal. Known values are: "user" and "servicePrincipal". + :vartype principal_type_properties_reviewed_by_principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name_properties_reviewed_by_principal_name: The identity display name. + :vartype principal_name_properties_reviewed_by_principal_name: str + :ivar user_principal_name_properties_reviewed_by_user_principal_name: The user principal + name(if valid). + :vartype user_principal_name_properties_reviewed_by_user_principal_name: str + :ivar type_properties_resource_type: The type of resource. "azureRole" + :vartype type_properties_resource_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DecisionResourceType + :ivar id_properties_resource_id: The id of resource associated with a decision record. + :vartype id_properties_resource_id: str + :ivar display_name_properties_resource_display_name: The display name of resource associated + with a decision record. + :vartype display_name_properties_resource_display_name: str + :ivar type_properties_principal_type: The type of decision target : User/ServicePrincipal. + Known values are: "user" and "servicePrincipal". + :vartype type_properties_principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DecisionTargetType + :ivar id_properties_principal_id: The id of principal whose access was reviewed. + :vartype id_properties_principal_id: str + :ivar display_name_properties_principal_display_name: The display name of the user whose access + was reviewed. + :vartype display_name_properties_principal_display_name: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "recommendation": {"readonly": True}, + "reviewed_date_time": {"readonly": True}, + "apply_result": {"readonly": True}, + "applied_date_time": {"readonly": True}, + "principal_id_properties_applied_by_principal_id": {"readonly": True}, + "principal_type_properties_applied_by_principal_type": {"readonly": True}, + "principal_name_properties_applied_by_principal_name": {"readonly": True}, + "user_principal_name_properties_applied_by_user_principal_name": {"readonly": True}, + "principal_id_properties_reviewed_by_principal_id": {"readonly": True}, + "principal_type_properties_reviewed_by_principal_type": {"readonly": True}, + "principal_name_properties_reviewed_by_principal_name": {"readonly": True}, + "user_principal_name_properties_reviewed_by_user_principal_name": {"readonly": True}, + "id_properties_resource_id": {"readonly": True}, + "display_name_properties_resource_display_name": {"readonly": True}, + "id_properties_principal_id": {"readonly": True}, + "display_name_properties_principal_display_name": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "recommendation": {"key": "properties.recommendation", "type": "str"}, + "decision": {"key": "properties.decision", "type": "str"}, + "justification": {"key": "properties.justification", "type": "str"}, + "reviewed_date_time": {"key": "properties.reviewedDateTime", "type": "iso-8601"}, + "apply_result": {"key": "properties.applyResult", "type": "str"}, + "applied_date_time": {"key": "properties.appliedDateTime", "type": "iso-8601"}, + "insights": {"key": "properties.insights", "type": "[AccessReviewDecisionInsight]"}, + "membership_types": {"key": "properties.principalResourceMembership.membershipTypes", "type": "[str]"}, + "principal_id_properties_applied_by_principal_id": {"key": "properties.appliedBy.principalId", "type": "str"}, + "principal_type_properties_applied_by_principal_type": { + "key": "properties.appliedBy.principalType", + "type": "str", + }, + "principal_name_properties_applied_by_principal_name": { + "key": "properties.appliedBy.principalName", + "type": "str", + }, + "user_principal_name_properties_applied_by_user_principal_name": { + "key": "properties.appliedBy.userPrincipalName", + "type": "str", + }, + "principal_id_properties_reviewed_by_principal_id": {"key": "properties.reviewedBy.principalId", "type": "str"}, + "principal_type_properties_reviewed_by_principal_type": { + "key": "properties.reviewedBy.principalType", + "type": "str", + }, + "principal_name_properties_reviewed_by_principal_name": { + "key": "properties.reviewedBy.principalName", + "type": "str", + }, + "user_principal_name_properties_reviewed_by_user_principal_name": { + "key": "properties.reviewedBy.userPrincipalName", + "type": "str", + }, + "type_properties_resource_type": {"key": "properties.resource.type", "type": "str"}, + "id_properties_resource_id": {"key": "properties.resource.id", "type": "str"}, + "display_name_properties_resource_display_name": {"key": "properties.resource.displayName", "type": "str"}, + "type_properties_principal_type": {"key": "properties.principal.type", "type": "str"}, + "id_properties_principal_id": {"key": "properties.principal.id", "type": "str"}, + "display_name_properties_principal_display_name": {"key": "properties.principal.displayName", "type": "str"}, + } + + def __init__( # pylint: disable=too-many-locals + self, + *, + decision: Optional[Union[str, "_models.AccessReviewResult"]] = None, + justification: Optional[str] = None, + insights: Optional[List["_models.AccessReviewDecisionInsight"]] = None, + membership_types: Optional[ + List[Union[str, "_models.AccessReviewDecisionPrincipalResourceMembershipType"]] + ] = None, + type_properties_resource_type: Optional[Union[str, "_models.DecisionResourceType"]] = None, + **kwargs + ): + """ + :keyword decision: The decision on the approval step. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + "NotReviewed", "DontKnow", and "NotNotified". + :paramtype decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewResult + :keyword justification: Justification provided by approvers for their action. + :paramtype justification: str + :keyword insights: This is the collection of insights for this decision item. + :paramtype insights: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionInsight] + :keyword membership_types: Every decision item in an access review represents a principal's + membership to a resource. This property represents details of the membership. Examples of this + detail might be whether the principal has direct access or indirect access. + :paramtype membership_types: list[str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionPrincipalResourceMembershipType] + :keyword type_properties_resource_type: The type of resource. "azureRole" + :paramtype type_properties_resource_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DecisionResourceType + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.recommendation = None + self.decision = decision + self.justification = justification + self.reviewed_date_time = None + self.apply_result = None + self.applied_date_time = None + self.insights = insights + self.membership_types = membership_types + self.principal_id_properties_applied_by_principal_id = None + self.principal_type_properties_applied_by_principal_type = None + self.principal_name_properties_applied_by_principal_name = None + self.user_principal_name_properties_applied_by_user_principal_name = None + self.principal_id_properties_reviewed_by_principal_id = None + self.principal_type_properties_reviewed_by_principal_type = None + self.principal_name_properties_reviewed_by_principal_name = None + self.user_principal_name_properties_reviewed_by_user_principal_name = None + self.type_properties_resource_type = type_properties_resource_type + self.id_properties_resource_id = None + self.display_name_properties_resource_display_name = None + self.type_properties_principal_type = None # type: Optional[str] + self.id_properties_principal_id = None + self.display_name_properties_principal_display_name = None + + +class AccessReviewDecisionIdentity(_serialization.Model): + """Target of the decision. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AccessReviewDecisionServicePrincipalIdentity, AccessReviewDecisionUserIdentity + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2021_12_01_preview.models.DecisionTargetType + :ivar id: The id of principal whose access was reviewed. + :vartype id: str + :ivar display_name: The display name of the user whose access was reviewed. + :vartype display_name: str + """ + + _validation = { + "type": {"required": True}, + "id": {"readonly": True}, + "display_name": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + } + + _subtype_map = { + "type": { + "servicePrincipal": "AccessReviewDecisionServicePrincipalIdentity", + "user": "AccessReviewDecisionUserIdentity", + } + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = None # type: Optional[str] + self.id = None + self.display_name = None + + +class AccessReviewDecisionInsight(_serialization.Model): + """Access Review Decision Insight. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review insight id. + :vartype id: str + :ivar name: The access review insight name. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar type_properties_type: The type of insight. "userSignInInsight" + :vartype type_properties_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionInsightType + :ivar insight_created_date_time: Date Time when the insight was created. + :vartype insight_created_date_time: any + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "insight_created_date_time": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "type_properties_type": {"key": "properties.type", "type": "str"}, + "insight_created_date_time": {"key": "properties.insightCreatedDateTime", "type": "object"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.type_properties_type = None # type: Optional[str] + self.insight_created_date_time = None + + +class AccessReviewDecisionInsightProperties(_serialization.Model): + """Details of the Insight. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AccessReviewDecisionUserSignInInsightProperties + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of insight. Required. "userSignInInsight" + :vartype type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionInsightType + :ivar insight_created_date_time: Date Time when the insight was created. + :vartype insight_created_date_time: any + """ + + _validation = { + "type": {"required": True}, + "insight_created_date_time": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "insight_created_date_time": {"key": "insightCreatedDateTime", "type": "object"}, + } + + _subtype_map = {"type": {"userSignInInsight": "AccessReviewDecisionUserSignInInsightProperties"}} + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = None # type: Optional[str] + self.insight_created_date_time = None + + +class AccessReviewDecisionListResult(_serialization.Model): + """List of access review decisions. + + :ivar value: Access Review Decision list. + :vartype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AccessReviewDecision]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.AccessReviewDecision"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: Access Review Decision list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AccessReviewDecisionProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Approval Step. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar recommendation: The feature- generated recommendation shown to the reviewer. Known values + are: "Approve", "Deny", and "NoInfoAvailable". + :vartype recommendation: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessRecommendationType + :ivar decision: The decision on the approval step. This value is initially set to NotReviewed. + Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", "NotReviewed", + "DontKnow", and "NotNotified". + :vartype decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewResult + :ivar justification: Justification provided by approvers for their action. + :vartype justification: str + :ivar reviewed_date_time: Date Time when a decision was taken. + :vartype reviewed_date_time: ~datetime.datetime + :ivar apply_result: The outcome of applying the decision. Known values are: "New", "Applying", + "AppliedSuccessfully", "AppliedWithUnknownFailure", "AppliedSuccessfullyButObjectNotFound", and + "ApplyNotSupported". + :vartype apply_result: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewApplyResult + :ivar applied_date_time: The date and time when the review decision was applied. + :vartype applied_date_time: ~datetime.datetime + :ivar insights: This is the collection of insights for this decision item. + :vartype insights: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionInsight] + :ivar membership_types: Every decision item in an access review represents a principal's + membership to a resource. This property represents details of the membership. Examples of this + detail might be whether the principal has direct access or indirect access. + :vartype membership_types: list[str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionPrincipalResourceMembershipType] + :ivar principal_id_applied_by_principal_id: The identity id. + :vartype principal_id_applied_by_principal_id: str + :ivar principal_type_applied_by_principal_type: The identity type : user/servicePrincipal. + Known values are: "user" and "servicePrincipal". + :vartype principal_type_applied_by_principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name_applied_by_principal_name: The identity display name. + :vartype principal_name_applied_by_principal_name: str + :ivar user_principal_name_applied_by_user_principal_name: The user principal name(if valid). + :vartype user_principal_name_applied_by_user_principal_name: str + :ivar principal_id_reviewed_by_principal_id: The identity id. + :vartype principal_id_reviewed_by_principal_id: str + :ivar principal_type_reviewed_by_principal_type: The identity type : user/servicePrincipal. + Known values are: "user" and "servicePrincipal". + :vartype principal_type_reviewed_by_principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name_reviewed_by_principal_name: The identity display name. + :vartype principal_name_reviewed_by_principal_name: str + :ivar user_principal_name_reviewed_by_user_principal_name: The user principal name(if valid). + :vartype user_principal_name_reviewed_by_user_principal_name: str + :ivar type_resource_type: The type of resource. "azureRole" + :vartype type_resource_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DecisionResourceType + :ivar id_resource_id: The id of resource associated with a decision record. + :vartype id_resource_id: str + :ivar display_name_resource_display_name: The display name of resource associated with a + decision record. + :vartype display_name_resource_display_name: str + :ivar type_principal_type: The type of decision target : User/ServicePrincipal. Known values + are: "user" and "servicePrincipal". + :vartype type_principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DecisionTargetType + :ivar id_principal_id: The id of principal whose access was reviewed. + :vartype id_principal_id: str + :ivar display_name_principal_display_name: The display name of the user whose access was + reviewed. + :vartype display_name_principal_display_name: str + """ + + _validation = { + "recommendation": {"readonly": True}, + "reviewed_date_time": {"readonly": True}, + "apply_result": {"readonly": True}, + "applied_date_time": {"readonly": True}, + "principal_id_applied_by_principal_id": {"readonly": True}, + "principal_type_applied_by_principal_type": {"readonly": True}, + "principal_name_applied_by_principal_name": {"readonly": True}, + "user_principal_name_applied_by_user_principal_name": {"readonly": True}, + "principal_id_reviewed_by_principal_id": {"readonly": True}, + "principal_type_reviewed_by_principal_type": {"readonly": True}, + "principal_name_reviewed_by_principal_name": {"readonly": True}, + "user_principal_name_reviewed_by_user_principal_name": {"readonly": True}, + "id_resource_id": {"readonly": True}, + "display_name_resource_display_name": {"readonly": True}, + "id_principal_id": {"readonly": True}, + "display_name_principal_display_name": {"readonly": True}, + } + + _attribute_map = { + "recommendation": {"key": "recommendation", "type": "str"}, + "decision": {"key": "decision", "type": "str"}, + "justification": {"key": "justification", "type": "str"}, + "reviewed_date_time": {"key": "reviewedDateTime", "type": "iso-8601"}, + "apply_result": {"key": "applyResult", "type": "str"}, + "applied_date_time": {"key": "appliedDateTime", "type": "iso-8601"}, + "insights": {"key": "insights", "type": "[AccessReviewDecisionInsight]"}, + "membership_types": {"key": "principalResourceMembership.membershipTypes", "type": "[str]"}, + "principal_id_applied_by_principal_id": {"key": "appliedBy.principalId", "type": "str"}, + "principal_type_applied_by_principal_type": {"key": "appliedBy.principalType", "type": "str"}, + "principal_name_applied_by_principal_name": {"key": "appliedBy.principalName", "type": "str"}, + "user_principal_name_applied_by_user_principal_name": {"key": "appliedBy.userPrincipalName", "type": "str"}, + "principal_id_reviewed_by_principal_id": {"key": "reviewedBy.principalId", "type": "str"}, + "principal_type_reviewed_by_principal_type": {"key": "reviewedBy.principalType", "type": "str"}, + "principal_name_reviewed_by_principal_name": {"key": "reviewedBy.principalName", "type": "str"}, + "user_principal_name_reviewed_by_user_principal_name": {"key": "reviewedBy.userPrincipalName", "type": "str"}, + "type_resource_type": {"key": "resource.type", "type": "str"}, + "id_resource_id": {"key": "resource.id", "type": "str"}, + "display_name_resource_display_name": {"key": "resource.displayName", "type": "str"}, + "type_principal_type": {"key": "principal.type", "type": "str"}, + "id_principal_id": {"key": "principal.id", "type": "str"}, + "display_name_principal_display_name": {"key": "principal.displayName", "type": "str"}, + } + + def __init__( + self, + *, + decision: Optional[Union[str, "_models.AccessReviewResult"]] = None, + justification: Optional[str] = None, + insights: Optional[List["_models.AccessReviewDecisionInsight"]] = None, + membership_types: Optional[ + List[Union[str, "_models.AccessReviewDecisionPrincipalResourceMembershipType"]] + ] = None, + type_resource_type: Optional[Union[str, "_models.DecisionResourceType"]] = None, + **kwargs + ): + """ + :keyword decision: The decision on the approval step. This value is initially set to + NotReviewed. Approvers can take action of Approve/Deny. Known values are: "Approve", "Deny", + "NotReviewed", "DontKnow", and "NotNotified". + :paramtype decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewResult + :keyword justification: Justification provided by approvers for their action. + :paramtype justification: str + :keyword insights: This is the collection of insights for this decision item. + :paramtype insights: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionInsight] + :keyword membership_types: Every decision item in an access review represents a principal's + membership to a resource. This property represents details of the membership. Examples of this + detail might be whether the principal has direct access or indirect access. + :paramtype membership_types: list[str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionPrincipalResourceMembershipType] + :keyword type_resource_type: The type of resource. "azureRole" + :paramtype type_resource_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DecisionResourceType + """ + super().__init__(**kwargs) + self.recommendation = None + self.decision = decision + self.justification = justification + self.reviewed_date_time = None + self.apply_result = None + self.applied_date_time = None + self.insights = insights + self.membership_types = membership_types + self.principal_id_applied_by_principal_id = None + self.principal_type_applied_by_principal_type = None + self.principal_name_applied_by_principal_name = None + self.user_principal_name_applied_by_user_principal_name = None + self.principal_id_reviewed_by_principal_id = None + self.principal_type_reviewed_by_principal_type = None + self.principal_name_reviewed_by_principal_name = None + self.user_principal_name_reviewed_by_user_principal_name = None + self.type_resource_type = type_resource_type + self.id_resource_id = None + self.display_name_resource_display_name = None + self.type_principal_type = None # type: Optional[str] + self.id_principal_id = None + self.display_name_principal_display_name = None + + +class AccessReviewDecisionServicePrincipalIdentity(AccessReviewDecisionIdentity): + """Service Principal Decision Target. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2021_12_01_preview.models.DecisionTargetType + :ivar id: The id of principal whose access was reviewed. + :vartype id: str + :ivar display_name: The display name of the user whose access was reviewed. + :vartype display_name: str + :ivar app_id: The appId for the service principal entity being reviewed. + :vartype app_id: str + """ + + _validation = { + "type": {"required": True}, + "id": {"readonly": True}, + "display_name": {"readonly": True}, + "app_id": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "app_id": {"key": "appId", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = "servicePrincipal" # type: str + self.app_id = None + + +class AccessReviewDecisionUserIdentity(AccessReviewDecisionIdentity): + """User Decision Target. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of decision target : User/ServicePrincipal. Required. Known values are: + "user" and "servicePrincipal". + :vartype type: str or ~azure.mgmt.authorization.v2021_12_01_preview.models.DecisionTargetType + :ivar id: The id of principal whose access was reviewed. + :vartype id: str + :ivar display_name: The display name of the user whose access was reviewed. + :vartype display_name: str + :ivar user_principal_name: The user principal name of the user whose access was reviewed. + :vartype user_principal_name: str + """ + + _validation = { + "type": {"required": True}, + "id": {"readonly": True}, + "display_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "user_principal_name": {"key": "userPrincipalName", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = "user" # type: str + self.user_principal_name = None + + +class AccessReviewDecisionUserSignInInsightProperties(AccessReviewDecisionInsightProperties): + """User Decision Target. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of insight. Required. "userSignInInsight" + :vartype type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionInsightType + :ivar insight_created_date_time: Date Time when the insight was created. + :vartype insight_created_date_time: any + :ivar last_sign_in_date_time: Date Time when the user signed into the tenant. + :vartype last_sign_in_date_time: any + """ + + _validation = { + "type": {"required": True}, + "insight_created_date_time": {"readonly": True}, + "last_sign_in_date_time": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "insight_created_date_time": {"key": "insightCreatedDateTime", "type": "object"}, + "last_sign_in_date_time": {"key": "lastSignInDateTime", "type": "object"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = "userSignInInsight" # type: str + self.last_sign_in_date_time = None + + +class AccessReviewDefaultSettings(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Access Review Default Settings. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review default settings id. This is only going to be default. + :vartype id: str + :ivar name: The access review default settings name. This is always going to be Access Review + Default Settings. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + review creator is enabled. + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to + pass justification when recording a decision. + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DefaultDecisionType + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar recommendation_look_back_duration: Recommendations for access reviews are calculated by + looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :vartype recommendation_look_back_duration: ~datetime.timedelta + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_properties_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_properties_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date + in the future. Required on create. + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :vartype type_properties_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "mail_notifications_enabled": {"key": "properties.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "properties.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "properties.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "properties.justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "properties.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "properties.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "properties.recommendationsEnabled", "type": "bool"}, + "recommendation_look_back_duration": {"key": "properties.recommendationLookBackDuration", "type": "duration"}, + "instance_duration_in_days": {"key": "properties.instanceDurationInDays", "type": "int"}, + "type_properties_recurrence_range_type": {"key": "properties.recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "properties.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "properties.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.recurrence.range.endDate", "type": "iso-8601"}, + "type_properties_recurrence_pattern_type": {"key": "properties.recurrence.pattern.type", "type": "str"}, + "interval": {"key": "properties.recurrence.pattern.interval", "type": "int"}, + } + + def __init__( + self, + *, + mail_notifications_enabled: Optional[bool] = None, + reminder_notifications_enabled: Optional[bool] = None, + default_decision_enabled: Optional[bool] = None, + justification_required_on_approval: Optional[bool] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, + auto_apply_decisions_enabled: Optional[bool] = None, + recommendations_enabled: Optional[bool] = None, + recommendation_look_back_duration: Optional[datetime.timedelta] = None, + instance_duration_in_days: Optional[int] = None, + type_properties_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, + number_of_occurrences: Optional[int] = None, + start_date: Optional[datetime.datetime] = None, + end_date: Optional[datetime.datetime] = None, + type_properties_recurrence_pattern_type: Optional[ + Union[str, "_models.AccessReviewRecurrencePatternType"] + ] = None, + interval: Optional[int] = None, + **kwargs + ): + """ + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword recommendation_look_back_duration: Recommendations for access reviews are calculated + by looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :paramtype recommendation_look_back_duration: ~datetime.timedelta + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_properties_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_properties_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_properties_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :paramtype type_properties_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.mail_notifications_enabled = mail_notifications_enabled + self.reminder_notifications_enabled = reminder_notifications_enabled + self.default_decision_enabled = default_decision_enabled + self.justification_required_on_approval = justification_required_on_approval + self.default_decision = default_decision + self.auto_apply_decisions_enabled = auto_apply_decisions_enabled + self.recommendations_enabled = recommendations_enabled + self.recommendation_look_back_duration = recommendation_look_back_duration + self.instance_duration_in_days = instance_duration_in_days + self.type_properties_recurrence_range_type = type_properties_recurrence_range_type + self.number_of_occurrences = number_of_occurrences + self.start_date = start_date + self.end_date = end_date + self.type_properties_recurrence_pattern_type = type_properties_recurrence_pattern_type + self.interval = interval + + +class AccessReviewHistoryDefinition(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Access Review History Definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review history definition id. + :vartype id: str + :ivar name: The access review history definition unique id. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar display_name: The display name for the history definition. + :vartype display_name: str + :ivar review_history_period_start_date_time: Date time used when selecting review data, all + reviews included in data start on or after this date. For use only with one-time/non-recurring + reports. + :vartype review_history_period_start_date_time: ~datetime.datetime + :ivar review_history_period_end_date_time: Date time used when selecting review data, all + reviews included in data end on or before this date. For use only with one-time/non-recurring + reports. + :vartype review_history_period_end_date_time: ~datetime.datetime + :ivar decisions: Collection of review decisions which the history data should be filtered on. + For example if Approve and Deny are supplied the data will only contain review results in which + the decision maker approved or denied a review request. + :vartype decisions: list[str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewResult] + :ivar status: This read-only field specifies the of the requested review history data. This is + either requested, in-progress, done or error. Known values are: "Requested", "InProgress", + "Done", and "Error". + :vartype status: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinitionStatus + :ivar created_date_time: Date time when history definition was created. + :vartype created_date_time: ~datetime.datetime + :ivar scopes: A collection of scopes used when selecting review history data. + :vartype scopes: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScope] + :ivar instances: Set of access review history instances for this history definition. + :vartype instances: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance] + :ivar type_properties_settings_range_type: The recurrence range type. The possible values are: + endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_properties_settings_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date + in the future. Required on create. + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_properties_settings_pattern_type: The recurrence type : weekly, monthly, etc. Known + values are: "weekly" and "absoluteMonthly". + :vartype type_properties_settings_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int + :ivar principal_id: The identity id. + :vartype principal_id: str + :ivar principal_type: The identity type : user/servicePrincipal. Known values are: "user" and + "servicePrincipal". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name: The identity display name. + :vartype principal_name: str + :ivar user_principal_name: The user principal name(if valid). + :vartype user_principal_name: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "review_history_period_start_date_time": {"readonly": True}, + "review_history_period_end_date_time": {"readonly": True}, + "status": {"readonly": True}, + "created_date_time": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "review_history_period_start_date_time": { + "key": "properties.reviewHistoryPeriodStartDateTime", + "type": "iso-8601", + }, + "review_history_period_end_date_time": {"key": "properties.reviewHistoryPeriodEndDateTime", "type": "iso-8601"}, + "decisions": {"key": "properties.decisions", "type": "[str]"}, + "status": {"key": "properties.status", "type": "str"}, + "created_date_time": {"key": "properties.createdDateTime", "type": "iso-8601"}, + "scopes": {"key": "properties.scopes", "type": "[AccessReviewScope]"}, + "instances": {"key": "properties.instances", "type": "[AccessReviewHistoryInstance]"}, + "type_properties_settings_range_type": {"key": "properties.settings.range.type", "type": "str"}, + "number_of_occurrences": {"key": "properties.settings.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "properties.settings.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.settings.range.endDate", "type": "iso-8601"}, + "type_properties_settings_pattern_type": {"key": "properties.settings.pattern.type", "type": "str"}, + "interval": {"key": "properties.settings.pattern.interval", "type": "int"}, + "principal_id": {"key": "properties.createdBy.principalId", "type": "str"}, + "principal_type": {"key": "properties.createdBy.principalType", "type": "str"}, + "principal_name": {"key": "properties.createdBy.principalName", "type": "str"}, + "user_principal_name": {"key": "properties.createdBy.userPrincipalName", "type": "str"}, + } + + def __init__( + self, + *, + display_name: Optional[str] = None, + decisions: Optional[List[Union[str, "_models.AccessReviewResult"]]] = None, + scopes: Optional[List["_models.AccessReviewScope"]] = None, + instances: Optional[List["_models.AccessReviewHistoryInstance"]] = None, + type_properties_settings_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, + number_of_occurrences: Optional[int] = None, + start_date: Optional[datetime.datetime] = None, + end_date: Optional[datetime.datetime] = None, + type_properties_settings_pattern_type: Optional[Union[str, "_models.AccessReviewRecurrencePatternType"]] = None, + interval: Optional[int] = None, + **kwargs + ): + """ + :keyword display_name: The display name for the history definition. + :paramtype display_name: str + :keyword decisions: Collection of review decisions which the history data should be filtered + on. For example if Approve and Deny are supplied the data will only contain review results in + which the decision maker approved or denied a review request. + :paramtype decisions: list[str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewResult] + :keyword scopes: A collection of scopes used when selecting review history data. + :paramtype scopes: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScope] + :keyword instances: Set of access review history instances for this history definition. + :paramtype instances: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance] + :keyword type_properties_settings_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_properties_settings_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_properties_settings_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :paramtype type_properties_settings_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.display_name = display_name + self.review_history_period_start_date_time = None + self.review_history_period_end_date_time = None + self.decisions = decisions + self.status = None + self.created_date_time = None + self.scopes = scopes + self.instances = instances + self.type_properties_settings_range_type = type_properties_settings_range_type + self.number_of_occurrences = number_of_occurrences + self.start_date = start_date + self.end_date = end_date + self.type_properties_settings_pattern_type = type_properties_settings_pattern_type + self.interval = interval + self.principal_id = None + self.principal_type = None + self.principal_name = None + self.user_principal_name = None + + +class AccessReviewHistoryDefinitionInstanceListResult(_serialization.Model): + """List of Access Review History Instances. + + :ivar value: Access Review History Definition's Instance list. + :vartype value: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AccessReviewHistoryInstance]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.AccessReviewHistoryInstance"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Access Review History Definition's Instance list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AccessReviewHistoryDefinitionListResult(_serialization.Model): + """List of Access Review History Definitions. + + :ivar value: Access Review History Definition list. + :vartype value: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AccessReviewHistoryDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.AccessReviewHistoryDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Access Review History Definition list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AccessReviewHistoryDefinitionProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Access Review History Instances. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar display_name: The display name for the history definition. + :vartype display_name: str + :ivar review_history_period_start_date_time: Date time used when selecting review data, all + reviews included in data start on or after this date. For use only with one-time/non-recurring + reports. + :vartype review_history_period_start_date_time: ~datetime.datetime + :ivar review_history_period_end_date_time: Date time used when selecting review data, all + reviews included in data end on or before this date. For use only with one-time/non-recurring + reports. + :vartype review_history_period_end_date_time: ~datetime.datetime + :ivar decisions: Collection of review decisions which the history data should be filtered on. + For example if Approve and Deny are supplied the data will only contain review results in which + the decision maker approved or denied a review request. + :vartype decisions: list[str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewResult] + :ivar status: This read-only field specifies the of the requested review history data. This is + either requested, in-progress, done or error. Known values are: "Requested", "InProgress", + "Done", and "Error". + :vartype status: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinitionStatus + :ivar created_date_time: Date time when history definition was created. + :vartype created_date_time: ~datetime.datetime + :ivar scopes: A collection of scopes used when selecting review history data. + :vartype scopes: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScope] + :ivar instances: Set of access review history instances for this history definition. + :vartype instances: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance] + :ivar type_settings_range_type: The recurrence range type. The possible values are: endDate, + noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_settings_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date + in the future. Required on create. + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_settings_pattern_type: The recurrence type : weekly, monthly, etc. Known values are: + "weekly" and "absoluteMonthly". + :vartype type_settings_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int + :ivar principal_id: The identity id. + :vartype principal_id: str + :ivar principal_type: The identity type : user/servicePrincipal. Known values are: "user" and + "servicePrincipal". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name: The identity display name. + :vartype principal_name: str + :ivar user_principal_name: The user principal name(if valid). + :vartype user_principal_name: str + """ + + _validation = { + "review_history_period_start_date_time": {"readonly": True}, + "review_history_period_end_date_time": {"readonly": True}, + "status": {"readonly": True}, + "created_date_time": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, + } + + _attribute_map = { + "display_name": {"key": "displayName", "type": "str"}, + "review_history_period_start_date_time": {"key": "reviewHistoryPeriodStartDateTime", "type": "iso-8601"}, + "review_history_period_end_date_time": {"key": "reviewHistoryPeriodEndDateTime", "type": "iso-8601"}, + "decisions": {"key": "decisions", "type": "[str]"}, + "status": {"key": "status", "type": "str"}, + "created_date_time": {"key": "createdDateTime", "type": "iso-8601"}, + "scopes": {"key": "scopes", "type": "[AccessReviewScope]"}, + "instances": {"key": "instances", "type": "[AccessReviewHistoryInstance]"}, + "type_settings_range_type": {"key": "settings.range.type", "type": "str"}, + "number_of_occurrences": {"key": "settings.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "settings.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "settings.range.endDate", "type": "iso-8601"}, + "type_settings_pattern_type": {"key": "settings.pattern.type", "type": "str"}, + "interval": {"key": "settings.pattern.interval", "type": "int"}, + "principal_id": {"key": "createdBy.principalId", "type": "str"}, + "principal_type": {"key": "createdBy.principalType", "type": "str"}, + "principal_name": {"key": "createdBy.principalName", "type": "str"}, + "user_principal_name": {"key": "createdBy.userPrincipalName", "type": "str"}, + } + + def __init__( + self, + *, + display_name: Optional[str] = None, + decisions: Optional[List[Union[str, "_models.AccessReviewResult"]]] = None, + scopes: Optional[List["_models.AccessReviewScope"]] = None, + instances: Optional[List["_models.AccessReviewHistoryInstance"]] = None, + type_settings_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, + number_of_occurrences: Optional[int] = None, + start_date: Optional[datetime.datetime] = None, + end_date: Optional[datetime.datetime] = None, + type_settings_pattern_type: Optional[Union[str, "_models.AccessReviewRecurrencePatternType"]] = None, + interval: Optional[int] = None, + **kwargs + ): + """ + :keyword display_name: The display name for the history definition. + :paramtype display_name: str + :keyword decisions: Collection of review decisions which the history data should be filtered + on. For example if Approve and Deny are supplied the data will only contain review results in + which the decision maker approved or denied a review request. + :paramtype decisions: list[str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewResult] + :keyword scopes: A collection of scopes used when selecting review history data. + :paramtype scopes: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScope] + :keyword instances: Set of access review history instances for this history definition. + :paramtype instances: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance] + :keyword type_settings_range_type: The recurrence range type. The possible values are: endDate, + noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_settings_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_settings_pattern_type: The recurrence type : weekly, monthly, etc. Known values + are: "weekly" and "absoluteMonthly". + :paramtype type_settings_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) + self.display_name = display_name + self.review_history_period_start_date_time = None + self.review_history_period_end_date_time = None + self.decisions = decisions + self.status = None + self.created_date_time = None + self.scopes = scopes + self.instances = instances + self.type_settings_range_type = type_settings_range_type + self.number_of_occurrences = number_of_occurrences + self.start_date = start_date + self.end_date = end_date + self.type_settings_pattern_type = type_settings_pattern_type + self.interval = interval + self.principal_id = None + self.principal_type = None + self.principal_name = None + self.user_principal_name = None + + +class AccessReviewHistoryInstance(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Access Review History Definition Instance. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review history definition instance id. + :vartype id: str + :ivar name: The access review history definition instance unique id. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar review_history_period_start_date_time: Date time used when selecting review data, all + reviews included in data start on or after this date. For use only with one-time/non-recurring + reports. + :vartype review_history_period_start_date_time: ~datetime.datetime + :ivar review_history_period_end_date_time: Date time used when selecting review data, all + reviews included in data end on or before this date. For use only with one-time/non-recurring + reports. + :vartype review_history_period_end_date_time: ~datetime.datetime + :ivar display_name: The display name for the parent history definition. + :vartype display_name: str + :ivar status: Status of the requested review history instance data. This is either requested, + in-progress, done or error. The state transitions are as follows - Requested -> InProgress -> + Done -> Expired. Known values are: "Requested", "InProgress", "Done", and "Error". + :vartype status: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinitionStatus + :ivar run_date_time: Date time when the history data report is scheduled to be generated. + :vartype run_date_time: ~datetime.datetime + :ivar fulfilled_date_time: Date time when the history data report is scheduled to be generated. + :vartype fulfilled_date_time: ~datetime.datetime + :ivar download_uri: Uri which can be used to retrieve review history data. To generate this + Uri, generateDownloadUri() must be called for a specific accessReviewHistoryDefinitionInstance. + The link expires after a 24 hour period. Callers can see the expiration date time by looking at + the 'se' parameter in the generated uri. + :vartype download_uri: str + :ivar expiration: Date time when history data report expires and the associated data is + deleted. + :vartype expiration: ~datetime.datetime + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "status": {"readonly": True}, + "download_uri": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "review_history_period_start_date_time": { + "key": "properties.reviewHistoryPeriodStartDateTime", + "type": "iso-8601", + }, + "review_history_period_end_date_time": {"key": "properties.reviewHistoryPeriodEndDateTime", "type": "iso-8601"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "run_date_time": {"key": "properties.runDateTime", "type": "iso-8601"}, + "fulfilled_date_time": {"key": "properties.fulfilledDateTime", "type": "iso-8601"}, + "download_uri": {"key": "properties.downloadUri", "type": "str"}, + "expiration": {"key": "properties.expiration", "type": "iso-8601"}, + } + + def __init__( + self, + *, + review_history_period_start_date_time: Optional[datetime.datetime] = None, + review_history_period_end_date_time: Optional[datetime.datetime] = None, + display_name: Optional[str] = None, + run_date_time: Optional[datetime.datetime] = None, + fulfilled_date_time: Optional[datetime.datetime] = None, + expiration: Optional[datetime.datetime] = None, + **kwargs + ): + """ + :keyword review_history_period_start_date_time: Date time used when selecting review data, all + reviews included in data start on or after this date. For use only with one-time/non-recurring + reports. + :paramtype review_history_period_start_date_time: ~datetime.datetime + :keyword review_history_period_end_date_time: Date time used when selecting review data, all + reviews included in data end on or before this date. For use only with one-time/non-recurring + reports. + :paramtype review_history_period_end_date_time: ~datetime.datetime + :keyword display_name: The display name for the parent history definition. + :paramtype display_name: str + :keyword run_date_time: Date time when the history data report is scheduled to be generated. + :paramtype run_date_time: ~datetime.datetime + :keyword fulfilled_date_time: Date time when the history data report is scheduled to be + generated. + :paramtype fulfilled_date_time: ~datetime.datetime + :keyword expiration: Date time when history data report expires and the associated data is + deleted. + :paramtype expiration: ~datetime.datetime + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.review_history_period_start_date_time = review_history_period_start_date_time + self.review_history_period_end_date_time = review_history_period_end_date_time + self.display_name = display_name + self.status = None + self.run_date_time = run_date_time + self.fulfilled_date_time = fulfilled_date_time + self.download_uri = None + self.expiration = expiration + + +class AccessReviewInstance(_serialization.Model): + """Access Review Instance. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review instance id. + :vartype id: str + :ivar name: The access review instance name. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar status: This read-only field specifies the status of an access review instance. Known + values are: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", + "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". + :vartype status: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceStatus + :ivar start_date_time: The DateTime when the review instance is scheduled to be start. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: The DateTime when the review instance is scheduled to end. + :vartype end_date_time: ~datetime.datetime + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :ivar backup_reviewers: This is the collection of backup reviewers. + :vartype backup_reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a + review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". + :vartype reviewers_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceReviewersType + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date_time": {"key": "properties.startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "properties.endDateTime", "type": "iso-8601"}, + "reviewers": {"key": "properties.reviewers", "type": "[AccessReviewReviewer]"}, + "backup_reviewers": {"key": "properties.backupReviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "properties.reviewersType", "type": "str"}, + } + + def __init__( + self, + *, + start_date_time: Optional[datetime.datetime] = None, + end_date_time: Optional[datetime.datetime] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + backup_reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + **kwargs + ): + """ + :keyword start_date_time: The DateTime when the review instance is scheduled to be start. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: The DateTime when the review instance is scheduled to end. + :paramtype end_date_time: ~datetime.datetime + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :keyword backup_reviewers: This is the collection of backup reviewers. + :paramtype backup_reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.status = None + self.start_date_time = start_date_time + self.end_date_time = end_date_time + self.reviewers = reviewers + self.backup_reviewers = backup_reviewers + self.reviewers_type = None + + +class AccessReviewInstanceListResult(_serialization.Model): + """List of Access Review Instances. + + :ivar value: Access Review Instance list. + :vartype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AccessReviewInstance]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.AccessReviewInstance"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: Access Review Instance list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AccessReviewInstanceProperties(_serialization.Model): + """Access Review Instance properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar status: This read-only field specifies the status of an access review instance. Known + values are: "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", + "Completing", "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". + :vartype status: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceStatus + :ivar start_date_time: The DateTime when the review instance is scheduled to be start. + :vartype start_date_time: ~datetime.datetime + :ivar end_date_time: The DateTime when the review instance is scheduled to end. + :vartype end_date_time: ~datetime.datetime + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :ivar backup_reviewers: This is the collection of backup reviewers. + :vartype backup_reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a + review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". + :vartype reviewers_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceReviewersType + """ + + _validation = { + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + } + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + "start_date_time": {"key": "startDateTime", "type": "iso-8601"}, + "end_date_time": {"key": "endDateTime", "type": "iso-8601"}, + "reviewers": {"key": "reviewers", "type": "[AccessReviewReviewer]"}, + "backup_reviewers": {"key": "backupReviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "reviewersType", "type": "str"}, + } + + def __init__( + self, + *, + start_date_time: Optional[datetime.datetime] = None, + end_date_time: Optional[datetime.datetime] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + backup_reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + **kwargs + ): + """ + :keyword start_date_time: The DateTime when the review instance is scheduled to be start. + :paramtype start_date_time: ~datetime.datetime + :keyword end_date_time: The DateTime when the review instance is scheduled to end. + :paramtype end_date_time: ~datetime.datetime + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :keyword backup_reviewers: This is the collection of backup reviewers. + :paramtype backup_reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + """ + super().__init__(**kwargs) + self.status = None + self.start_date_time = start_date_time + self.end_date_time = end_date_time + self.reviewers = reviewers + self.backup_reviewers = backup_reviewers + self.reviewers_type = None + + +class AccessReviewReviewer(_serialization.Model): + """Descriptor for what needs to be reviewed. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The id of the reviewer(user/servicePrincipal). + :vartype principal_id: str + :ivar principal_type: The identity type : user/servicePrincipal. Known values are: "user" and + "servicePrincipal". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewerType + """ + + _validation = { + "principal_type": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "principal_type": {"key": "principalType", "type": "str"}, + } + + def __init__(self, *, principal_id: Optional[str] = None, **kwargs): + """ + :keyword principal_id: The id of the reviewer(user/servicePrincipal). + :paramtype principal_id: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.principal_type = None + + +class AccessReviewScheduleDefinition(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Access Review Schedule Definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The access review schedule definition id. + :vartype id: str + :ivar name: The access review schedule definition unique id. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar display_name: The display name for the schedule definition. + :vartype display_name: str + :ivar status: This read-only field specifies the status of an accessReview. Known values are: + "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", "Completing", + "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". + :vartype status: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionStatus + :ivar description_for_admins: The description provided by the access review creator and visible + to admins. + :vartype description_for_admins: str + :ivar description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :vartype description_for_reviewers: str + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :ivar backup_reviewers: This is the collection of backup reviewers. + :vartype backup_reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a + review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". + :vartype reviewers_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionReviewersType + :ivar instances: This is the collection of instances returned when one does an expand on it. + :vartype instances: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :ivar resource_id: ResourceId in which this review is getting created. + :vartype resource_id: str + :ivar role_definition_id: This is used to indicate the role being reviewed. + :vartype role_definition_id: str + :ivar principal_type_properties_scope_principal_type: The identity type user/servicePrincipal + to review. Known values are: "user", "guestUser", "servicePrincipal", "user,group", and + "redeemedGuestUser". + :vartype principal_type_properties_scope_principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScopePrincipalType + :ivar assignment_state: The role assignment state eligible/active to review. Known values are: + "eligible" and "active". + :vartype assignment_state: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScopeAssignmentState + :ivar inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :vartype inactive_duration: ~datetime.timedelta + :ivar expand_nested_memberships: Flag to indicate whether to expand nested memberships or not. + :vartype expand_nested_memberships: bool + :ivar include_inherited_access: Flag to indicate whether to expand nested memberships or not. + :vartype include_inherited_access: bool + :ivar include_access_below_resource: Flag to indicate whether to expand nested memberships or + not. + :vartype include_access_below_resource: bool + :ivar exclude_resource_id: This is used to indicate the resource id(s) to exclude. + :vartype exclude_resource_id: str + :ivar exclude_role_definition_id: This is used to indicate the role definition id(s) to + exclude. + :vartype exclude_role_definition_id: str + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + review creator is enabled. + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to + pass justification when recording a decision. + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DefaultDecisionType + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar recommendation_look_back_duration: Recommendations for access reviews are calculated by + looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :vartype recommendation_look_back_duration: ~datetime.timedelta + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_properties_settings_recurrence_range_type: The recurrence range type. The possible + values are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_properties_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date + in the future. Required on create. + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, + etc. Known values are: "weekly" and "absoluteMonthly". + :vartype type_properties_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int + :ivar principal_id: The identity id. + :vartype principal_id: str + :ivar principal_type_properties_created_by_principal_type: The identity type : + user/servicePrincipal. Known values are: "user" and "servicePrincipal". + :vartype principal_type_properties_created_by_principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name: The identity display name. + :vartype principal_name: str + :ivar user_principal_name: The user principal name(if valid). + :vartype user_principal_name: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + "resource_id": {"readonly": True}, + "role_definition_id": {"readonly": True}, + "principal_type_properties_scope_principal_type": {"readonly": True}, + "assignment_state": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type_properties_created_by_principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "description_for_admins": {"key": "properties.descriptionForAdmins", "type": "str"}, + "description_for_reviewers": {"key": "properties.descriptionForReviewers", "type": "str"}, + "reviewers": {"key": "properties.reviewers", "type": "[AccessReviewReviewer]"}, + "backup_reviewers": {"key": "properties.backupReviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "properties.reviewersType", "type": "str"}, + "instances": {"key": "properties.instances", "type": "[AccessReviewInstance]"}, + "resource_id": {"key": "properties.scope.resourceId", "type": "str"}, + "role_definition_id": {"key": "properties.scope.roleDefinitionId", "type": "str"}, + "principal_type_properties_scope_principal_type": {"key": "properties.scope.principalType", "type": "str"}, + "assignment_state": {"key": "properties.scope.assignmentState", "type": "str"}, + "inactive_duration": {"key": "properties.scope.inactiveDuration", "type": "duration"}, + "expand_nested_memberships": {"key": "properties.scope.expandNestedMemberships", "type": "bool"}, + "include_inherited_access": {"key": "properties.scope.includeInheritedAccess", "type": "bool"}, + "include_access_below_resource": {"key": "properties.scope.includeAccessBelowResource", "type": "bool"}, + "exclude_resource_id": {"key": "properties.scope.excludeResourceId", "type": "str"}, + "exclude_role_definition_id": {"key": "properties.scope.excludeRoleDefinitionId", "type": "str"}, + "mail_notifications_enabled": {"key": "properties.settings.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "properties.settings.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "properties.settings.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": { + "key": "properties.settings.justificationRequiredOnApproval", + "type": "bool", + }, + "default_decision": {"key": "properties.settings.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "properties.settings.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "properties.settings.recommendationsEnabled", "type": "bool"}, + "recommendation_look_back_duration": { + "key": "properties.settings.recommendationLookBackDuration", + "type": "duration", + }, + "instance_duration_in_days": {"key": "properties.settings.instanceDurationInDays", "type": "int"}, + "type_properties_settings_recurrence_range_type": { + "key": "properties.settings.recurrence.range.type", + "type": "str", + }, + "number_of_occurrences": {"key": "properties.settings.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "properties.settings.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.settings.recurrence.range.endDate", "type": "iso-8601"}, + "type_properties_settings_recurrence_pattern_type": { + "key": "properties.settings.recurrence.pattern.type", + "type": "str", + }, + "interval": {"key": "properties.settings.recurrence.pattern.interval", "type": "int"}, + "principal_id": {"key": "properties.createdBy.principalId", "type": "str"}, + "principal_type_properties_created_by_principal_type": { + "key": "properties.createdBy.principalType", + "type": "str", + }, + "principal_name": {"key": "properties.createdBy.principalName", "type": "str"}, + "user_principal_name": {"key": "properties.createdBy.userPrincipalName", "type": "str"}, + } + + def __init__( # pylint: disable=too-many-locals + self, + *, + display_name: Optional[str] = None, + description_for_admins: Optional[str] = None, + description_for_reviewers: Optional[str] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + backup_reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + instances: Optional[List["_models.AccessReviewInstance"]] = None, + inactive_duration: Optional[datetime.timedelta] = None, + expand_nested_memberships: Optional[bool] = None, + include_inherited_access: Optional[bool] = None, + include_access_below_resource: Optional[bool] = None, + exclude_resource_id: Optional[str] = None, + exclude_role_definition_id: Optional[str] = None, + mail_notifications_enabled: Optional[bool] = None, + reminder_notifications_enabled: Optional[bool] = None, + default_decision_enabled: Optional[bool] = None, + justification_required_on_approval: Optional[bool] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, + auto_apply_decisions_enabled: Optional[bool] = None, + recommendations_enabled: Optional[bool] = None, + recommendation_look_back_duration: Optional[datetime.timedelta] = None, + instance_duration_in_days: Optional[int] = None, + type_properties_settings_recurrence_range_type: Optional[ + Union[str, "_models.AccessReviewRecurrenceRangeType"] + ] = None, + number_of_occurrences: Optional[int] = None, + start_date: Optional[datetime.datetime] = None, + end_date: Optional[datetime.datetime] = None, + type_properties_settings_recurrence_pattern_type: Optional[ + Union[str, "_models.AccessReviewRecurrencePatternType"] + ] = None, + interval: Optional[int] = None, + **kwargs + ): + """ + :keyword display_name: The display name for the schedule definition. + :paramtype display_name: str + :keyword description_for_admins: The description provided by the access review creator and + visible to admins. + :paramtype description_for_admins: str + :keyword description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :paramtype description_for_reviewers: str + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :keyword backup_reviewers: This is the collection of backup reviewers. + :paramtype backup_reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :keyword instances: This is the collection of instances returned when one does an expand on it. + :paramtype instances: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :keyword inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :paramtype inactive_duration: ~datetime.timedelta + :keyword expand_nested_memberships: Flag to indicate whether to expand nested memberships or + not. + :paramtype expand_nested_memberships: bool + :keyword include_inherited_access: Flag to indicate whether to expand nested memberships or + not. + :paramtype include_inherited_access: bool + :keyword include_access_below_resource: Flag to indicate whether to expand nested memberships + or not. + :paramtype include_access_below_resource: bool + :keyword exclude_resource_id: This is used to indicate the resource id(s) to exclude. + :paramtype exclude_resource_id: str + :keyword exclude_role_definition_id: This is used to indicate the role definition id(s) to + exclude. + :paramtype exclude_role_definition_id: str + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword recommendation_look_back_duration: Recommendations for access reviews are calculated + by looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :paramtype recommendation_look_back_duration: ~datetime.timedelta + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_properties_settings_recurrence_range_type: The recurrence range type. The + possible values are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and + "numbered". + :paramtype type_properties_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_properties_settings_recurrence_pattern_type: The recurrence type : weekly, + monthly, etc. Known values are: "weekly" and "absoluteMonthly". + :paramtype type_properties_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.display_name = display_name + self.status = None + self.description_for_admins = description_for_admins + self.description_for_reviewers = description_for_reviewers + self.reviewers = reviewers + self.backup_reviewers = backup_reviewers + self.reviewers_type = None + self.instances = instances + self.resource_id = None + self.role_definition_id = None + self.principal_type_properties_scope_principal_type = None + self.assignment_state = None + self.inactive_duration = inactive_duration + self.expand_nested_memberships = expand_nested_memberships + self.include_inherited_access = include_inherited_access + self.include_access_below_resource = include_access_below_resource + self.exclude_resource_id = exclude_resource_id + self.exclude_role_definition_id = exclude_role_definition_id + self.mail_notifications_enabled = mail_notifications_enabled + self.reminder_notifications_enabled = reminder_notifications_enabled + self.default_decision_enabled = default_decision_enabled + self.justification_required_on_approval = justification_required_on_approval + self.default_decision = default_decision + self.auto_apply_decisions_enabled = auto_apply_decisions_enabled + self.recommendations_enabled = recommendations_enabled + self.recommendation_look_back_duration = recommendation_look_back_duration + self.instance_duration_in_days = instance_duration_in_days + self.type_properties_settings_recurrence_range_type = type_properties_settings_recurrence_range_type + self.number_of_occurrences = number_of_occurrences + self.start_date = start_date + self.end_date = end_date + self.type_properties_settings_recurrence_pattern_type = type_properties_settings_recurrence_pattern_type + self.interval = interval + self.principal_id = None + self.principal_type_properties_created_by_principal_type = None + self.principal_name = None + self.user_principal_name = None + + +class AccessReviewScheduleDefinitionListResult(_serialization.Model): + """List of Access Review Schedule Definitions. + + :ivar value: Access Review Schedule Definition list. + :vartype value: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AccessReviewScheduleDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.AccessReviewScheduleDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Access Review Schedule Definition list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AccessReviewScheduleDefinitionProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Access Review. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar display_name: The display name for the schedule definition. + :vartype display_name: str + :ivar status: This read-only field specifies the status of an accessReview. Known values are: + "NotStarted", "InProgress", "Completed", "Applied", "Initializing", "Applying", "Completing", + "Scheduled", "AutoReviewing", "AutoReviewed", and "Starting". + :vartype status: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionStatus + :ivar description_for_admins: The description provided by the access review creator and visible + to admins. + :vartype description_for_admins: str + :ivar description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :vartype description_for_reviewers: str + :ivar reviewers: This is the collection of reviewers. + :vartype reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :ivar backup_reviewers: This is the collection of backup reviewers. + :vartype backup_reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :ivar reviewers_type: This field specifies the type of reviewers for a review. Usually for a + review, reviewers are explicitly assigned. However, in some cases, the reviewers may not be + assigned and instead be chosen dynamically. For example managers review or self review. Known + values are: "Assigned", "Self", and "Managers". + :vartype reviewers_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionReviewersType + :ivar instances: This is the collection of instances returned when one does an expand on it. + :vartype instances: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :ivar resource_id: ResourceId in which this review is getting created. + :vartype resource_id: str + :ivar role_definition_id: This is used to indicate the role being reviewed. + :vartype role_definition_id: str + :ivar principal_type_scope_principal_type: The identity type user/servicePrincipal to review. + Known values are: "user", "guestUser", "servicePrincipal", "user,group", and + "redeemedGuestUser". + :vartype principal_type_scope_principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScopePrincipalType + :ivar assignment_state: The role assignment state eligible/active to review. Known values are: + "eligible" and "active". + :vartype assignment_state: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScopeAssignmentState + :ivar inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :vartype inactive_duration: ~datetime.timedelta + :ivar expand_nested_memberships: Flag to indicate whether to expand nested memberships or not. + :vartype expand_nested_memberships: bool + :ivar include_inherited_access: Flag to indicate whether to expand nested memberships or not. + :vartype include_inherited_access: bool + :ivar include_access_below_resource: Flag to indicate whether to expand nested memberships or + not. + :vartype include_access_below_resource: bool + :ivar exclude_resource_id: This is used to indicate the resource id(s) to exclude. + :vartype exclude_resource_id: str + :ivar exclude_role_definition_id: This is used to indicate the role definition id(s) to + exclude. + :vartype exclude_role_definition_id: str + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + review creator is enabled. + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to + pass justification when recording a decision. + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DefaultDecisionType + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar recommendation_look_back_duration: Recommendations for access reviews are calculated by + looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :vartype recommendation_look_back_duration: ~datetime.timedelta + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_settings_recurrence_range_type: The recurrence range type. The possible values are: + endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date + in the future. Required on create. + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known + values are: "weekly" and "absoluteMonthly". + :vartype type_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int + :ivar principal_id: The identity id. + :vartype principal_id: str + :ivar principal_type_created_by_principal_type: The identity type : user/servicePrincipal. + Known values are: "user" and "servicePrincipal". + :vartype principal_type_created_by_principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewActorIdentityType + :ivar principal_name: The identity display name. + :vartype principal_name: str + :ivar user_principal_name: The user principal name(if valid). + :vartype user_principal_name: str + """ + + _validation = { + "status": {"readonly": True}, + "reviewers_type": {"readonly": True}, + "resource_id": {"readonly": True}, + "role_definition_id": {"readonly": True}, + "principal_type_scope_principal_type": {"readonly": True}, + "assignment_state": {"readonly": True}, + "principal_id": {"readonly": True}, + "principal_type_created_by_principal_type": {"readonly": True}, + "principal_name": {"readonly": True}, + "user_principal_name": {"readonly": True}, + } + + _attribute_map = { + "display_name": {"key": "displayName", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "description_for_admins": {"key": "descriptionForAdmins", "type": "str"}, + "description_for_reviewers": {"key": "descriptionForReviewers", "type": "str"}, + "reviewers": {"key": "reviewers", "type": "[AccessReviewReviewer]"}, + "backup_reviewers": {"key": "backupReviewers", "type": "[AccessReviewReviewer]"}, + "reviewers_type": {"key": "reviewersType", "type": "str"}, + "instances": {"key": "instances", "type": "[AccessReviewInstance]"}, + "resource_id": {"key": "scope.resourceId", "type": "str"}, + "role_definition_id": {"key": "scope.roleDefinitionId", "type": "str"}, + "principal_type_scope_principal_type": {"key": "scope.principalType", "type": "str"}, + "assignment_state": {"key": "scope.assignmentState", "type": "str"}, + "inactive_duration": {"key": "scope.inactiveDuration", "type": "duration"}, + "expand_nested_memberships": {"key": "scope.expandNestedMemberships", "type": "bool"}, + "include_inherited_access": {"key": "scope.includeInheritedAccess", "type": "bool"}, + "include_access_below_resource": {"key": "scope.includeAccessBelowResource", "type": "bool"}, + "exclude_resource_id": {"key": "scope.excludeResourceId", "type": "str"}, + "exclude_role_definition_id": {"key": "scope.excludeRoleDefinitionId", "type": "str"}, + "mail_notifications_enabled": {"key": "settings.mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "settings.reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "settings.defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "settings.justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "settings.defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "settings.autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "settings.recommendationsEnabled", "type": "bool"}, + "recommendation_look_back_duration": {"key": "settings.recommendationLookBackDuration", "type": "duration"}, + "instance_duration_in_days": {"key": "settings.instanceDurationInDays", "type": "int"}, + "type_settings_recurrence_range_type": {"key": "settings.recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "settings.recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "settings.recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "settings.recurrence.range.endDate", "type": "iso-8601"}, + "type_settings_recurrence_pattern_type": {"key": "settings.recurrence.pattern.type", "type": "str"}, + "interval": {"key": "settings.recurrence.pattern.interval", "type": "int"}, + "principal_id": {"key": "createdBy.principalId", "type": "str"}, + "principal_type_created_by_principal_type": {"key": "createdBy.principalType", "type": "str"}, + "principal_name": {"key": "createdBy.principalName", "type": "str"}, + "user_principal_name": {"key": "createdBy.userPrincipalName", "type": "str"}, + } + + def __init__( # pylint: disable=too-many-locals + self, + *, + display_name: Optional[str] = None, + description_for_admins: Optional[str] = None, + description_for_reviewers: Optional[str] = None, + reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + backup_reviewers: Optional[List["_models.AccessReviewReviewer"]] = None, + instances: Optional[List["_models.AccessReviewInstance"]] = None, + inactive_duration: Optional[datetime.timedelta] = None, + expand_nested_memberships: Optional[bool] = None, + include_inherited_access: Optional[bool] = None, + include_access_below_resource: Optional[bool] = None, + exclude_resource_id: Optional[str] = None, + exclude_role_definition_id: Optional[str] = None, + mail_notifications_enabled: Optional[bool] = None, + reminder_notifications_enabled: Optional[bool] = None, + default_decision_enabled: Optional[bool] = None, + justification_required_on_approval: Optional[bool] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, + auto_apply_decisions_enabled: Optional[bool] = None, + recommendations_enabled: Optional[bool] = None, + recommendation_look_back_duration: Optional[datetime.timedelta] = None, + instance_duration_in_days: Optional[int] = None, + type_settings_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, + number_of_occurrences: Optional[int] = None, + start_date: Optional[datetime.datetime] = None, + end_date: Optional[datetime.datetime] = None, + type_settings_recurrence_pattern_type: Optional[Union[str, "_models.AccessReviewRecurrencePatternType"]] = None, + interval: Optional[int] = None, + **kwargs + ): + """ + :keyword display_name: The display name for the schedule definition. + :paramtype display_name: str + :keyword description_for_admins: The description provided by the access review creator and + visible to admins. + :paramtype description_for_admins: str + :keyword description_for_reviewers: The description provided by the access review creator to be + shown to reviewers. + :paramtype description_for_reviewers: str + :keyword reviewers: This is the collection of reviewers. + :paramtype reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :keyword backup_reviewers: This is the collection of backup reviewers. + :paramtype backup_reviewers: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewReviewer] + :keyword instances: This is the collection of instances returned when one does an expand on it. + :paramtype instances: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :keyword inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :paramtype inactive_duration: ~datetime.timedelta + :keyword expand_nested_memberships: Flag to indicate whether to expand nested memberships or + not. + :paramtype expand_nested_memberships: bool + :keyword include_inherited_access: Flag to indicate whether to expand nested memberships or + not. + :paramtype include_inherited_access: bool + :keyword include_access_below_resource: Flag to indicate whether to expand nested memberships + or not. + :paramtype include_access_below_resource: bool + :keyword exclude_resource_id: This is used to indicate the resource id(s) to exclude. + :paramtype exclude_resource_id: str + :keyword exclude_role_definition_id: This is used to indicate the role definition id(s) to + exclude. + :paramtype exclude_role_definition_id: str + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword recommendation_look_back_duration: Recommendations for access reviews are calculated + by looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :paramtype recommendation_look_back_duration: ~datetime.timedelta + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_settings_recurrence_range_type: The recurrence range type. The possible values + are: endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_settings_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_settings_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. + Known values are: "weekly" and "absoluteMonthly". + :paramtype type_settings_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) + self.display_name = display_name + self.status = None + self.description_for_admins = description_for_admins + self.description_for_reviewers = description_for_reviewers + self.reviewers = reviewers + self.backup_reviewers = backup_reviewers + self.reviewers_type = None + self.instances = instances + self.resource_id = None + self.role_definition_id = None + self.principal_type_scope_principal_type = None + self.assignment_state = None + self.inactive_duration = inactive_duration + self.expand_nested_memberships = expand_nested_memberships + self.include_inherited_access = include_inherited_access + self.include_access_below_resource = include_access_below_resource + self.exclude_resource_id = exclude_resource_id + self.exclude_role_definition_id = exclude_role_definition_id + self.mail_notifications_enabled = mail_notifications_enabled + self.reminder_notifications_enabled = reminder_notifications_enabled + self.default_decision_enabled = default_decision_enabled + self.justification_required_on_approval = justification_required_on_approval + self.default_decision = default_decision + self.auto_apply_decisions_enabled = auto_apply_decisions_enabled + self.recommendations_enabled = recommendations_enabled + self.recommendation_look_back_duration = recommendation_look_back_duration + self.instance_duration_in_days = instance_duration_in_days + self.type_settings_recurrence_range_type = type_settings_recurrence_range_type + self.number_of_occurrences = number_of_occurrences + self.start_date = start_date + self.end_date = end_date + self.type_settings_recurrence_pattern_type = type_settings_recurrence_pattern_type + self.interval = interval + self.principal_id = None + self.principal_type_created_by_principal_type = None + self.principal_name = None + self.user_principal_name = None + + +class AccessReviewScheduleSettings(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Settings of an Access Review. + + :ivar mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and the + review creator is enabled. + :vartype mail_notifications_enabled: bool + :ivar reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :vartype reminder_notifications_enabled: bool + :ivar default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :vartype default_decision_enabled: bool + :ivar justification_required_on_approval: Flag to indicate whether the reviewer is required to + pass justification when recording a decision. + :vartype justification_required_on_approval: bool + :ivar default_decision: This specifies the behavior for the autoReview feature when an access + review completes. Known values are: "Approve", "Deny", and "Recommendation". + :vartype default_decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DefaultDecisionType + :ivar auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :vartype auto_apply_decisions_enabled: bool + :ivar recommendations_enabled: Flag to indicate whether showing recommendations to reviewers is + enabled. + :vartype recommendations_enabled: bool + :ivar recommendation_look_back_duration: Recommendations for access reviews are calculated by + looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :vartype recommendation_look_back_duration: ~datetime.timedelta + :ivar instance_duration_in_days: The duration in days for an instance. + :vartype instance_duration_in_days: int + :ivar type_recurrence_range_type: The recurrence range type. The possible values are: endDate, + noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :vartype type_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :ivar number_of_occurrences: The number of times to repeat the access review. Required and must + be positive if type is numbered. + :vartype number_of_occurrences: int + :ivar start_date: The DateTime when the review is scheduled to be start. This could be a date + in the future. Required on create. + :vartype start_date: ~datetime.datetime + :ivar end_date: The DateTime when the review is scheduled to end. Required if type is endDate. + :vartype end_date: ~datetime.datetime + :ivar type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known values + are: "weekly" and "absoluteMonthly". + :vartype type_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :ivar interval: The interval for recurrence. For a quarterly review, the interval is 3 for type + : absoluteMonthly. + :vartype interval: int + """ + + _attribute_map = { + "mail_notifications_enabled": {"key": "mailNotificationsEnabled", "type": "bool"}, + "reminder_notifications_enabled": {"key": "reminderNotificationsEnabled", "type": "bool"}, + "default_decision_enabled": {"key": "defaultDecisionEnabled", "type": "bool"}, + "justification_required_on_approval": {"key": "justificationRequiredOnApproval", "type": "bool"}, + "default_decision": {"key": "defaultDecision", "type": "str"}, + "auto_apply_decisions_enabled": {"key": "autoApplyDecisionsEnabled", "type": "bool"}, + "recommendations_enabled": {"key": "recommendationsEnabled", "type": "bool"}, + "recommendation_look_back_duration": {"key": "recommendationLookBackDuration", "type": "duration"}, + "instance_duration_in_days": {"key": "instanceDurationInDays", "type": "int"}, + "type_recurrence_range_type": {"key": "recurrence.range.type", "type": "str"}, + "number_of_occurrences": {"key": "recurrence.range.numberOfOccurrences", "type": "int"}, + "start_date": {"key": "recurrence.range.startDate", "type": "iso-8601"}, + "end_date": {"key": "recurrence.range.endDate", "type": "iso-8601"}, + "type_recurrence_pattern_type": {"key": "recurrence.pattern.type", "type": "str"}, + "interval": {"key": "recurrence.pattern.interval", "type": "int"}, + } + + def __init__( + self, + *, + mail_notifications_enabled: Optional[bool] = None, + reminder_notifications_enabled: Optional[bool] = None, + default_decision_enabled: Optional[bool] = None, + justification_required_on_approval: Optional[bool] = None, + default_decision: Optional[Union[str, "_models.DefaultDecisionType"]] = None, + auto_apply_decisions_enabled: Optional[bool] = None, + recommendations_enabled: Optional[bool] = None, + recommendation_look_back_duration: Optional[datetime.timedelta] = None, + instance_duration_in_days: Optional[int] = None, + type_recurrence_range_type: Optional[Union[str, "_models.AccessReviewRecurrenceRangeType"]] = None, + number_of_occurrences: Optional[int] = None, + start_date: Optional[datetime.datetime] = None, + end_date: Optional[datetime.datetime] = None, + type_recurrence_pattern_type: Optional[Union[str, "_models.AccessReviewRecurrencePatternType"]] = None, + interval: Optional[int] = None, + **kwargs + ): + """ + :keyword mail_notifications_enabled: Flag to indicate whether sending mails to reviewers and + the review creator is enabled. + :paramtype mail_notifications_enabled: bool + :keyword reminder_notifications_enabled: Flag to indicate whether sending reminder emails to + reviewers are enabled. + :paramtype reminder_notifications_enabled: bool + :keyword default_decision_enabled: Flag to indicate whether reviewers are required to provide a + justification when reviewing access. + :paramtype default_decision_enabled: bool + :keyword justification_required_on_approval: Flag to indicate whether the reviewer is required + to pass justification when recording a decision. + :paramtype justification_required_on_approval: bool + :keyword default_decision: This specifies the behavior for the autoReview feature when an + access review completes. Known values are: "Approve", "Deny", and "Recommendation". + :paramtype default_decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.DefaultDecisionType + :keyword auto_apply_decisions_enabled: Flag to indicate whether auto-apply capability, to + automatically change the target object access resource, is enabled. If not enabled, a user + must, after the review completes, apply the access review. + :paramtype auto_apply_decisions_enabled: bool + :keyword recommendations_enabled: Flag to indicate whether showing recommendations to reviewers + is enabled. + :paramtype recommendations_enabled: bool + :keyword recommendation_look_back_duration: Recommendations for access reviews are calculated + by looking back at 30 days of data(w.r.t the start date of the review) by default. However, in + some scenarios, customers want to change how far back to look at and want to configure 60 days, + 90 days, etc. instead. This setting allows customers to configure this duration. The value + should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can + be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, + minutes, seconds)). + :paramtype recommendation_look_back_duration: ~datetime.timedelta + :keyword instance_duration_in_days: The duration in days for an instance. + :paramtype instance_duration_in_days: int + :keyword type_recurrence_range_type: The recurrence range type. The possible values are: + endDate, noEnd, numbered. Known values are: "endDate", "noEnd", and "numbered". + :paramtype type_recurrence_range_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrenceRangeType + :keyword number_of_occurrences: The number of times to repeat the access review. Required and + must be positive if type is numbered. + :paramtype number_of_occurrences: int + :keyword start_date: The DateTime when the review is scheduled to be start. This could be a + date in the future. Required on create. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The DateTime when the review is scheduled to end. Required if type is + endDate. + :paramtype end_date: ~datetime.datetime + :keyword type_recurrence_pattern_type: The recurrence type : weekly, monthly, etc. Known values + are: "weekly" and "absoluteMonthly". + :paramtype type_recurrence_pattern_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewRecurrencePatternType + :keyword interval: The interval for recurrence. For a quarterly review, the interval is 3 for + type : absoluteMonthly. + :paramtype interval: int + """ + super().__init__(**kwargs) + self.mail_notifications_enabled = mail_notifications_enabled + self.reminder_notifications_enabled = reminder_notifications_enabled + self.default_decision_enabled = default_decision_enabled + self.justification_required_on_approval = justification_required_on_approval + self.default_decision = default_decision + self.auto_apply_decisions_enabled = auto_apply_decisions_enabled + self.recommendations_enabled = recommendations_enabled + self.recommendation_look_back_duration = recommendation_look_back_duration + self.instance_duration_in_days = instance_duration_in_days + self.type_recurrence_range_type = type_recurrence_range_type + self.number_of_occurrences = number_of_occurrences + self.start_date = start_date + self.end_date = end_date + self.type_recurrence_pattern_type = type_recurrence_pattern_type + self.interval = interval + + +class AccessReviewScope(_serialization.Model): + """Descriptor for what needs to be reviewed. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar resource_id: ResourceId in which this review is getting created. + :vartype resource_id: str + :ivar role_definition_id: This is used to indicate the role being reviewed. + :vartype role_definition_id: str + :ivar principal_type: The identity type user/servicePrincipal to review. Known values are: + "user", "guestUser", "servicePrincipal", "user,group", and "redeemedGuestUser". + :vartype principal_type: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScopePrincipalType + :ivar assignment_state: The role assignment state eligible/active to review. Known values are: + "eligible" and "active". + :vartype assignment_state: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScopeAssignmentState + :ivar inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :vartype inactive_duration: ~datetime.timedelta + :ivar expand_nested_memberships: Flag to indicate whether to expand nested memberships or not. + :vartype expand_nested_memberships: bool + :ivar include_inherited_access: Flag to indicate whether to expand nested memberships or not. + :vartype include_inherited_access: bool + :ivar include_access_below_resource: Flag to indicate whether to expand nested memberships or + not. + :vartype include_access_below_resource: bool + :ivar exclude_resource_id: This is used to indicate the resource id(s) to exclude. + :vartype exclude_resource_id: str + :ivar exclude_role_definition_id: This is used to indicate the role definition id(s) to + exclude. + :vartype exclude_role_definition_id: str + """ + + _validation = { + "resource_id": {"readonly": True}, + "role_definition_id": {"readonly": True}, + "principal_type": {"readonly": True}, + "assignment_state": {"readonly": True}, + } + + _attribute_map = { + "resource_id": {"key": "resourceId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "principal_type": {"key": "principalType", "type": "str"}, + "assignment_state": {"key": "assignmentState", "type": "str"}, + "inactive_duration": {"key": "inactiveDuration", "type": "duration"}, + "expand_nested_memberships": {"key": "expandNestedMemberships", "type": "bool"}, + "include_inherited_access": {"key": "includeInheritedAccess", "type": "bool"}, + "include_access_below_resource": {"key": "includeAccessBelowResource", "type": "bool"}, + "exclude_resource_id": {"key": "excludeResourceId", "type": "str"}, + "exclude_role_definition_id": {"key": "excludeRoleDefinitionId", "type": "str"}, + } + + def __init__( + self, + *, + inactive_duration: Optional[datetime.timedelta] = None, + expand_nested_memberships: Optional[bool] = None, + include_inherited_access: Optional[bool] = None, + include_access_below_resource: Optional[bool] = None, + exclude_resource_id: Optional[str] = None, + exclude_role_definition_id: Optional[str] = None, + **kwargs + ): + """ + :keyword inactive_duration: Duration users are inactive for. The value should be in ISO 8601 + format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be used to convert + TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours, minutes, + seconds)). + :paramtype inactive_duration: ~datetime.timedelta + :keyword expand_nested_memberships: Flag to indicate whether to expand nested memberships or + not. + :paramtype expand_nested_memberships: bool + :keyword include_inherited_access: Flag to indicate whether to expand nested memberships or + not. + :paramtype include_inherited_access: bool + :keyword include_access_below_resource: Flag to indicate whether to expand nested memberships + or not. + :paramtype include_access_below_resource: bool + :keyword exclude_resource_id: This is used to indicate the resource id(s) to exclude. + :paramtype exclude_resource_id: str + :keyword exclude_role_definition_id: This is used to indicate the role definition id(s) to + exclude. + :paramtype exclude_role_definition_id: str + """ + super().__init__(**kwargs) + self.resource_id = None + self.role_definition_id = None + self.principal_type = None + self.assignment_state = None + self.inactive_duration = inactive_duration + self.expand_nested_memberships = expand_nested_memberships + self.include_inherited_access = include_inherited_access + self.include_access_below_resource = include_access_below_resource + self.exclude_resource_id = exclude_resource_id + self.exclude_role_definition_id = exclude_role_definition_id + + +class Alert(_serialization.Model): # pylint: disable=too-many-instance-attributes + """The alert. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The alert ID. + :vartype id: str + :ivar name: The alert name. + :vartype name: str + :ivar type: The alert type. + :vartype type: str + :ivar scope: The alert scope. + :vartype scope: str + :ivar is_active: False by default; true if the alert is active. + :vartype is_active: bool + :ivar incident_count: The number of generated incidents of the alert. + :vartype incident_count: int + :ivar last_modified_date_time: The date time when the alert configuration was updated or new + incidents were generated. + :vartype last_modified_date_time: ~datetime.datetime + :ivar last_scanned_date_time: The date time when the alert was last scanned. + :vartype last_scanned_date_time: ~datetime.datetime + :ivar alert_definition: The alert definition. + :vartype alert_definition: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertDefinition + :ivar alert_incidents: The alert incidents. + :vartype alert_incidents: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertIncident] + :ivar alert_configuration: The alert configuration. + :vartype alert_configuration: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "scope": {"readonly": True}, + "incident_count": {"readonly": True}, + "last_modified_date_time": {"readonly": True}, + "last_scanned_date_time": {"readonly": True}, + "alert_definition": {"readonly": True}, + "alert_incidents": {"readonly": True}, + "alert_configuration": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "is_active": {"key": "properties.isActive", "type": "bool"}, + "incident_count": {"key": "properties.incidentCount", "type": "int"}, + "last_modified_date_time": {"key": "properties.lastModifiedDateTime", "type": "iso-8601"}, + "last_scanned_date_time": {"key": "properties.lastScannedDateTime", "type": "iso-8601"}, + "alert_definition": {"key": "properties.alertDefinition", "type": "AlertDefinition"}, + "alert_incidents": {"key": "properties.alertIncidents", "type": "[AlertIncident]"}, + "alert_configuration": {"key": "properties.alertConfiguration", "type": "AlertConfiguration"}, + } + + def __init__(self, *, is_active: Optional[bool] = None, **kwargs): + """ + :keyword is_active: False by default; true if the alert is active. + :paramtype is_active: bool + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.scope = None + self.is_active = is_active + self.incident_count = None + self.last_modified_date_time = None + self.last_scanned_date_time = None + self.alert_definition = None + self.alert_incidents = None + self.alert_configuration = None + + +class AlertConfiguration(_serialization.Model): + """Alert configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The alert configuration ID. + :vartype id: str + :ivar name: The alert configuration name. + :vartype name: str + :ivar type: The alert configuration type. + :vartype type: str + :ivar alert_definition_id: The alert definition ID. + :vartype alert_definition_id: str + :ivar scope: The alert scope. + :vartype scope: str + :ivar is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :vartype is_enabled: bool + :ivar alert_configuration_type: The alert configuration type. + :vartype alert_configuration_type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "alert_definition_id": {"readonly": True}, + "scope": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "alert_definition_id": {"key": "properties.alertDefinitionId", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "is_enabled": {"key": "properties.isEnabled", "type": "bool"}, + "alert_configuration_type": {"key": "properties.alertConfigurationType", "type": "str"}, + } + + def __init__(self, *, is_enabled: Optional[bool] = None, **kwargs): + """ + :keyword is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :paramtype is_enabled: bool + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.alert_definition_id = None + self.scope = None + self.is_enabled = is_enabled + self.alert_configuration_type = None # type: Optional[str] + + +class AlertConfigurationListResult(_serialization.Model): + """Alert configuration list operation result. + + :ivar value: Alert configuration list. + :vartype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AlertConfiguration]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.AlertConfiguration"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: Alert configuration list. + :paramtype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AlertConfigurationProperties(_serialization.Model): + """Alert configuration properties. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureRolesAssignedOutsidePimAlertConfigurationProperties, + DuplicateRoleCreatedAlertConfigurationProperties, + TooManyOwnersAssignedToResourceAlertConfigurationProperties, + TooManyPermanentOwnersAssignedToResourceAlertConfigurationProperties + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar alert_definition_id: The alert definition ID. + :vartype alert_definition_id: str + :ivar scope: The alert scope. + :vartype scope: str + :ivar is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :vartype is_enabled: bool + :ivar alert_configuration_type: The alert configuration type. Required. + :vartype alert_configuration_type: str + """ + + _validation = { + "alert_definition_id": {"readonly": True}, + "scope": {"readonly": True}, + "alert_configuration_type": {"required": True}, + } + + _attribute_map = { + "alert_definition_id": {"key": "alertDefinitionId", "type": "str"}, + "scope": {"key": "scope", "type": "str"}, + "is_enabled": {"key": "isEnabled", "type": "bool"}, + "alert_configuration_type": {"key": "alertConfigurationType", "type": "str"}, + } + + _subtype_map = { + "alert_configuration_type": { + "AzureRolesAssignedOutsidePimAlertConfiguration": "AzureRolesAssignedOutsidePimAlertConfigurationProperties", + "DuplicateRoleCreatedAlertConfiguration": "DuplicateRoleCreatedAlertConfigurationProperties", + "TooManyOwnersAssignedToResourceAlertConfiguration": "TooManyOwnersAssignedToResourceAlertConfigurationProperties", + "TooManyPermanentOwnersAssignedToResourceAlertConfiguration": "TooManyPermanentOwnersAssignedToResourceAlertConfigurationProperties", + } + } + + def __init__(self, *, is_enabled: Optional[bool] = None, **kwargs): + """ + :keyword is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :paramtype is_enabled: bool + """ + super().__init__(**kwargs) + self.alert_definition_id = None + self.scope = None + self.is_enabled = is_enabled + self.alert_configuration_type = None # type: Optional[str] + + +class AlertDefinition(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Alert definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The alert definition ID. + :vartype id: str + :ivar name: The alert definition name. + :vartype name: str + :ivar type: The alert definition type. + :vartype type: str + :ivar display_name: The alert display name. + :vartype display_name: str + :ivar scope: The alert scope. + :vartype scope: str + :ivar description: The alert description. + :vartype description: str + :ivar severity_level: Severity level of the alert. Known values are: "Low", "Medium", and + "High". + :vartype severity_level: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.SeverityLevel + :ivar security_impact: Security impact of the alert. + :vartype security_impact: str + :ivar mitigation_steps: The methods to mitigate the alert. + :vartype mitigation_steps: str + :ivar how_to_prevent: The ways to prevent the alert. + :vartype how_to_prevent: str + :ivar is_remediatable: True if the alert can be remediated; false, otherwise. + :vartype is_remediatable: bool + :ivar is_configurable: True if the alert configuration can be configured; false, otherwise. + :vartype is_configurable: bool + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "display_name": {"readonly": True}, + "scope": {"readonly": True}, + "description": {"readonly": True}, + "severity_level": {"readonly": True}, + "security_impact": {"readonly": True}, + "mitigation_steps": {"readonly": True}, + "how_to_prevent": {"readonly": True}, + "is_remediatable": {"readonly": True}, + "is_configurable": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "severity_level": {"key": "properties.severityLevel", "type": "str"}, + "security_impact": {"key": "properties.securityImpact", "type": "str"}, + "mitigation_steps": {"key": "properties.mitigationSteps", "type": "str"}, + "how_to_prevent": {"key": "properties.howToPrevent", "type": "str"}, + "is_remediatable": {"key": "properties.isRemediatable", "type": "bool"}, + "is_configurable": {"key": "properties.isConfigurable", "type": "bool"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.display_name = None + self.scope = None + self.description = None + self.severity_level = None + self.security_impact = None + self.mitigation_steps = None + self.how_to_prevent = None + self.is_remediatable = None + self.is_configurable = None + + +class AlertDefinitionListResult(_serialization.Model): + """Alert definition list operation result. + + :ivar value: Alert definition list. + :vartype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AlertDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.AlertDefinition"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: Alert definition list. + :paramtype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AlertIncident(_serialization.Model): + """Alert incident. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The alert incident ID. + :vartype id: str + :ivar name: The alert incident name. + :vartype name: str + :ivar type: The alert incident type. + :vartype type: str + :ivar alert_incident_type: The alert incident type. + :vartype alert_incident_type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "alert_incident_type": {"key": "properties.alertIncidentType", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.alert_incident_type = None # type: Optional[str] + + +class AlertIncidentListResult(_serialization.Model): + """Alert incident list operation result. + + :ivar value: Alert incident list. + :vartype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertIncident] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AlertIncident]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.AlertIncident"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: Alert incident list. + :paramtype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertIncident] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AlertIncidentProperties(_serialization.Model): + """Alert incident properties. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureRolesAssignedOutsidePimAlertIncidentProperties, + DuplicateRoleCreatedAlertIncidentProperties, + TooManyOwnersAssignedToResourceAlertIncidentProperties, + TooManyPermanentOwnersAssignedToResourceAlertIncidentProperties + + All required parameters must be populated in order to send to Azure. + + :ivar alert_incident_type: The alert incident type. Required. + :vartype alert_incident_type: str + """ + + _validation = { + "alert_incident_type": {"required": True}, + } + + _attribute_map = { + "alert_incident_type": {"key": "alertIncidentType", "type": "str"}, + } + + _subtype_map = { + "alert_incident_type": { + "AzureRolesAssignedOutsidePimAlertIncident": "AzureRolesAssignedOutsidePimAlertIncidentProperties", + "DuplicateRoleCreatedAlertIncident": "DuplicateRoleCreatedAlertIncidentProperties", + "TooManyOwnersAssignedToResourceAlertIncident": "TooManyOwnersAssignedToResourceAlertIncidentProperties", + "TooManyPermanentOwnersAssignedToResourceAlertIncident": "TooManyPermanentOwnersAssignedToResourceAlertIncidentProperties", + } + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.alert_incident_type = None # type: Optional[str] + + +class AlertListResult(_serialization.Model): + """Alert list operation result. + + :ivar value: Alert list. + :vartype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.Alert] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Alert]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[List["_models.Alert"]] = None, next_link: Optional[str] = None, **kwargs): + """ + :keyword value: Alert list. + :paramtype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.Alert] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AlertOperationListResult(_serialization.Model): + """Alert operation list operation result. + + :ivar value: Alert operation list. + :vartype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertOperationResult] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AlertOperationResult]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.AlertOperationResult"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: Alert operation list. + :paramtype value: + list[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertOperationResult] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AlertOperationResult(_serialization.Model): + """Alert operation result. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The id of the alert operation. + :vartype id: str + :ivar status: The status of the alert operation. + :vartype status: str + """ + + _validation = { + "id": {"readonly": True}, + "status": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "status": {"key": "status", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None + self.status = None + + +class AzureRolesAssignedOutsidePimAlertConfigurationProperties(AlertConfigurationProperties): + """The Azure roles assigned outside PIM alert configuration properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar alert_definition_id: The alert definition ID. + :vartype alert_definition_id: str + :ivar scope: The alert scope. + :vartype scope: str + :ivar is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :vartype is_enabled: bool + :ivar alert_configuration_type: The alert configuration type. Required. + :vartype alert_configuration_type: str + """ + + _validation = { + "alert_definition_id": {"readonly": True}, + "scope": {"readonly": True}, + "alert_configuration_type": {"required": True}, + } + + _attribute_map = { + "alert_definition_id": {"key": "alertDefinitionId", "type": "str"}, + "scope": {"key": "scope", "type": "str"}, + "is_enabled": {"key": "isEnabled", "type": "bool"}, + "alert_configuration_type": {"key": "alertConfigurationType", "type": "str"}, + } + + def __init__(self, *, is_enabled: Optional[bool] = None, **kwargs): + """ + :keyword is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :paramtype is_enabled: bool + """ + super().__init__(is_enabled=is_enabled, **kwargs) + self.alert_configuration_type = "AzureRolesAssignedOutsidePimAlertConfiguration" # type: str + + +class AzureRolesAssignedOutsidePimAlertIncidentProperties( + AlertIncidentProperties +): # pylint: disable=too-many-instance-attributes + """Azure roles assigned outside PIM alert incident properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar alert_incident_type: The alert incident type. Required. + :vartype alert_incident_type: str + :ivar assignee_display_name: The assignee display name. + :vartype assignee_display_name: str + :ivar assignee_user_principal_name: The assignee user principal name. + :vartype assignee_user_principal_name: str + :ivar assignee_id: The assignee ID. + :vartype assignee_id: str + :ivar role_display_name: The role display name. + :vartype role_display_name: str + :ivar role_template_id: The role template ID. + :vartype role_template_id: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar assignment_activated_date: The date the assignment was activated. + :vartype assignment_activated_date: ~datetime.datetime + :ivar requestor_id: The requestor ID. + :vartype requestor_id: str + :ivar requestor_display_name: The requestor display name. + :vartype requestor_display_name: str + :ivar requestor_user_principal_name: The requestor user principal name. + :vartype requestor_user_principal_name: str + """ + + _validation = { + "alert_incident_type": {"required": True}, + "assignee_display_name": {"readonly": True}, + "assignee_user_principal_name": {"readonly": True}, + "assignee_id": {"readonly": True}, + "role_display_name": {"readonly": True}, + "role_template_id": {"readonly": True}, + "role_definition_id": {"readonly": True}, + "assignment_activated_date": {"readonly": True}, + "requestor_id": {"readonly": True}, + "requestor_display_name": {"readonly": True}, + "requestor_user_principal_name": {"readonly": True}, + } + + _attribute_map = { + "alert_incident_type": {"key": "alertIncidentType", "type": "str"}, + "assignee_display_name": {"key": "assigneeDisplayName", "type": "str"}, + "assignee_user_principal_name": {"key": "assigneeUserPrincipalName", "type": "str"}, + "assignee_id": {"key": "assigneeId", "type": "str"}, + "role_display_name": {"key": "roleDisplayName", "type": "str"}, + "role_template_id": {"key": "roleTemplateId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + "assignment_activated_date": {"key": "assignmentActivatedDate", "type": "iso-8601"}, + "requestor_id": {"key": "requestorId", "type": "str"}, + "requestor_display_name": {"key": "requestorDisplayName", "type": "str"}, + "requestor_user_principal_name": {"key": "requestorUserPrincipalName", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.alert_incident_type = "AzureRolesAssignedOutsidePimAlertIncident" # type: str + self.assignee_display_name = None + self.assignee_user_principal_name = None + self.assignee_id = None + self.role_display_name = None + self.role_template_id = None + self.role_definition_id = None + self.assignment_activated_date = None + self.requestor_id = None + self.requestor_display_name = None + self.requestor_user_principal_name = None + + +class CloudErrorBody(_serialization.Model): + """An error response from the service. + + :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. + :vartype code: str + :ivar message: A message describing the error, intended to be suitable for display in a user + interface. + :vartype message: str + """ + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs): + """ + :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. + :paramtype code: str + :keyword message: A message describing the error, intended to be suitable for display in a user + interface. + :paramtype message: str + """ + super().__init__(**kwargs) + self.code = code + self.message = message + + +class DuplicateRoleCreatedAlertConfigurationProperties(AlertConfigurationProperties): + """The duplicate role created alert configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar alert_definition_id: The alert definition ID. + :vartype alert_definition_id: str + :ivar scope: The alert scope. + :vartype scope: str + :ivar is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :vartype is_enabled: bool + :ivar alert_configuration_type: The alert configuration type. Required. + :vartype alert_configuration_type: str + """ + + _validation = { + "alert_definition_id": {"readonly": True}, + "scope": {"readonly": True}, + "alert_configuration_type": {"required": True}, + } + + _attribute_map = { + "alert_definition_id": {"key": "alertDefinitionId", "type": "str"}, + "scope": {"key": "scope", "type": "str"}, + "is_enabled": {"key": "isEnabled", "type": "bool"}, + "alert_configuration_type": {"key": "alertConfigurationType", "type": "str"}, + } + + def __init__(self, *, is_enabled: Optional[bool] = None, **kwargs): + """ + :keyword is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :paramtype is_enabled: bool + """ + super().__init__(is_enabled=is_enabled, **kwargs) + self.alert_configuration_type = "DuplicateRoleCreatedAlertConfiguration" # type: str + + +class DuplicateRoleCreatedAlertIncidentProperties(AlertIncidentProperties): + """Duplicate role created alert incident properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar alert_incident_type: The alert incident type. Required. + :vartype alert_incident_type: str + :ivar role_name: The role name. + :vartype role_name: str + :ivar duplicate_roles: The duplicate roles. + :vartype duplicate_roles: str + :ivar reason: The reason for the incident. + :vartype reason: str + """ + + _validation = { + "alert_incident_type": {"required": True}, + "role_name": {"readonly": True}, + "duplicate_roles": {"readonly": True}, + "reason": {"readonly": True}, + } + + _attribute_map = { + "alert_incident_type": {"key": "alertIncidentType", "type": "str"}, + "role_name": {"key": "roleName", "type": "str"}, + "duplicate_roles": {"key": "duplicateRoles", "type": "str"}, + "reason": {"key": "reason", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.alert_incident_type = "DuplicateRoleCreatedAlertIncident" # type: str + self.role_name = None + self.duplicate_roles = None + self.reason = None + + +class ErrorDefinition(_serialization.Model): + """Error description and code explaining why an operation failed. + + :ivar error: Error of the list gateway status. + :vartype error: ~azure.mgmt.authorization.v2021_12_01_preview.models.ErrorDefinitionProperties + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDefinitionProperties"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDefinitionProperties"] = None, **kwargs): + """ + :keyword error: Error of the list gateway status. + :paramtype error: + ~azure.mgmt.authorization.v2021_12_01_preview.models.ErrorDefinitionProperties + """ + super().__init__(**kwargs) + self.error = error + + +class ErrorDefinitionProperties(_serialization.Model): + """Error description and code explaining why an operation failed. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar message: Description of the error. + :vartype message: str + :ivar code: Error code of list gateway. + :vartype code: str + """ + + _validation = { + "message": {"readonly": True}, + } + + _attribute_map = { + "message": {"key": "message", "type": "str"}, + "code": {"key": "code", "type": "str"}, + } + + def __init__(self, *, code: Optional[str] = None, **kwargs): + """ + :keyword code: Error code of list gateway. + :paramtype code: str + """ + super().__init__(**kwargs) + self.message = None + self.code = code + + +class Operation(_serialization.Model): + """The definition of a Microsoft.Authorization operation. + + :ivar name: Name of the operation. + :vartype name: str + :ivar is_data_action: Indicates whether the operation is a data action. + :vartype is_data_action: bool + :ivar display: Display of the operation. + :vartype display: ~azure.mgmt.authorization.v2021_12_01_preview.models.OperationDisplay + :ivar origin: Origin of the operation. + :vartype origin: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + is_data_action: Optional[bool] = None, + display: Optional["_models.OperationDisplay"] = None, + origin: Optional[str] = None, + **kwargs + ): + """ + :keyword name: Name of the operation. + :paramtype name: str + :keyword is_data_action: Indicates whether the operation is a data action. + :paramtype is_data_action: bool + :keyword display: Display of the operation. + :paramtype display: ~azure.mgmt.authorization.v2021_12_01_preview.models.OperationDisplay + :keyword origin: Origin of the operation. + :paramtype origin: str + """ + super().__init__(**kwargs) + self.name = name + self.is_data_action = is_data_action + self.display = display + self.origin = origin + + +class OperationDisplay(_serialization.Model): + """The display information for a Microsoft.Authorization operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: The resource provider name: Microsoft.Authorization. + :vartype provider: str + :ivar resource: The resource on which the operation is performed. + :vartype resource: str + :ivar operation: The operation that users can perform. + :vartype operation: str + :ivar description: The description for the operation. + :vartype description: str + """ + + _validation = { + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, + } + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(_serialization.Model): + """The result of a request to list Microsoft.Authorization operations. + + :ivar value: The collection value. + :vartype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.Operation] + :ivar next_link: The URI that can be used to request the next set of paged results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs): + """ + :keyword value: The collection value. + :paramtype value: list[~azure.mgmt.authorization.v2021_12_01_preview.models.Operation] + :keyword next_link: The URI that can be used to request the next set of paged results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RecordAllDecisionsProperties(_serialization.Model): + """Record All Decisions payload. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The id of principal which needs to be approved/denied. + :vartype principal_id: str + :ivar resource_id: The id of resource which needs to be approved/denied. + :vartype resource_id: str + :ivar decision: The decision to make. Approvers can take action of Approve/Deny. Known values + are: "Approve" and "Deny". + :vartype decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.RecordAllDecisionsResult + :ivar justification: Justification provided by approvers for their action. + :vartype justification: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "resource_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "resource_id": {"key": "resourceId", "type": "str"}, + "decision": {"key": "decision", "type": "str"}, + "justification": {"key": "justification", "type": "str"}, + } + + def __init__( + self, + *, + decision: Optional[Union[str, "_models.RecordAllDecisionsResult"]] = None, + justification: Optional[str] = None, + **kwargs + ): + """ + :keyword decision: The decision to make. Approvers can take action of Approve/Deny. Known + values are: "Approve" and "Deny". + :paramtype decision: str or + ~azure.mgmt.authorization.v2021_12_01_preview.models.RecordAllDecisionsResult + :keyword justification: Justification provided by approvers for their action. + :paramtype justification: str + """ + super().__init__(**kwargs) + self.principal_id = None + self.resource_id = None + self.decision = decision + self.justification = justification + + +class TooManyOwnersAssignedToResourceAlertConfigurationProperties(AlertConfigurationProperties): + """Too many owners assigned to resource alert configuration properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar alert_definition_id: The alert definition ID. + :vartype alert_definition_id: str + :ivar scope: The alert scope. + :vartype scope: str + :ivar is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :vartype is_enabled: bool + :ivar alert_configuration_type: The alert configuration type. Required. + :vartype alert_configuration_type: str + :ivar threshold_number_of_owners: The threshold number of owners. + :vartype threshold_number_of_owners: int + :ivar threshold_percentage_of_owners_out_of_all_role_members: The threshold percentage of + owners out of all role members. + :vartype threshold_percentage_of_owners_out_of_all_role_members: int + """ + + _validation = { + "alert_definition_id": {"readonly": True}, + "scope": {"readonly": True}, + "alert_configuration_type": {"required": True}, + } + + _attribute_map = { + "alert_definition_id": {"key": "alertDefinitionId", "type": "str"}, + "scope": {"key": "scope", "type": "str"}, + "is_enabled": {"key": "isEnabled", "type": "bool"}, + "alert_configuration_type": {"key": "alertConfigurationType", "type": "str"}, + "threshold_number_of_owners": {"key": "thresholdNumberOfOwners", "type": "int"}, + "threshold_percentage_of_owners_out_of_all_role_members": { + "key": "thresholdPercentageOfOwnersOutOfAllRoleMembers", + "type": "int", + }, + } + + def __init__( + self, + *, + is_enabled: Optional[bool] = None, + threshold_number_of_owners: Optional[int] = None, + threshold_percentage_of_owners_out_of_all_role_members: Optional[int] = None, + **kwargs + ): + """ + :keyword is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :paramtype is_enabled: bool + :keyword threshold_number_of_owners: The threshold number of owners. + :paramtype threshold_number_of_owners: int + :keyword threshold_percentage_of_owners_out_of_all_role_members: The threshold percentage of + owners out of all role members. + :paramtype threshold_percentage_of_owners_out_of_all_role_members: int + """ + super().__init__(is_enabled=is_enabled, **kwargs) + self.alert_configuration_type = "TooManyOwnersAssignedToResourceAlertConfiguration" # type: str + self.threshold_number_of_owners = threshold_number_of_owners + self.threshold_percentage_of_owners_out_of_all_role_members = ( + threshold_percentage_of_owners_out_of_all_role_members + ) + + +class TooManyOwnersAssignedToResourceAlertIncidentProperties(AlertIncidentProperties): + """Too many owners assigned to resource alert incident properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar alert_incident_type: The alert incident type. Required. + :vartype alert_incident_type: str + :ivar assignee_name: The assignee name. + :vartype assignee_name: str + :ivar assignee_type: The assignee type. + :vartype assignee_type: str + """ + + _validation = { + "alert_incident_type": {"required": True}, + "assignee_name": {"readonly": True}, + "assignee_type": {"readonly": True}, + } + + _attribute_map = { + "alert_incident_type": {"key": "alertIncidentType", "type": "str"}, + "assignee_name": {"key": "assigneeName", "type": "str"}, + "assignee_type": {"key": "assigneeType", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.alert_incident_type = "TooManyOwnersAssignedToResourceAlertIncident" # type: str + self.assignee_name = None + self.assignee_type = None + + +class TooManyPermanentOwnersAssignedToResourceAlertConfigurationProperties(AlertConfigurationProperties): + """Too many permanent owners assigned to resource alert configuration properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar alert_definition_id: The alert definition ID. + :vartype alert_definition_id: str + :ivar scope: The alert scope. + :vartype scope: str + :ivar is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :vartype is_enabled: bool + :ivar alert_configuration_type: The alert configuration type. Required. + :vartype alert_configuration_type: str + :ivar threshold_number_of_permanent_owners: The threshold number of permanent owners. + :vartype threshold_number_of_permanent_owners: int + :ivar threshold_percentage_of_permanent_owners_out_of_all_owners: The threshold percentage of + permanent owners out of all owners. + :vartype threshold_percentage_of_permanent_owners_out_of_all_owners: int + """ + + _validation = { + "alert_definition_id": {"readonly": True}, + "scope": {"readonly": True}, + "alert_configuration_type": {"required": True}, + } + + _attribute_map = { + "alert_definition_id": {"key": "alertDefinitionId", "type": "str"}, + "scope": {"key": "scope", "type": "str"}, + "is_enabled": {"key": "isEnabled", "type": "bool"}, + "alert_configuration_type": {"key": "alertConfigurationType", "type": "str"}, + "threshold_number_of_permanent_owners": {"key": "thresholdNumberOfPermanentOwners", "type": "int"}, + "threshold_percentage_of_permanent_owners_out_of_all_owners": { + "key": "thresholdPercentageOfPermanentOwnersOutOfAllOwners", + "type": "int", + }, + } + + def __init__( + self, + *, + is_enabled: Optional[bool] = None, + threshold_number_of_permanent_owners: Optional[int] = None, + threshold_percentage_of_permanent_owners_out_of_all_owners: Optional[int] = None, + **kwargs + ): + """ + :keyword is_enabled: True if the alert is enabled, false will disable the scanning for the + specific alert. + :paramtype is_enabled: bool + :keyword threshold_number_of_permanent_owners: The threshold number of permanent owners. + :paramtype threshold_number_of_permanent_owners: int + :keyword threshold_percentage_of_permanent_owners_out_of_all_owners: The threshold percentage + of permanent owners out of all owners. + :paramtype threshold_percentage_of_permanent_owners_out_of_all_owners: int + """ + super().__init__(is_enabled=is_enabled, **kwargs) + self.alert_configuration_type = "TooManyPermanentOwnersAssignedToResourceAlertConfiguration" # type: str + self.threshold_number_of_permanent_owners = threshold_number_of_permanent_owners + self.threshold_percentage_of_permanent_owners_out_of_all_owners = ( + threshold_percentage_of_permanent_owners_out_of_all_owners + ) + + +class TooManyPermanentOwnersAssignedToResourceAlertIncidentProperties(AlertIncidentProperties): + """Too many permanent owners assigned to resource alert incident properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar alert_incident_type: The alert incident type. Required. + :vartype alert_incident_type: str + :ivar assignee_name: The assignee name. + :vartype assignee_name: str + :ivar assignee_type: The assignee type. + :vartype assignee_type: str + """ + + _validation = { + "alert_incident_type": {"required": True}, + "assignee_name": {"readonly": True}, + "assignee_type": {"readonly": True}, + } + + _attribute_map = { + "alert_incident_type": {"key": "alertIncidentType", "type": "str"}, + "assignee_name": {"key": "assigneeName", "type": "str"}, + "assignee_type": {"key": "assigneeType", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.alert_incident_type = "TooManyPermanentOwnersAssignedToResourceAlertIncident" # type: str + self.assignee_name = None + self.assignee_type = None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/__init__.py new file mode 100644 index 00000000000..96a5dd0f695 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/__init__.py @@ -0,0 +1,89 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import Operations +from ._access_review_history_definitions_operations import AccessReviewHistoryDefinitionsOperations +from ._access_review_history_definition_operations import AccessReviewHistoryDefinitionOperations +from ._access_review_history_definition_instance_operations import AccessReviewHistoryDefinitionInstanceOperations +from ._access_review_history_definition_instances_operations import AccessReviewHistoryDefinitionInstancesOperations +from ._access_review_schedule_definitions_operations import AccessReviewScheduleDefinitionsOperations +from ._access_review_instances_operations import AccessReviewInstancesOperations +from ._access_review_instance_operations import AccessReviewInstanceOperations +from ._access_review_instance_decisions_operations import AccessReviewInstanceDecisionsOperations +from ._access_review_instance_contacted_reviewers_operations import AccessReviewInstanceContactedReviewersOperations +from ._access_review_default_settings_operations import AccessReviewDefaultSettingsOperations +from ._scope_access_review_history_definitions_operations import ScopeAccessReviewHistoryDefinitionsOperations +from ._scope_access_review_history_definition_operations import ScopeAccessReviewHistoryDefinitionOperations +from ._scope_access_review_history_definition_instance_operations import ( + ScopeAccessReviewHistoryDefinitionInstanceOperations, +) +from ._scope_access_review_history_definition_instances_operations import ( + ScopeAccessReviewHistoryDefinitionInstancesOperations, +) +from ._scope_access_review_schedule_definitions_operations import ScopeAccessReviewScheduleDefinitionsOperations +from ._scope_access_review_instances_operations import ScopeAccessReviewInstancesOperations +from ._scope_access_review_instance_operations import ScopeAccessReviewInstanceOperations +from ._scope_access_review_instance_decisions_operations import ScopeAccessReviewInstanceDecisionsOperations +from ._scope_access_review_instance_contacted_reviewers_operations import ( + ScopeAccessReviewInstanceContactedReviewersOperations, +) +from ._scope_access_review_default_settings_operations import ScopeAccessReviewDefaultSettingsOperations +from ._access_review_schedule_definitions_assigned_for_my_approval_operations import ( + AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations, +) +from ._access_review_instances_assigned_for_my_approval_operations import ( + AccessReviewInstancesAssignedForMyApprovalOperations, +) +from ._access_review_instance_my_decisions_operations import AccessReviewInstanceMyDecisionsOperations +from ._tenant_level_access_review_instance_contacted_reviewers_operations import ( + TenantLevelAccessReviewInstanceContactedReviewersOperations, +) +from ._alerts_operations import AlertsOperations +from ._alert_configurations_operations import AlertConfigurationsOperations +from ._alert_definitions_operations import AlertDefinitionsOperations +from ._alert_incidents_operations import AlertIncidentsOperations +from ._alert_operation_operations import AlertOperationOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "AccessReviewHistoryDefinitionsOperations", + "AccessReviewHistoryDefinitionOperations", + "AccessReviewHistoryDefinitionInstanceOperations", + "AccessReviewHistoryDefinitionInstancesOperations", + "AccessReviewScheduleDefinitionsOperations", + "AccessReviewInstancesOperations", + "AccessReviewInstanceOperations", + "AccessReviewInstanceDecisionsOperations", + "AccessReviewInstanceContactedReviewersOperations", + "AccessReviewDefaultSettingsOperations", + "ScopeAccessReviewHistoryDefinitionsOperations", + "ScopeAccessReviewHistoryDefinitionOperations", + "ScopeAccessReviewHistoryDefinitionInstanceOperations", + "ScopeAccessReviewHistoryDefinitionInstancesOperations", + "ScopeAccessReviewScheduleDefinitionsOperations", + "ScopeAccessReviewInstancesOperations", + "ScopeAccessReviewInstanceOperations", + "ScopeAccessReviewInstanceDecisionsOperations", + "ScopeAccessReviewInstanceContactedReviewersOperations", + "ScopeAccessReviewDefaultSettingsOperations", + "AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations", + "AccessReviewInstancesAssignedForMyApprovalOperations", + "AccessReviewInstanceMyDecisionsOperations", + "TenantLevelAccessReviewInstanceContactedReviewersOperations", + "AlertsOperations", + "AlertConfigurationsOperations", + "AlertDefinitionsOperations", + "AlertIncidentsOperations", + "AlertOperationOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_default_settings_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_default_settings_operations.py new file mode 100644 index 00000000000..357b52a5f8b --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_default_settings_operations.py @@ -0,0 +1,273 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_put_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewDefaultSettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_default_settings` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, **kwargs: Any) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + request = build_get_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore + + @overload + def put( + self, properties: _models.AccessReviewScheduleSettings, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleSettings + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put( + self, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put( + self, properties: Union[_models.AccessReviewScheduleSettings, IO], **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param properties: Access review schedule settings. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleSettings or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleSettings") + + request = build_put_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + put.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_instance_operations.py new file mode 100644 index 00000000000..9bb57b7d526 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_instance_operations.py @@ -0,0 +1,148 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_generate_download_uri_request( + history_definition_id: str, instance_id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances/{instanceId}/generateDownloadUri", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "historyDefinitionId": _SERIALIZER.url("history_definition_id", history_definition_id, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewHistoryDefinitionInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_history_definition_instance` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def generate_download_uri( + self, history_definition_id: str, instance_id: str, **kwargs: Any + ) -> _models.AccessReviewHistoryInstance: + """Generates a uri which can be used to retrieve review history data. This URI has a TTL of 1 day + and can be retrieved by fetching the accessReviewHistoryDefinition object. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param instance_id: The id of the access review history definition instance to generate a URI + for. Required. + :type instance_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryInstance] + + request = build_generate_download_uri_request( + history_definition_id=history_definition_id, + instance_id=instance_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.generate_download_uri.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + generate_download_uri.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances/{instanceId}/generateDownloadUri"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_instances_operations.py new file mode 100644 index 00000000000..53b6f65a1e9 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_instances_operations.py @@ -0,0 +1,157 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(history_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "historyDefinitionId": _SERIALIZER.url("history_definition_id", history_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewHistoryDefinitionInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_history_definition_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, history_definition_id: str, **kwargs: Any) -> Iterable["_models.AccessReviewHistoryInstance"]: + """Get access review history definition instances by definition Id. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewHistoryInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinitionInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + history_definition_id=history_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewHistoryDefinitionInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_operations.py new file mode 100644 index 00000000000..f31c78f32b1 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definition_operations.py @@ -0,0 +1,292 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_request(history_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "historyDefinitionId": _SERIALIZER.url("history_definition_id", history_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request(history_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "historyDefinitionId": _SERIALIZER.url("history_definition_id", history_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewHistoryDefinitionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_history_definition` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create( + self, + history_definition_id: str, + properties: _models.AccessReviewHistoryDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, history_definition_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + history_definition_id: str, + properties: Union[_models.AccessReviewHistoryDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinitionProperties or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewHistoryDefinitionProperties") + + request = build_create_request( + history_definition_id=history_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore + + @distributed_trace + def delete_by_id( # pylint: disable=inconsistent-return-statements + self, history_definition_id: str, **kwargs: Any + ) -> None: + """Delete an access review history definition. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_id_request( + history_definition_id=history_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definitions_operations.py new file mode 100644 index 00000000000..60aba776bdf --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_history_definitions_operations.py @@ -0,0 +1,244 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(history_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "historyDefinitionId": _SERIALIZER.url("history_definition_id", history_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewHistoryDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_history_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.AccessReviewHistoryDefinition"]: + """Lists the accessReviewHistoryDefinitions available from this provider, definition instances are + only available for 30 days after creation. + + :param filter: The filter to apply on the operation. Only standard filters on definition name + and created date are supported. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewHistoryDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewHistoryDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions"} # type: ignore + + @distributed_trace + def get_by_id(self, history_definition_id: str, **kwargs: Any) -> _models.AccessReviewHistoryDefinition: + """Get access review history definition by definition Id. + + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinition] + + request = build_get_by_id_request( + history_definition_id=history_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_contacted_reviewers_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_contacted_reviewers_operations.py new file mode 100644 index 00000000000..026cc2eb83e --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_contacted_reviewers_operations.py @@ -0,0 +1,163 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceContactedReviewersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance_contacted_reviewers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> Iterable["_models.AccessReviewContactedReviewer"]: + """Get access review instance contacted reviewers. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewContactedReviewer or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewContactedReviewer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewContactedReviewerListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewContactedReviewerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_decisions_operations.py new file mode 100644 index 00000000000..fbfe008e68b --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_decisions_operations.py @@ -0,0 +1,173 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + schedule_definition_id: str, id: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance_decisions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewDecision"]: + """Get access review instance decisions. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_my_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_my_decisions_operations.py new file mode 100644 index 00000000000..5c44aa06262 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_my_decisions_operations.py @@ -0,0 +1,443 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + schedule_definition_id: str, id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "decisionId": _SERIALIZER.url("decision_id", decision_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_patch_request(schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + "decisionId": _SERIALIZER.url("decision_id", decision_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceMyDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance_my_decisions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewDecision"]: + """Get my access review instance decisions. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore + + @distributed_trace + def get_by_id( + self, schedule_definition_id: str, id: str, decision_id: str, **kwargs: Any + ) -> _models.AccessReviewDecision: + """Get my single access review instance decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore + + @overload + def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: _models.AccessReviewDecisionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def patch( + self, + schedule_definition_id: str, + id: str, + decision_id: str, + properties: Union[_models.AccessReviewDecisionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewDecision: + """Record a decision. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param decision_id: The id of the decision record. Required. + :type decision_id: str + :param properties: Access review decision properties to patch. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecisionProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDecision or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecision] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewDecisionProperties") + + request = build_patch_request( + schedule_definition_id=schedule_definition_id, + id=id, + decision_id=decision_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.patch.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDecision", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + patch.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions/{decisionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_operations.py new file mode 100644 index 00000000000..9dae5630af1 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instance_operations.py @@ -0,0 +1,488 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_stop_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reset_decisions_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_apply_decisions_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_send_reminders_request( + schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_accept_recommendations_request(schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instance` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to stop an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop"} # type: ignore + + @distributed_trace + def reset_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to reset all decisions for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reset_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.reset_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + reset_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions"} # type: ignore + + @distributed_trace + def apply_decisions( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to apply all decisions for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_apply_decisions_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.apply_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + apply_decisions.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions"} # type: ignore + + @distributed_trace + def send_reminders( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to send reminders for an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_send_reminders_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.send_reminders.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + send_reminders.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders"} # type: ignore + + @distributed_trace + def accept_recommendations( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to accept recommendations for decision in an access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_accept_recommendations_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.accept_recommendations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + accept_recommendations.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/acceptRecommendations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py new file mode 100644 index 00000000000..ecebf5871bd --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instances_assigned_for_my_approval_operations.py @@ -0,0 +1,251 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(schedule_definition_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstancesAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instances_assigned_for_my_approval` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewInstance"]: + """Get access review instances assigned for my approval. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: + """Get single access review instance assigned for my approval. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instances_operations.py new file mode 100644 index 00000000000..79461040509 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_instances_operations.py @@ -0,0 +1,428 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + schedule_definition_id: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(schedule_definition_id: str, id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewInstance"]: + """Get access review instances. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, id: str, **kwargs: Any) -> _models.AccessReviewInstance: + """Get access review instances. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore + + @overload + def create( + self, + schedule_definition_id: str, + id: str, + properties: _models.AccessReviewInstanceProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + schedule_definition_id: str, + id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + schedule_definition_id: str, + id: str, + properties: Union[_models.AccessReviewInstanceProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewInstanceProperties") + + request = build_create_request( + schedule_definition_id=schedule_definition_id, + id=id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py new file mode 100644 index 00000000000..4b70ae4ce6e --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_schedule_definitions_assigned_for_my_approval_operations.py @@ -0,0 +1,152 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(*, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewScheduleDefinitionsAssignedForMyApprovalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions_assigned_for_my_approval` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.AccessReviewScheduleDefinition"]: + """Get access review instances assigned for my approval. + + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_schedule_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_schedule_definitions_operations.py new file mode 100644 index 00000000000..08acdeedb53 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_access_review_schedule_definitions_operations.py @@ -0,0 +1,567 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_by_id_request( + schedule_definition_id: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_stop_request(schedule_definition_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AccessReviewScheduleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`access_review_schedule_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.AccessReviewScheduleDefinition"]: + """Get access review schedule definitions. + + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore + + @distributed_trace + def get_by_id(self, schedule_definition_id: str, **kwargs: Any) -> _models.AccessReviewScheduleDefinition: + """Get single access review definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + request = build_get_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace + def delete_by_id( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Delete access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @overload + def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: _models.AccessReviewScheduleDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_by_id( + self, schedule_definition_id: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_by_id( + self, + schedule_definition_id: str, + properties: Union[_models.AccessReviewScheduleDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionProperties + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleDefinitionProperties") + + request = build_create_or_update_by_id_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update_by_id.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace + def stop( # pylint: disable=inconsistent-return-statements + self, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Stop access review definition. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + schedule_definition_id=schedule_definition_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_configurations_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_configurations_operations.py new file mode 100644 index 00000000000..b08eef5d17d --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_configurations_operations.py @@ -0,0 +1,397 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertConfigurations/{alertId}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertConfigurations/{alertId}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertConfigurations" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AlertConfigurationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`alert_configurations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.AlertConfiguration: + """Get the specified alert configuration. + + :param scope: The scope of the alert configuration. The scope can be any REST resource + instance. For example, use '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' + for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param alert_id: The name of the alert configuration to get. Required. + :type alert_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertConfiguration] + + request = build_get_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertConfiguration", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertConfigurations/{alertId}"} # type: ignore + + @overload + def update( + self, + scope: str, + alert_id: str, + parameters: _models.AlertConfiguration, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AlertConfiguration: + """Update an alert configuration. + + :param scope: The scope of the alert configuration. Required. + :type scope: str + :param alert_id: The name of the alert configuration to update. Required. + :type alert_id: str + :param parameters: Parameters for the alert configuration. Required. + :type parameters: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, scope: str, alert_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AlertConfiguration: + """Update an alert configuration. + + :param scope: The scope of the alert configuration. Required. + :type scope: str + :param alert_id: The name of the alert configuration to update. Required. + :type alert_id: str + :param parameters: Parameters for the alert configuration. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, scope: str, alert_id: str, parameters: Union[_models.AlertConfiguration, IO], **kwargs: Any + ) -> _models.AlertConfiguration: + """Update an alert configuration. + + :param scope: The scope of the alert configuration. Required. + :type scope: str + :param alert_id: The name of the alert configuration to update. Required. + :type alert_id: str + :param parameters: Parameters for the alert configuration. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertConfiguration] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "AlertConfiguration") + + request = build_update_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertConfiguration", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertConfigurations/{alertId}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.AlertConfiguration"]: + """Gets alert configurations for a resource scope. + + :param scope: The scope of the alert configuration. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AlertConfiguration or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertConfiguration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertConfigurationListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AlertConfigurationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertConfigurations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_definitions_operations.py new file mode 100644 index 00000000000..4c755bc0611 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_definitions_operations.py @@ -0,0 +1,243 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, alert_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertDefinitions/{alertDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertDefinitionId": _SERIALIZER.url("alert_definition_id", alert_definition_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertDefinitions" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AlertDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`alert_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, alert_definition_id: str, **kwargs: Any) -> _models.AlertDefinition: + """Get the specified alert definition. + + :param scope: The scope of the alert definition. The scope can be any REST resource instance. + For example, use '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a + subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param alert_definition_id: The name of the alert definition to get. Required. + :type alert_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertDefinition] + + request = build_get_request( + scope=scope, + alert_definition_id=alert_definition_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertDefinitions/{alertDefinitionId}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.AlertDefinition"]: + """Gets alert definitions for a resource scope. + + :param scope: The scope of the alert definition. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AlertDefinition or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AlertDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alertDefinitions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_incidents_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_incidents_operations.py new file mode 100644 index 00000000000..3ae21275bfb --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_incidents_operations.py @@ -0,0 +1,339 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, alert_id: str, alert_incident_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/alertIncidents/{alertIncidentId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + "alertIncidentId": _SERIALIZER.url("alert_incident_id", alert_incident_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/alertIncidents", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_remediate_request(scope: str, alert_id: str, alert_incident_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/alertIncidents/{alertIncidentId}/remediate", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + "alertIncidentId": _SERIALIZER.url("alert_incident_id", alert_incident_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AlertIncidentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`alert_incidents` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, alert_id: str, alert_incident_id: str, **kwargs: Any) -> _models.AlertIncident: + """Get the specified alert incident. + + :param scope: The scope of the alert incident. The scope can be any REST resource instance. For + example, use '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a + subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param alert_id: The name of the alert. Required. + :type alert_id: str + :param alert_incident_id: The name of the alert incident to get. Required. + :type alert_incident_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertIncident or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertIncident + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertIncident] + + request = build_get_request( + scope=scope, + alert_id=alert_id, + alert_incident_id=alert_incident_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertIncident", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/alertIncidents/{alertIncidentId}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, alert_id: str, **kwargs: Any) -> Iterable["_models.AlertIncident"]: + """Gets alert incidents for a resource scope. + + :param scope: The scope of the alert incident. Required. + :type scope: str + :param alert_id: The name of the alert. Required. + :type alert_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AlertIncident or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertIncident] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertIncidentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AlertIncidentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/alertIncidents"} # type: ignore + + @distributed_trace + def remediate( # pylint: disable=inconsistent-return-statements + self, scope: str, alert_id: str, alert_incident_id: str, **kwargs: Any + ) -> None: + """Remediate an alert incident. + + :param scope: The scope of the alert incident. Required. + :type scope: str + :param alert_id: The name of the alert. Required. + :type alert_id: str + :param alert_incident_id: The name of the alert incident to remediate. Required. + :type alert_incident_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_remediate_request( + scope=scope, + alert_id=alert_id, + alert_incident_id=alert_incident_id, + api_version=api_version, + template_url=self.remediate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + remediate.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/alertIncidents/{alertIncidentId}/remediate"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_operation_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_operation_operations.py new file mode 100644 index 00000000000..4d5c3594642 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alert_operation_operations.py @@ -0,0 +1,216 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, operation_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/operations/{operationId}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "operationId": _SERIALIZER.url("operation_id", operation_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/operations") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AlertOperationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`alert_operation` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, operation_id: str, **kwargs: Any) -> _models.AlertOperationResult: + """Get the specified alert operation. + + :param scope: The scope of the alert operation. Required. + :type scope: str + :param operation_id: The id of the alert operation. Required. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertOperationResult or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertOperationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationResult] + + request = build_get_request( + scope=scope, + operation_id=operation_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertOperationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/operations/{operationId}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> _models.AlertOperationListResult: + """Gets alert operations for a resource scope. + + :param scope: The scope of the alert operation. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AlertOperationListResult or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AlertOperationListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationListResult] + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertOperationListResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alerts_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alerts_operations.py new file mode 100644 index 00000000000..d0d7045843a --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_alerts_operations.py @@ -0,0 +1,673 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_refresh_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/refresh" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_refresh_all_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/refresh") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AlertsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`alerts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: + """Get the specified alert. + + :param scope: The scope of the alert. The scope can be any REST resource instance. For example, + use '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/' for a subscription, + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' + for a resource group, and + '/providers/Microsoft.Subscription/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' + for a resource. Required. + :type scope: str + :param alert_id: The name of the alert to get. Required. + :type alert_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Alert] + + request = build_get_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Alert", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}"} # type: ignore + + @overload + def update( + self, + scope: str, + alert_id: str, + parameters: _models.Alert, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Alert: + """Update an alert. + + :param scope: The scope of the alert. Required. + :type scope: str + :param alert_id: The name of the alert to dismiss. Required. + :type alert_id: str + :param parameters: Parameters for the alert. Required. + :type parameters: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, scope: str, alert_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Alert: + """Update an alert. + + :param scope: The scope of the alert. Required. + :type scope: str + :param alert_id: The name of the alert to dismiss. Required. + :type alert_id: str + :param parameters: Parameters for the alert. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update(self, scope: str, alert_id: str, parameters: Union[_models.Alert, IO], **kwargs: Any) -> _models.Alert: + """Update an alert. + + :param scope: The scope of the alert. Required. + :type scope: str + :param alert_id: The name of the alert to dismiss. Required. + :type alert_id: str + :param parameters: Parameters for the alert. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Alert] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Alert") + + request = build_update_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Alert", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}"} # type: ignore + + @distributed_trace + def list_for_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.Alert"]: + """Gets alerts for a resource scope. + + :param scope: The scope of the alert. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Alert or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.Alert] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AlertListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts"} # type: ignore + + def _refresh_initial(self, scope: str, alert_id: str, **kwargs: Any) -> _models.AlertOperationResult: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationResult] + + request = build_refresh_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self._refresh_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("AlertOperationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _refresh_initial.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/refresh"} # type: ignore + + @distributed_trace + def begin_refresh(self, scope: str, alert_id: str, **kwargs: Any) -> LROPoller[_models.AlertOperationResult]: + """Refresh an alert. + + :param scope: The scope of the alert. Required. + :type scope: str + :param alert_id: The name of the alert to refresh. Required. + :type alert_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either AlertOperationResult or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationResult] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._refresh_initial( # type: ignore + scope=scope, + alert_id=alert_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("AlertOperationResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, response_headers) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_refresh.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/{alertId}/refresh"} # type: ignore + + def _refresh_all_initial(self, scope: str, **kwargs: Any) -> _models.AlertOperationResult: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationResult] + + request = build_refresh_all_request( + scope=scope, + api_version=api_version, + template_url=self._refresh_all_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("AlertOperationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _refresh_all_initial.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/refresh"} # type: ignore + + @distributed_trace + def begin_refresh_all(self, scope: str, **kwargs: Any) -> LROPoller[_models.AlertOperationResult]: + """Refresh all alerts for a resource scope. + + :param scope: The scope of the alert. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either AlertOperationResult or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.authorization.v2021_12_01_preview.models.AlertOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertOperationResult] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._refresh_all_initial( # type: ignore + scope=scope, api_version=api_version, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("AlertOperationResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, response_headers) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_refresh_all.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/alerts/refresh"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_operations.py new file mode 100644 index 00000000000..00ac57a8270 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_operations.py @@ -0,0 +1,143 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: + """Lists the operations available from this provider. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_default_settings_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_default_settings_operations.py new file mode 100644 index 00000000000..43ed386ee59 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_default_settings_operations.py @@ -0,0 +1,280 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_put_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScopeAccessReviewDefaultSettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`scope_access_review_default_settings` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, **kwargs: Any) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param scope: The scope of the resource. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + request = build_get_request( + scope=scope, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore + + @overload + def put( + self, + scope: str, + properties: _models.AccessReviewScheduleSettings, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Access review schedule settings. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleSettings + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put( + self, scope: str, properties: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Access review schedule settings. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put( + self, scope: str, properties: Union[_models.AccessReviewScheduleSettings, IO], **kwargs: Any + ) -> _models.AccessReviewDefaultSettings: + """Get access review default settings for the subscription. + + :param scope: The scope of the resource. Required. + :type scope: str + :param properties: Access review schedule settings. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleSettings or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewDefaultSettings or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDefaultSettings + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDefaultSettings] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleSettings") + + request = build_put_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewDefaultSettings", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + put.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleSettings/default"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_instance_operations.py new file mode 100644 index 00000000000..b1c5e8bb74c --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_instance_operations.py @@ -0,0 +1,150 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_generate_download_uri_request( + scope: str, history_definition_id: str, instance_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances/{instanceId}/generateDownloadUri", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "historyDefinitionId": _SERIALIZER.url("history_definition_id", history_definition_id, "str"), + "instanceId": _SERIALIZER.url("instance_id", instance_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScopeAccessReviewHistoryDefinitionInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`scope_access_review_history_definition_instance` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def generate_download_uri( + self, scope: str, history_definition_id: str, instance_id: str, **kwargs: Any + ) -> _models.AccessReviewHistoryInstance: + """Generates a uri which can be used to retrieve review history data. This URI has a TTL of 1 day + and can be retrieved by fetching the accessReviewHistoryDefinition object. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param instance_id: The id of the access review history definition instance to generate a URI + for. Required. + :type instance_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryInstance] + + request = build_generate_download_uri_request( + scope=scope, + history_definition_id=history_definition_id, + instance_id=instance_id, + api_version=api_version, + template_url=self.generate_download_uri.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + generate_download_uri.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances/{instanceId}/generateDownloadUri"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_instances_operations.py new file mode 100644 index 00000000000..9d8bdcd6de9 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_instances_operations.py @@ -0,0 +1,161 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(scope: str, history_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "historyDefinitionId": _SERIALIZER.url("history_definition_id", history_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScopeAccessReviewHistoryDefinitionInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`scope_access_review_history_definition_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, history_definition_id: str, **kwargs: Any + ) -> Iterable["_models.AccessReviewHistoryInstance"]: + """Get access review history definition instances by definition Id. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewHistoryInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinitionInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + history_definition_id=history_definition_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewHistoryDefinitionInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}/instances"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_operations.py new file mode 100644 index 00000000000..f51131afeeb --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definition_operations.py @@ -0,0 +1,308 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_request(scope: str, history_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "historyDefinitionId": _SERIALIZER.url("history_definition_id", history_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request(scope: str, history_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "historyDefinitionId": _SERIALIZER.url("history_definition_id", history_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScopeAccessReviewHistoryDefinitionOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`scope_access_review_history_definition` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create( + self, + scope: str, + history_definition_id: str, + properties: _models.AccessReviewHistoryDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + history_definition_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + history_definition_id: str, + properties: Union[_models.AccessReviewHistoryDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewHistoryDefinition: + """Create a scheduled or one-time Access Review History Definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :param properties: Access review history definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinitionProperties or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewHistoryDefinitionProperties") + + request = build_create_request( + scope=scope, + history_definition_id=history_definition_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore + + @distributed_trace + def delete_by_id( # pylint: disable=inconsistent-return-statements + self, scope: str, history_definition_id: str, **kwargs: Any + ) -> None: + """Delete an access review history definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_id_request( + scope=scope, + history_definition_id=history_definition_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definitions_operations.py new file mode 100644 index 00000000000..0b5e32881fb --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_history_definitions_operations.py @@ -0,0 +1,247 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(scope: str, history_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "historyDefinitionId": _SERIALIZER.url("history_definition_id", history_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScopeAccessReviewHistoryDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`scope_access_review_history_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewHistoryDefinition"]: + """Lists the accessReviewHistoryDefinitions available from this provider, definition instances are + only available for 30 days after creation. + + :param scope: The scope of the resource. Required. + :type scope: str + :param filter: The filter to apply on the operation. Only standard filters on definition name + and created date are supported. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewHistoryDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewHistoryDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions"} # type: ignore + + @distributed_trace + def get_by_id(self, scope: str, history_definition_id: str, **kwargs: Any) -> _models.AccessReviewHistoryDefinition: + """Get access review history definition by definition Id. + + :param scope: The scope of the resource. Required. + :type scope: str + :param history_definition_id: The id of the access review history definition. Required. + :type history_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewHistoryDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewHistoryDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewHistoryDefinition] + + request = build_get_by_id_request( + scope=scope, + history_definition_id=history_definition_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewHistoryDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewHistoryDefinitions/{historyDefinitionId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_contacted_reviewers_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_contacted_reviewers_operations.py new file mode 100644 index 00000000000..9e15baefa1a --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_contacted_reviewers_operations.py @@ -0,0 +1,165 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(scope: str, schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScopeAccessReviewInstanceContactedReviewersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`scope_access_review_instance_contacted_reviewers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> Iterable["_models.AccessReviewContactedReviewer"]: + """Get access review instance contacted reviewers. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewContactedReviewer or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewContactedReviewer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewContactedReviewerListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewContactedReviewerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_decisions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_decisions_operations.py new file mode 100644 index 00000000000..65b648db574 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_decisions_operations.py @@ -0,0 +1,175 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + scope: str, schedule_definition_id: str, id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScopeAccessReviewInstanceDecisionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`scope_access_review_instance_decisions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, schedule_definition_id: str, id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewDecision"]: + """Get access review instance decisions. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewDecision or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewDecision] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewDecisionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewDecisionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/decisions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_operations.py new file mode 100644 index 00000000000..32c56a4c1ac --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instance_operations.py @@ -0,0 +1,581 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_stop_request(scope: str, schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_record_all_decisions_request(scope: str, schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/recordAllDecisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reset_decisions_request(scope: str, schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_apply_decisions_request(scope: str, schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_send_reminders_request(scope: str, schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScopeAccessReviewInstanceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`scope_access_review_instance` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def stop( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to stop an access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/stop"} # type: ignore + + @overload + def record_all_decisions( # pylint: disable=inconsistent-return-statements + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: _models.RecordAllDecisionsProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """An action to approve/deny all decisions for a review with certain filters. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Record all decisions payload. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.RecordAllDecisionsProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def record_all_decisions( # pylint: disable=inconsistent-return-statements + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """An action to approve/deny all decisions for a review with certain filters. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Record all decisions payload. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def record_all_decisions( # pylint: disable=inconsistent-return-statements + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: Union[_models.RecordAllDecisionsProperties, IO], + **kwargs: Any + ) -> None: + """An action to approve/deny all decisions for a review with certain filters. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Record all decisions payload. Is either a model type or a IO type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.RecordAllDecisionsProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "RecordAllDecisionsProperties") + + request = build_record_all_decisions_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.record_all_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + record_all_decisions.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/recordAllDecisions"} # type: ignore + + @distributed_trace + def reset_decisions( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to reset all decisions for an access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reset_decisions_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.reset_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + reset_decisions.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/resetDecisions"} # type: ignore + + @distributed_trace + def apply_decisions( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to apply all decisions for an access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_apply_decisions_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.apply_decisions.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + apply_decisions.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/applyDecisions"} # type: ignore + + @distributed_trace + def send_reminders( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> None: + """An action to send reminders for an access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_send_reminders_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.send_reminders.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + send_reminders.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/sendReminders"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instances_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instances_operations.py new file mode 100644 index 00000000000..b14ff99e7c2 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_instances_operations.py @@ -0,0 +1,443 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + scope: str, schedule_definition_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(scope: str, schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(scope: str, schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScopeAccessReviewInstancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`scope_access_review_instances` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, schedule_definition_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewInstance"]: + """Get access review instances. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewInstance or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstanceListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewInstanceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances"} # type: ignore + + @distributed_trace + def get_by_id( + self, scope: str, schedule_definition_id: str, id: str, **kwargs: Any + ) -> _models.AccessReviewInstance: + """Get access review instances. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + request = build_get_by_id_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore + + @overload + def create( + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: _models.AccessReviewInstanceProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + schedule_definition_id: str, + id: str, + properties: Union[_models.AccessReviewInstanceProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewInstance: + """Update access review instance. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :param properties: Access review instance properties. Is either a model type or a IO type. + Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstanceProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewInstance or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewInstance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewInstance] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewInstanceProperties") + + request = build_create_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewInstance", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_schedule_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_schedule_definitions_operations.py new file mode 100644 index 00000000000..012b9717fb1 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_scope_access_review_schedule_definitions_operations.py @@ -0,0 +1,588 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(scope: str, schedule_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request(scope: str, schedule_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_by_id_request(scope: str, schedule_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_stop_request(scope: str, schedule_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScopeAccessReviewScheduleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`scope_access_review_schedule_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.AccessReviewScheduleDefinition"]: + """Get access review schedule definitions. + + :param scope: The scope of the resource. Required. + :type scope: str + :param filter: The filter to apply on the operation. Other than standard filters, one custom + filter option is supported : 'assignedToMeToReview()'. When one specified + $filter=assignedToMeToReview(), only items that are assigned to the calling user to review are + returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewScheduleDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewScheduleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions"} # type: ignore + + @distributed_trace + def get_by_id( + self, scope: str, schedule_definition_id: str, **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Get single access review definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + request = build_get_by_id_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace + def delete_by_id( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Delete access review schedule definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_id_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @overload + def create_or_update_by_id( + self, + scope: str, + schedule_definition_id: str, + properties: _models.AccessReviewScheduleDefinitionProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_by_id( + self, + scope: str, + schedule_definition_id: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_by_id( + self, + scope: str, + schedule_definition_id: str, + properties: Union[_models.AccessReviewScheduleDefinitionProperties, IO], + **kwargs: Any + ) -> _models.AccessReviewScheduleDefinition: + """Create or Update access review schedule definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param properties: Access review schedule definition properties. Is either a model type or a IO + type. Required. + :type properties: + ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinitionProperties + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: AccessReviewScheduleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewScheduleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewScheduleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "AccessReviewScheduleDefinitionProperties") + + request = build_create_or_update_by_id_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AccessReviewScheduleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update_by_id.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}"} # type: ignore + + @distributed_trace + def stop( # pylint: disable=inconsistent-return-statements + self, scope: str, schedule_definition_id: str, **kwargs: Any + ) -> None: + """Stop access review definition. + + :param scope: The scope of the resource. Required. + :type scope: str + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( + scope=scope, + schedule_definition_id=schedule_definition_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + stop.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/stop"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py new file mode 100644 index 00000000000..48d84587e79 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/operations/_tenant_level_access_review_instance_contacted_reviewers_operations.py @@ -0,0 +1,161 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(schedule_definition_id: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers", + ) # pylint: disable=line-too-long + path_format_arguments = { + "scheduleDefinitionId": _SERIALIZER.url("schedule_definition_id", schedule_definition_id, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class TenantLevelAccessReviewInstanceContactedReviewersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2021_12_01_preview.AuthorizationManagementClient`'s + :attr:`tenant_level_access_review_instance_contacted_reviewers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, schedule_definition_id: str, id: str, **kwargs: Any + ) -> Iterable["_models.AccessReviewContactedReviewer"]: + """Get access review instance contacted reviewers. + + :param schedule_definition_id: The id of the access review schedule definition. Required. + :type schedule_definition_id: str + :param id: The id of the access review instance. Required. + :type id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AccessReviewContactedReviewer or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2021_12_01_preview.models.AccessReviewContactedReviewer] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessReviewContactedReviewerListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + schedule_definition_id=schedule_definition_id, + id=id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AccessReviewContactedReviewerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorDefinition, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/accessReviewScheduleDefinitions/{scheduleDefinitionId}/instances/{id}/contactedReviewers"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/py.typed b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/py.typed new file mode 100644 index 00000000000..e5aff4f83af --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2021_12_01_preview/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/__init__.py new file mode 100644 index 00000000000..9eb8d3ec28c --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/__init__.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._authorization_management_client import AuthorizationManagementClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_authorization_management_client.py new file mode 100644 index 00000000000..6f4840749c3 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_authorization_management_client.py @@ -0,0 +1,125 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models +from .._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + DenyAssignmentsOperations, + PermissionsOperations, + ProviderOperationsMetadataOperations, + RoleAssignmentsOperations, + RoleDefinitionsOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to get deny + assignments. A deny assignment describes the set of actions on resources that are denied for + Azure Active Directory users. + + :ivar deny_assignments: DenyAssignmentsOperations operations + :vartype deny_assignments: + azure.mgmt.authorization.v2022_04_01.operations.DenyAssignmentsOperations + :ivar provider_operations_metadata: ProviderOperationsMetadataOperations operations + :vartype provider_operations_metadata: + azure.mgmt.authorization.v2022_04_01.operations.ProviderOperationsMetadataOperations + :ivar role_assignments: RoleAssignmentsOperations operations + :vartype role_assignments: + azure.mgmt.authorization.v2022_04_01.operations.RoleAssignmentsOperations + :ivar permissions: PermissionsOperations operations + :vartype permissions: azure.mgmt.authorization.v2022_04_01.operations.PermissionsOperations + :ivar role_definitions: RoleDefinitionsOperations operations + :vartype role_definitions: + azure.mgmt.authorization.v2022_04_01.operations.RoleDefinitionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2022-04-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.deny_assignments = DenyAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.provider_operations_metadata = ProviderOperationsMetadataOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_assignments = RoleAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.permissions = PermissionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.role_definitions = RoleDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> AuthorizationManagementClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_configuration.py new file mode 100644 index 00000000000..8231f4b9cfb --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_configuration.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for AuthorizationManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-04-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-04-01") # type: str + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_metadata.json b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_metadata.json new file mode 100644 index 00000000000..52c70819b93 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_metadata.json @@ -0,0 +1,106 @@ +{ + "chosen_version": "2022-04-01", + "total_api_version_list": ["2022-04-01"], + "client": { + "name": "AuthorizationManagementClient", + "filename": "_authorization_management_client", + "description": "Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to get deny assignments. A deny assignment describes the set of actions on resources that are denied for Azure Active Directory users.", + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, + "azure_arm": true, + "has_lro_operations": false, + "client_side_validation": false, + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AuthorizationManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "global_parameters": { + "sync": { + "credential": { + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials.TokenCredential", + "required": true + }, + "subscription_id": { + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", + "docstring_type": "str", + "required": true + } + }, + "async": { + "credential": { + "signature": "credential: \"AsyncTokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", + "required": true + }, + "subscription_id": { + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", + "docstring_type": "str", + "required": true + } + }, + "constant": { + }, + "call": "credential, subscription_id", + "service_client_specific": { + "sync": { + "api_version": { + "signature": "api_version=None, # type: Optional[str]", + "description": "API version to use if no profile is provided, or if missing in profile.", + "docstring_type": "str", + "required": false + }, + "base_url": { + "signature": "base_url: str = \"https://management.azure.com\",", + "description": "Service URL", + "docstring_type": "str", + "required": false + }, + "profile": { + "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "description": "A profile definition, from KnownProfiles to dict.", + "docstring_type": "azure.profiles.KnownProfiles", + "required": false + } + }, + "async": { + "api_version": { + "signature": "api_version: Optional[str] = None,", + "description": "API version to use if no profile is provided, or if missing in profile.", + "docstring_type": "str", + "required": false + }, + "base_url": { + "signature": "base_url: str = \"https://management.azure.com\",", + "description": "Service URL", + "docstring_type": "str", + "required": false + }, + "profile": { + "signature": "profile: KnownProfiles = KnownProfiles.default,", + "description": "A profile definition, from KnownProfiles to dict.", + "docstring_type": "azure.profiles.KnownProfiles", + "required": false + } + } + } + }, + "config": { + "credential": true, + "credential_scopes": ["https://management.azure.com/.default"], + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "operation_groups": { + "deny_assignments": "DenyAssignmentsOperations", + "provider_operations_metadata": "ProviderOperationsMetadataOperations", + "role_assignments": "RoleAssignmentsOperations", + "permissions": "PermissionsOperations", + "role_definitions": "RoleDefinitionsOperations" + } +} \ No newline at end of file diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_vendor.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_vendor.py new file mode 100644 index 00000000000..9aad73fc743 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_version.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_version.py new file mode 100644 index 00000000000..cac9f5d10f8 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "3.0.0" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/__init__.py new file mode 100644 index 00000000000..dd28625b36f --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._authorization_management_client import AuthorizationManagementClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["AuthorizationManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_authorization_management_client.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_authorization_management_client.py new file mode 100644 index 00000000000..3c58e60529a --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_authorization_management_client.py @@ -0,0 +1,122 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models +from ..._serialization import Deserializer, Serializer +from ._configuration import AuthorizationManagementClientConfiguration +from .operations import ( + DenyAssignmentsOperations, + PermissionsOperations, + ProviderOperationsMetadataOperations, + RoleAssignmentsOperations, + RoleDefinitionsOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class AuthorizationManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Role based access control provides you a way to apply granular level policy administration down + to individual resources or resource groups. These operations enable you to get deny + assignments. A deny assignment describes the set of actions on resources that are denied for + Azure Active Directory users. + + :ivar deny_assignments: DenyAssignmentsOperations operations + :vartype deny_assignments: + azure.mgmt.authorization.v2022_04_01.aio.operations.DenyAssignmentsOperations + :ivar provider_operations_metadata: ProviderOperationsMetadataOperations operations + :vartype provider_operations_metadata: + azure.mgmt.authorization.v2022_04_01.aio.operations.ProviderOperationsMetadataOperations + :ivar role_assignments: RoleAssignmentsOperations operations + :vartype role_assignments: + azure.mgmt.authorization.v2022_04_01.aio.operations.RoleAssignmentsOperations + :ivar permissions: PermissionsOperations operations + :vartype permissions: azure.mgmt.authorization.v2022_04_01.aio.operations.PermissionsOperations + :ivar role_definitions: RoleDefinitionsOperations operations + :vartype role_definitions: + azure.mgmt.authorization.v2022_04_01.aio.operations.RoleDefinitionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2022-04-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AuthorizationManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.deny_assignments = DenyAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.provider_operations_metadata = ProviderOperationsMetadataOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.role_assignments = RoleAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.permissions = PermissionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.role_definitions = RoleDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "AuthorizationManagementClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_configuration.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_configuration.py new file mode 100644 index 00000000000..481ef853904 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_configuration.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class AuthorizationManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for AuthorizationManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-04-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AuthorizationManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-04-01") # type: str + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-authorization/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/__init__.py new file mode 100644 index 00000000000..bbb62cee061 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._deny_assignments_operations import DenyAssignmentsOperations +from ._provider_operations_metadata_operations import ProviderOperationsMetadataOperations +from ._role_assignments_operations import RoleAssignmentsOperations +from ._permissions_operations import PermissionsOperations +from ._role_definitions_operations import RoleDefinitionsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DenyAssignmentsOperations", + "ProviderOperationsMetadataOperations", + "RoleAssignmentsOperations", + "PermissionsOperations", + "RoleDefinitionsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_deny_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_deny_assignments_operations.py new file mode 100644 index 00000000000..54f6121da98 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_deny_assignments_operations.py @@ -0,0 +1,557 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._deny_assignments_operations import ( + build_get_by_id_request, + build_get_request, + build_list_for_resource_group_request, + build_list_for_resource_request, + build_list_for_scope_request, + build_list_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class DenyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2022_04_01.aio.AuthorizationManagementClient`'s + :attr:`deny_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.DenyAssignment"]: + """Gets deny assignments for a resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource. Required. + :type resource_type: str + :param resource_name: The name of the resource to get deny assignments for. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny + assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny + assignments by name at specified scope. Use $filter=principalId eq '{id}' to return all deny + assignments at, above and below the scope for the specified principal. Use + $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, above and below the + scope for the specified principal. This filter is different from the principalId filter as it + returns not only those deny assignments that contain the specified principal is the Principals + list but also those deny assignments that contain the specified principal is the + ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny + assignment name and description properties are returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.DenyAssignment"]: + """Gets deny assignments for a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny + assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny + assignments by name at specified scope. Use $filter=principalId eq '{id}' to return all deny + assignments at, above and below the scope for the specified principal. Use + $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, above and below the + scope for the specified principal. This filter is different from the principalId filter as it + returns not only those deny assignments that contain the specified principal is the Principals + list but also those deny assignments that contain the specified principal is the + ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny + assignment name and description properties are returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.DenyAssignment"]: + """Gets all deny assignments for the subscription. + + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny + assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny + assignments by name at specified scope. Use $filter=principalId eq '{id}' to return all deny + assignments at, above and below the scope for the specified principal. Use + $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, above and below the + scope for the specified principal. This filter is different from the principalId filter as it + returns not only those deny assignments that contain the specified principal is the Principals + list but also those deny assignments that contain the specified principal is the + ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny + assignment name and description properties are returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, deny_assignment_id: str, **kwargs: Any) -> _models.DenyAssignment: + """Get the specified deny assignment. + + :param scope: The scope of the deny assignment. Required. + :type scope: str + :param deny_assignment_id: The ID of the deny assignment to get. Required. + :type deny_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DenyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignment] + + request = build_get_request( + scope=scope, + deny_assignment_id=deny_assignment_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DenyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId}"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, deny_assignment_id: str, **kwargs: Any) -> _models.DenyAssignment: + """Gets a deny assignment by ID. + + :param deny_assignment_id: The fully qualified deny assignment ID. For example, use the format, + /subscriptions/{guid}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} for + subscription level deny assignments, or + /providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} for tenant level deny + assignments. Required. + :type deny_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DenyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignment] + + request = build_get_by_id_request( + deny_assignment_id=deny_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DenyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{denyAssignmentId}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.DenyAssignment"]: + """Gets deny assignments for a scope. + + :param scope: The scope of the deny assignments. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny + assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny + assignments by name at specified scope. Use $filter=principalId eq '{id}' to return all deny + assignments at, above and below the scope for the specified principal. Use + $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, above and below the + scope for the specified principal. This filter is different from the principalId filter as it + returns not only those deny assignments that contain the specified principal is the Principals + list but also those deny assignments that contain the specified principal is the + ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny + assignment name and description properties are returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_permissions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_permissions_operations.py new file mode 100644 index 00000000000..33799d74168 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_permissions_operations.py @@ -0,0 +1,229 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._permissions_operations import build_list_for_resource_group_request, build_list_for_resource_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PermissionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2022_04_01.aio.AuthorizationManagementClient`'s + :attr:`permissions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_for_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Permission"]: + """Gets all permissions the caller has for a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PermissionGetResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions"} # type: ignore + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.Permission"]: + """Gets all permissions the caller has for a resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource. Required. + :type resource_type: str + :param resource_name: The name of the resource to get the permissions for. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PermissionGetResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_provider_operations_metadata_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_provider_operations_metadata_operations.py new file mode 100644 index 00000000000..98bf7a71162 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_provider_operations_metadata_operations.py @@ -0,0 +1,191 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._provider_operations_metadata_operations import build_get_request, build_list_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ProviderOperationsMetadataOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2022_04_01.aio.AuthorizationManagementClient`'s + :attr:`provider_operations_metadata` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_provider_namespace: str, expand: str = "resourceTypes", **kwargs: Any + ) -> _models.ProviderOperationsMetadata: + """Gets provider operations metadata for the specified resource provider. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". + :type expand: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ProviderOperationsMetadata or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.ProviderOperationsMetadata + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadata] + + request = build_get_request( + resource_provider_namespace=resource_provider_namespace, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ProviderOperationsMetadata", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}"} # type: ignore + + @distributed_trace + def list(self, expand: str = "resourceTypes", **kwargs: Any) -> AsyncIterable["_models.ProviderOperationsMetadata"]: + """Gets provider operations metadata for all resource providers. + + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". + :type expand: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ProviderOperationsMetadata or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.ProviderOperationsMetadata] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadataListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ProviderOperationsMetadataListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_role_assignments_operations.py new file mode 100644 index 00000000000..edb09edb1a8 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_role_assignments_operations.py @@ -0,0 +1,1001 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_assignments_operations import ( + build_create_by_id_request, + build_create_request, + build_delete_by_id_request, + build_delete_request, + build_get_by_id_request, + build_get_request, + build_list_for_resource_group_request, + build_list_for_resource_request, + build_list_for_scope_request, + build_list_for_subscription_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2022_04_01.aio.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_for_subscription( + self, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: + """List all role assignments that apply to a subscription. + + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignments at or above the scope. Use $filter=principalId eq {id} to return all role + assignments at, above or below the scope for the specified principal. Default value is None. + :type filter: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_subscription_request( + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: + """List all role assignments that apply to a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignments at or above the scope. Use $filter=principalId eq {id} to return all role + assignments at, above or below the scope for the specified principal. Default value is None. + :type filter: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: + """List all role assignments that apply to a resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param resource_type: The resource type name. For example the type name of a web app is 'sites' + (from Microsoft.Web/sites). Required. + :type resource_type: str + :param resource_name: The resource name. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignments at or above the scope. Use $filter=principalId eq {id} to return all role + assignments at, above or below the scope for the specified principal. Default value is None. + :type filter: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace_async + async def get( + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> _models.RoleAssignment: + """Get a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignmentCreateParameters + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace_async + async def delete( + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: + """Delete a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, + scope: str, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RoleAssignment"]: + """List all role assignments that apply to a scope. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignments at or above the scope. Use $filter=principalId eq {id} to return all role + assignments at, above or below the scope for the specified principal. Default value is None. + :type filter: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :param skip_token: The skipToken to apply on the operation. Use $skipToken={skiptoken} to + return paged role assignments following the skipToken passed. Only supported on provider level + calls. Default value is None. + :type skip_token: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + tenant_id=tenant_id, + skip_token=skip_token, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace_async + async def get_by_id( + self, role_assignment_id: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> _models.RoleAssignment: + """Get a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_by_id_request( + role_assignment_id=role_assignment_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @overload + async def create_by_id( + self, + role_assignment_id: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, role_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, role_assignment_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignmentCreateParameters + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @distributed_trace_async + async def delete_by_id( + self, role_assignment_id: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: + """Delete a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_by_id_request( + role_assignment_id=role_assignment_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_role_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_role_definitions_operations.py new file mode 100644 index 00000000000..9b6bf5a1475 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/aio/operations/_role_definitions_operations.py @@ -0,0 +1,449 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._role_definitions_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_by_id_request, + build_get_request, + build_list_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RoleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2022_04_01.aio.AuthorizationManagementClient`'s + :attr:`role_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete(self, scope: str, role_definition_id: str, **kwargs: Any) -> Optional[_models.RoleDefinition]: + """Deletes a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition to delete. Required. + :type role_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or None or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleDefinition]] + + request = build_delete_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("RoleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, role_definition_id: str, **kwargs: Any) -> _models.RoleDefinition: + """Get role definition by name (GUID). + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + request = build_get_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @overload + async def create_or_update( + self, + scope: str, + role_definition_id: str, + role_definition: _models.RoleDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Required. + :type role_definition: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + scope: str, + role_definition_id: str, + role_definition: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Required. + :type role_definition: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, scope: str, role_definition_id: str, role_definition: Union[_models.RoleDefinition, IO], **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Is either a model type or a IO + type. Required. + :type role_definition: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(role_definition, (IO, bytes)): + _content = role_definition + else: + _json = self._serialize.body(role_definition, "RoleDefinition") + + request = build_create_or_update_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace + def list(self, scope: str, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.RoleDefinition"]: + """Get all role definitions that are applicable at scope and above. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use atScopeAndBelow filter to search below + the given scope as well. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RoleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, role_id: str, **kwargs: Any) -> _models.RoleDefinition: + """Gets a role definition by ID. + + :param role_id: The fully qualified role definition ID. Use the format, + /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for + subscription level role definitions, or + /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for tenant level role + definitions. Required. + :type role_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + request = build_get_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{roleId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/__init__.py new file mode 100644 index 00000000000..dc6219ed0e5 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/__init__.py @@ -0,0 +1,99 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import ApprovalSettings +from ._models_py3 import ApprovalStage +from ._models_py3 import DenyAssignment +from ._models_py3 import DenyAssignmentFilter +from ._models_py3 import DenyAssignmentListResult +from ._models_py3 import DenyAssignmentPermission +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import Permission +from ._models_py3 import PermissionGetResult +from ._models_py3 import Principal +from ._models_py3 import ProviderOperation +from ._models_py3 import ProviderOperationsMetadata +from ._models_py3 import ProviderOperationsMetadataListResult +from ._models_py3 import ResourceType +from ._models_py3 import RoleAssignment +from ._models_py3 import RoleAssignmentCreateParameters +from ._models_py3 import RoleAssignmentFilter +from ._models_py3 import RoleAssignmentListResult +from ._models_py3 import RoleDefinition +from ._models_py3 import RoleDefinitionFilter +from ._models_py3 import RoleDefinitionListResult +from ._models_py3 import RoleManagementPolicyApprovalRule +from ._models_py3 import RoleManagementPolicyAuthenticationContextRule +from ._models_py3 import RoleManagementPolicyEnablementRule +from ._models_py3 import RoleManagementPolicyExpirationRule +from ._models_py3 import RoleManagementPolicyNotificationRule +from ._models_py3 import RoleManagementPolicyRule +from ._models_py3 import RoleManagementPolicyRuleTarget +from ._models_py3 import UserSet +from ._models_py3 import ValidationResponse +from ._models_py3 import ValidationResponseErrorInfo + +from ._authorization_management_client_enums import ApprovalMode +from ._authorization_management_client_enums import EnablementRules +from ._authorization_management_client_enums import NotificationDeliveryMechanism +from ._authorization_management_client_enums import NotificationLevel +from ._authorization_management_client_enums import PrincipalType +from ._authorization_management_client_enums import RecipientType +from ._authorization_management_client_enums import RoleManagementPolicyRuleType +from ._authorization_management_client_enums import UserType +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ApprovalSettings", + "ApprovalStage", + "DenyAssignment", + "DenyAssignmentFilter", + "DenyAssignmentListResult", + "DenyAssignmentPermission", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "Permission", + "PermissionGetResult", + "Principal", + "ProviderOperation", + "ProviderOperationsMetadata", + "ProviderOperationsMetadataListResult", + "ResourceType", + "RoleAssignment", + "RoleAssignmentCreateParameters", + "RoleAssignmentFilter", + "RoleAssignmentListResult", + "RoleDefinition", + "RoleDefinitionFilter", + "RoleDefinitionListResult", + "RoleManagementPolicyApprovalRule", + "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", + "RoleManagementPolicyExpirationRule", + "RoleManagementPolicyNotificationRule", + "RoleManagementPolicyRule", + "RoleManagementPolicyRuleTarget", + "UserSet", + "ValidationResponse", + "ValidationResponseErrorInfo", + "ApprovalMode", + "EnablementRules", + "NotificationDeliveryMechanism", + "NotificationLevel", + "PrincipalType", + "RecipientType", + "RoleManagementPolicyRuleType", + "UserType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_authorization_management_client_enums.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_authorization_management_client_enums.py new file mode 100644 index 00000000000..b479e5120c4 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_authorization_management_client_enums.py @@ -0,0 +1,76 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ApprovalMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of rule.""" + + SINGLE_STAGE = "SingleStage" + SERIAL = "Serial" + PARALLEL = "Parallel" + NO_APPROVAL = "NoApproval" + + +class EnablementRules(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of enablement rule.""" + + MULTI_FACTOR_AUTHENTICATION = "MultiFactorAuthentication" + JUSTIFICATION = "Justification" + TICKETING = "Ticketing" + + +class NotificationDeliveryMechanism(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of notification.""" + + EMAIL = "Email" + + +class NotificationLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The notification level.""" + + NONE = "None" + CRITICAL = "Critical" + ALL = "All" + + +class PrincipalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The principal type of the assigned principal ID.""" + + USER = "User" + GROUP = "Group" + SERVICE_PRINCIPAL = "ServicePrincipal" + FOREIGN_GROUP = "ForeignGroup" + DEVICE = "Device" + + +class RecipientType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The recipient type.""" + + REQUESTOR = "Requestor" + APPROVER = "Approver" + ADMIN = "Admin" + + +class RoleManagementPolicyRuleType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of rule.""" + + ROLE_MANAGEMENT_POLICY_APPROVAL_RULE = "RoleManagementPolicyApprovalRule" + ROLE_MANAGEMENT_POLICY_AUTHENTICATION_CONTEXT_RULE = "RoleManagementPolicyAuthenticationContextRule" + ROLE_MANAGEMENT_POLICY_ENABLEMENT_RULE = "RoleManagementPolicyEnablementRule" + ROLE_MANAGEMENT_POLICY_EXPIRATION_RULE = "RoleManagementPolicyExpirationRule" + ROLE_MANAGEMENT_POLICY_NOTIFICATION_RULE = "RoleManagementPolicyNotificationRule" + + +class UserType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of user.""" + + USER = "User" + GROUP = "Group" diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_models_py3.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_models_py3.py new file mode 100644 index 00000000000..3083c814543 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_models_py3.py @@ -0,0 +1,1733 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + + +class ApprovalSettings(_serialization.Model): + """The approval settings. + + :ivar is_approval_required: Determines whether approval is required or not. + :vartype is_approval_required: bool + :ivar is_approval_required_for_extension: Determines whether approval is required for + assignment extension. + :vartype is_approval_required_for_extension: bool + :ivar is_requestor_justification_required: Determine whether requestor justification is + required. + :vartype is_requestor_justification_required: bool + :ivar approval_mode: The type of rule. Known values are: "SingleStage", "Serial", "Parallel", + and "NoApproval". + :vartype approval_mode: str or ~azure.mgmt.authorization.v2022_04_01.models.ApprovalMode + :ivar approval_stages: The approval stages of the request. + :vartype approval_stages: list[~azure.mgmt.authorization.v2022_04_01.models.ApprovalStage] + """ + + _attribute_map = { + "is_approval_required": {"key": "isApprovalRequired", "type": "bool"}, + "is_approval_required_for_extension": {"key": "isApprovalRequiredForExtension", "type": "bool"}, + "is_requestor_justification_required": {"key": "isRequestorJustificationRequired", "type": "bool"}, + "approval_mode": {"key": "approvalMode", "type": "str"}, + "approval_stages": {"key": "approvalStages", "type": "[ApprovalStage]"}, + } + + def __init__( + self, + *, + is_approval_required: Optional[bool] = None, + is_approval_required_for_extension: Optional[bool] = None, + is_requestor_justification_required: Optional[bool] = None, + approval_mode: Optional[Union[str, "_models.ApprovalMode"]] = None, + approval_stages: Optional[List["_models.ApprovalStage"]] = None, + **kwargs + ): + """ + :keyword is_approval_required: Determines whether approval is required or not. + :paramtype is_approval_required: bool + :keyword is_approval_required_for_extension: Determines whether approval is required for + assignment extension. + :paramtype is_approval_required_for_extension: bool + :keyword is_requestor_justification_required: Determine whether requestor justification is + required. + :paramtype is_requestor_justification_required: bool + :keyword approval_mode: The type of rule. Known values are: "SingleStage", "Serial", + "Parallel", and "NoApproval". + :paramtype approval_mode: str or ~azure.mgmt.authorization.v2022_04_01.models.ApprovalMode + :keyword approval_stages: The approval stages of the request. + :paramtype approval_stages: list[~azure.mgmt.authorization.v2022_04_01.models.ApprovalStage] + """ + super().__init__(**kwargs) + self.is_approval_required = is_approval_required + self.is_approval_required_for_extension = is_approval_required_for_extension + self.is_requestor_justification_required = is_requestor_justification_required + self.approval_mode = approval_mode + self.approval_stages = approval_stages + + +class ApprovalStage(_serialization.Model): + """The approval stage. + + :ivar approval_stage_time_out_in_days: The time in days when approval request would be timed + out. + :vartype approval_stage_time_out_in_days: int + :ivar is_approver_justification_required: Determines whether approver need to provide + justification for his decision. + :vartype is_approver_justification_required: bool + :ivar escalation_time_in_minutes: The time in minutes when the approval request would be + escalated if the primary approver does not approve. + :vartype escalation_time_in_minutes: int + :ivar primary_approvers: The primary approver of the request. + :vartype primary_approvers: list[~azure.mgmt.authorization.v2022_04_01.models.UserSet] + :ivar is_escalation_enabled: The value determine whether escalation feature is enabled. + :vartype is_escalation_enabled: bool + :ivar escalation_approvers: The escalation approver of the request. + :vartype escalation_approvers: list[~azure.mgmt.authorization.v2022_04_01.models.UserSet] + """ + + _attribute_map = { + "approval_stage_time_out_in_days": {"key": "approvalStageTimeOutInDays", "type": "int"}, + "is_approver_justification_required": {"key": "isApproverJustificationRequired", "type": "bool"}, + "escalation_time_in_minutes": {"key": "escalationTimeInMinutes", "type": "int"}, + "primary_approvers": {"key": "primaryApprovers", "type": "[UserSet]"}, + "is_escalation_enabled": {"key": "isEscalationEnabled", "type": "bool"}, + "escalation_approvers": {"key": "escalationApprovers", "type": "[UserSet]"}, + } + + def __init__( + self, + *, + approval_stage_time_out_in_days: Optional[int] = None, + is_approver_justification_required: Optional[bool] = None, + escalation_time_in_minutes: Optional[int] = None, + primary_approvers: Optional[List["_models.UserSet"]] = None, + is_escalation_enabled: Optional[bool] = None, + escalation_approvers: Optional[List["_models.UserSet"]] = None, + **kwargs + ): + """ + :keyword approval_stage_time_out_in_days: The time in days when approval request would be timed + out. + :paramtype approval_stage_time_out_in_days: int + :keyword is_approver_justification_required: Determines whether approver need to provide + justification for his decision. + :paramtype is_approver_justification_required: bool + :keyword escalation_time_in_minutes: The time in minutes when the approval request would be + escalated if the primary approver does not approve. + :paramtype escalation_time_in_minutes: int + :keyword primary_approvers: The primary approver of the request. + :paramtype primary_approvers: list[~azure.mgmt.authorization.v2022_04_01.models.UserSet] + :keyword is_escalation_enabled: The value determine whether escalation feature is enabled. + :paramtype is_escalation_enabled: bool + :keyword escalation_approvers: The escalation approver of the request. + :paramtype escalation_approvers: list[~azure.mgmt.authorization.v2022_04_01.models.UserSet] + """ + super().__init__(**kwargs) + self.approval_stage_time_out_in_days = approval_stage_time_out_in_days + self.is_approver_justification_required = is_approver_justification_required + self.escalation_time_in_minutes = escalation_time_in_minutes + self.primary_approvers = primary_approvers + self.is_escalation_enabled = is_escalation_enabled + self.escalation_approvers = escalation_approvers + + +class DenyAssignment(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Deny Assignment. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The deny assignment ID. + :vartype id: str + :ivar name: The deny assignment name. + :vartype name: str + :ivar type: The deny assignment type. + :vartype type: str + :ivar deny_assignment_name: The display name of the deny assignment. + :vartype deny_assignment_name: str + :ivar description: The description of the deny assignment. + :vartype description: str + :ivar permissions: An array of permissions that are denied by the deny assignment. + :vartype permissions: + list[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignmentPermission] + :ivar scope: The deny assignment scope. + :vartype scope: str + :ivar do_not_apply_to_child_scopes: Determines if the deny assignment applies to child scopes. + Default value is false. + :vartype do_not_apply_to_child_scopes: bool + :ivar principals: Array of principals to which the deny assignment applies. + :vartype principals: list[~azure.mgmt.authorization.v2022_04_01.models.Principal] + :ivar exclude_principals: Array of principals to which the deny assignment does not apply. + :vartype exclude_principals: list[~azure.mgmt.authorization.v2022_04_01.models.Principal] + :ivar is_system_protected: Specifies whether this deny assignment was created by Azure and + cannot be edited or deleted. + :vartype is_system_protected: bool + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "deny_assignment_name": {"key": "properties.denyAssignmentName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "permissions": {"key": "properties.permissions", "type": "[DenyAssignmentPermission]"}, + "scope": {"key": "properties.scope", "type": "str"}, + "do_not_apply_to_child_scopes": {"key": "properties.doNotApplyToChildScopes", "type": "bool"}, + "principals": {"key": "properties.principals", "type": "[Principal]"}, + "exclude_principals": {"key": "properties.excludePrincipals", "type": "[Principal]"}, + "is_system_protected": {"key": "properties.isSystemProtected", "type": "bool"}, + } + + def __init__( + self, + *, + deny_assignment_name: Optional[str] = None, + description: Optional[str] = None, + permissions: Optional[List["_models.DenyAssignmentPermission"]] = None, + scope: Optional[str] = None, + do_not_apply_to_child_scopes: Optional[bool] = None, + principals: Optional[List["_models.Principal"]] = None, + exclude_principals: Optional[List["_models.Principal"]] = None, + is_system_protected: Optional[bool] = None, + **kwargs + ): + """ + :keyword deny_assignment_name: The display name of the deny assignment. + :paramtype deny_assignment_name: str + :keyword description: The description of the deny assignment. + :paramtype description: str + :keyword permissions: An array of permissions that are denied by the deny assignment. + :paramtype permissions: + list[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignmentPermission] + :keyword scope: The deny assignment scope. + :paramtype scope: str + :keyword do_not_apply_to_child_scopes: Determines if the deny assignment applies to child + scopes. Default value is false. + :paramtype do_not_apply_to_child_scopes: bool + :keyword principals: Array of principals to which the deny assignment applies. + :paramtype principals: list[~azure.mgmt.authorization.v2022_04_01.models.Principal] + :keyword exclude_principals: Array of principals to which the deny assignment does not apply. + :paramtype exclude_principals: list[~azure.mgmt.authorization.v2022_04_01.models.Principal] + :keyword is_system_protected: Specifies whether this deny assignment was created by Azure and + cannot be edited or deleted. + :paramtype is_system_protected: bool + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.deny_assignment_name = deny_assignment_name + self.description = description + self.permissions = permissions + self.scope = scope + self.do_not_apply_to_child_scopes = do_not_apply_to_child_scopes + self.principals = principals + self.exclude_principals = exclude_principals + self.is_system_protected = is_system_protected + + +class DenyAssignmentFilter(_serialization.Model): + """Deny Assignments filter. + + :ivar deny_assignment_name: Return deny assignment with specified name. + :vartype deny_assignment_name: str + :ivar principal_id: Return all deny assignments where the specified principal is listed in the + principals list of deny assignments. + :vartype principal_id: str + :ivar gdpr_export_principal_id: Return all deny assignments where the specified principal is + listed either in the principals list or exclude principals list of deny assignments. + :vartype gdpr_export_principal_id: str + """ + + _attribute_map = { + "deny_assignment_name": {"key": "denyAssignmentName", "type": "str"}, + "principal_id": {"key": "principalId", "type": "str"}, + "gdpr_export_principal_id": {"key": "gdprExportPrincipalId", "type": "str"}, + } + + def __init__( + self, + *, + deny_assignment_name: Optional[str] = None, + principal_id: Optional[str] = None, + gdpr_export_principal_id: Optional[str] = None, + **kwargs + ): + """ + :keyword deny_assignment_name: Return deny assignment with specified name. + :paramtype deny_assignment_name: str + :keyword principal_id: Return all deny assignments where the specified principal is listed in + the principals list of deny assignments. + :paramtype principal_id: str + :keyword gdpr_export_principal_id: Return all deny assignments where the specified principal is + listed either in the principals list or exclude principals list of deny assignments. + :paramtype gdpr_export_principal_id: str + """ + super().__init__(**kwargs) + self.deny_assignment_name = deny_assignment_name + self.principal_id = principal_id + self.gdpr_export_principal_id = gdpr_export_principal_id + + +class DenyAssignmentListResult(_serialization.Model): + """Deny assignment list operation result. + + :ivar value: Deny assignment list. + :vartype value: list[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[DenyAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.DenyAssignment"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: Deny assignment list. + :paramtype value: list[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class DenyAssignmentPermission(_serialization.Model): + """Deny assignment permissions. + + :ivar actions: Actions to which the deny assignment does not grant access. + :vartype actions: list[str] + :ivar not_actions: Actions to exclude from that the deny assignment does not grant access. + :vartype not_actions: list[str] + :ivar data_actions: Data actions to which the deny assignment does not grant access. + :vartype data_actions: list[str] + :ivar not_data_actions: Data actions to exclude from that the deny assignment does not grant + access. + :vartype not_data_actions: list[str] + :ivar condition: The conditions on the Deny assignment permission. This limits the resources it + applies to. + :vartype condition: str + :ivar condition_version: Version of the condition. + :vartype condition_version: str + """ + + _attribute_map = { + "actions": {"key": "actions", "type": "[str]"}, + "not_actions": {"key": "notActions", "type": "[str]"}, + "data_actions": {"key": "dataActions", "type": "[str]"}, + "not_data_actions": {"key": "notDataActions", "type": "[str]"}, + "condition": {"key": "condition", "type": "str"}, + "condition_version": {"key": "conditionVersion", "type": "str"}, + } + + def __init__( + self, + *, + actions: Optional[List[str]] = None, + not_actions: Optional[List[str]] = None, + data_actions: Optional[List[str]] = None, + not_data_actions: Optional[List[str]] = None, + condition: Optional[str] = None, + condition_version: Optional[str] = None, + **kwargs + ): + """ + :keyword actions: Actions to which the deny assignment does not grant access. + :paramtype actions: list[str] + :keyword not_actions: Actions to exclude from that the deny assignment does not grant access. + :paramtype not_actions: list[str] + :keyword data_actions: Data actions to which the deny assignment does not grant access. + :paramtype data_actions: list[str] + :keyword not_data_actions: Data actions to exclude from that the deny assignment does not grant + access. + :paramtype not_data_actions: list[str] + :keyword condition: The conditions on the Deny assignment permission. This limits the resources + it applies to. + :paramtype condition: str + :keyword condition_version: Version of the condition. + :paramtype condition_version: str + """ + super().__init__(**kwargs) + self.actions = actions + self.not_actions = not_actions + self.data_actions = data_actions + self.not_data_actions = not_data_actions + self.condition = condition + self.condition_version = condition_version + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.authorization.v2022_04_01.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.mgmt.authorization.v2022_04_01.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.authorization.v2022_04_01.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.authorization.v2022_04_01.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class Permission(_serialization.Model): + """Role definition permissions. + + :ivar actions: Allowed actions. + :vartype actions: list[str] + :ivar not_actions: Denied actions. + :vartype not_actions: list[str] + :ivar data_actions: Allowed Data actions. + :vartype data_actions: list[str] + :ivar not_data_actions: Denied Data actions. + :vartype not_data_actions: list[str] + """ + + _attribute_map = { + "actions": {"key": "actions", "type": "[str]"}, + "not_actions": {"key": "notActions", "type": "[str]"}, + "data_actions": {"key": "dataActions", "type": "[str]"}, + "not_data_actions": {"key": "notDataActions", "type": "[str]"}, + } + + def __init__( + self, + *, + actions: Optional[List[str]] = None, + not_actions: Optional[List[str]] = None, + data_actions: Optional[List[str]] = None, + not_data_actions: Optional[List[str]] = None, + **kwargs + ): + """ + :keyword actions: Allowed actions. + :paramtype actions: list[str] + :keyword not_actions: Denied actions. + :paramtype not_actions: list[str] + :keyword data_actions: Allowed Data actions. + :paramtype data_actions: list[str] + :keyword not_data_actions: Denied Data actions. + :paramtype not_data_actions: list[str] + """ + super().__init__(**kwargs) + self.actions = actions + self.not_actions = not_actions + self.data_actions = data_actions + self.not_data_actions = not_data_actions + + +class PermissionGetResult(_serialization.Model): + """Permissions information. + + :ivar value: An array of permissions. + :vartype value: list[~azure.mgmt.authorization.v2022_04_01.models.Permission] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Permission]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.Permission"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: An array of permissions. + :paramtype value: list[~azure.mgmt.authorization.v2022_04_01.models.Permission] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class Principal(_serialization.Model): + """The name of the entity last modified it. + + :ivar id: The id of the principal made changes. + :vartype id: str + :ivar display_name: The name of the principal made changes. + :vartype display_name: str + :ivar type: Type of principal such as user , group etc. + :vartype type: str + :ivar email: Email of principal. + :vartype email: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "email": {"key": "email", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + display_name: Optional[str] = None, + type: Optional[str] = None, + email: Optional[str] = None, + **kwargs + ): + """ + :keyword id: The id of the principal made changes. + :paramtype id: str + :keyword display_name: The name of the principal made changes. + :paramtype display_name: str + :keyword type: Type of principal such as user , group etc. + :paramtype type: str + :keyword email: Email of principal. + :paramtype email: str + """ + super().__init__(**kwargs) + self.id = id + self.display_name = display_name + self.type = type + self.email = email + + +class ProviderOperation(_serialization.Model): + """Operation. + + :ivar name: The operation name. + :vartype name: str + :ivar display_name: The operation display name. + :vartype display_name: str + :ivar description: The operation description. + :vartype description: str + :ivar origin: The operation origin. + :vartype origin: str + :ivar properties: The operation properties. + :vartype properties: JSON + :ivar is_data_action: The dataAction flag to specify the operation type. + :vartype is_data_action: bool + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "origin": {"key": "origin", "type": "str"}, + "properties": {"key": "properties", "type": "object"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + origin: Optional[str] = None, + properties: Optional[JSON] = None, + is_data_action: Optional[bool] = None, + **kwargs + ): + """ + :keyword name: The operation name. + :paramtype name: str + :keyword display_name: The operation display name. + :paramtype display_name: str + :keyword description: The operation description. + :paramtype description: str + :keyword origin: The operation origin. + :paramtype origin: str + :keyword properties: The operation properties. + :paramtype properties: JSON + :keyword is_data_action: The dataAction flag to specify the operation type. + :paramtype is_data_action: bool + """ + super().__init__(**kwargs) + self.name = name + self.display_name = display_name + self.description = description + self.origin = origin + self.properties = properties + self.is_data_action = is_data_action + + +class ProviderOperationsMetadata(_serialization.Model): + """Provider Operations metadata. + + :ivar id: The provider id. + :vartype id: str + :ivar name: The provider name. + :vartype name: str + :ivar type: The provider type. + :vartype type: str + :ivar display_name: The provider display name. + :vartype display_name: str + :ivar resource_types: The provider resource types. + :vartype resource_types: list[~azure.mgmt.authorization.v2022_04_01.models.ResourceType] + :ivar operations: The provider operations. + :vartype operations: list[~azure.mgmt.authorization.v2022_04_01.models.ProviderOperation] + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "resource_types": {"key": "resourceTypes", "type": "[ResourceType]"}, + "operations": {"key": "operations", "type": "[ProviderOperation]"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + name: Optional[str] = None, + type: Optional[str] = None, + display_name: Optional[str] = None, + resource_types: Optional[List["_models.ResourceType"]] = None, + operations: Optional[List["_models.ProviderOperation"]] = None, + **kwargs + ): + """ + :keyword id: The provider id. + :paramtype id: str + :keyword name: The provider name. + :paramtype name: str + :keyword type: The provider type. + :paramtype type: str + :keyword display_name: The provider display name. + :paramtype display_name: str + :keyword resource_types: The provider resource types. + :paramtype resource_types: list[~azure.mgmt.authorization.v2022_04_01.models.ResourceType] + :keyword operations: The provider operations. + :paramtype operations: list[~azure.mgmt.authorization.v2022_04_01.models.ProviderOperation] + """ + super().__init__(**kwargs) + self.id = id + self.name = name + self.type = type + self.display_name = display_name + self.resource_types = resource_types + self.operations = operations + + +class ProviderOperationsMetadataListResult(_serialization.Model): + """Provider operations metadata list. + + :ivar value: The list of providers. + :vartype value: list[~azure.mgmt.authorization.v2022_04_01.models.ProviderOperationsMetadata] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ProviderOperationsMetadata]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.ProviderOperationsMetadata"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: The list of providers. + :paramtype value: list[~azure.mgmt.authorization.v2022_04_01.models.ProviderOperationsMetadata] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ResourceType(_serialization.Model): + """Resource Type. + + :ivar name: The resource type name. + :vartype name: str + :ivar display_name: The resource type display name. + :vartype display_name: str + :ivar operations: The resource type operations. + :vartype operations: list[~azure.mgmt.authorization.v2022_04_01.models.ProviderOperation] + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "operations": {"key": "operations", "type": "[ProviderOperation]"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display_name: Optional[str] = None, + operations: Optional[List["_models.ProviderOperation"]] = None, + **kwargs + ): + """ + :keyword name: The resource type name. + :paramtype name: str + :keyword display_name: The resource type display name. + :paramtype display_name: str + :keyword operations: The resource type operations. + :paramtype operations: list[~azure.mgmt.authorization.v2022_04_01.models.ProviderOperation] + """ + super().__init__(**kwargs) + self.name = name + self.display_name = display_name + self.operations = operations + + +class RoleAssignment(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Role Assignments. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role assignment ID. + :vartype id: str + :ivar name: The role assignment name. + :vartype name: str + :ivar type: The role assignment type. + :vartype type: str + :ivar scope: The role assignment scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or ~azure.mgmt.authorization.v2022_04_01.models.PrincipalType + :ivar description: Description of role assignment. + :vartype description: str + :ivar condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :vartype condition: str + :ivar condition_version: Version of the condition. Currently the only accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: Time it was created. + :vartype created_on: ~datetime.datetime + :ivar updated_on: Time it was updated. + :vartype updated_on: ~datetime.datetime + :ivar created_by: Id of the user who created the assignment. + :vartype created_by: str + :ivar updated_by: Id of the user who updated the assignment. + :vartype updated_by: str + :ivar delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :vartype delegated_managed_identity_resource_id: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "scope": {"readonly": True}, + "created_on": {"readonly": True}, + "updated_on": {"readonly": True}, + "created_by": {"readonly": True}, + "updated_by": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "updated_on": {"key": "properties.updatedOn", "type": "iso-8601"}, + "created_by": {"key": "properties.createdBy", "type": "str"}, + "updated_by": {"key": "properties.updatedBy", "type": "str"}, + "delegated_managed_identity_resource_id": { + "key": "properties.delegatedManagedIdentityResourceId", + "type": "str", + }, + } + + def __init__( + self, + *, + role_definition_id: Optional[str] = None, + principal_id: Optional[str] = None, + principal_type: Union[str, "_models.PrincipalType"] = "User", + description: Optional[str] = None, + condition: Optional[str] = None, + condition_version: Optional[str] = None, + delegated_managed_identity_resource_id: Optional[str] = None, + **kwargs + ): + """ + :keyword role_definition_id: The role definition ID. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or ~azure.mgmt.authorization.v2022_04_01.models.PrincipalType + :keyword description: Description of role assignment. + :paramtype description: str + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently the only accepted value is + '2.0'. + :paramtype condition_version: str + :keyword delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :paramtype delegated_managed_identity_resource_id: str + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.scope = None + self.role_definition_id = role_definition_id + self.principal_id = principal_id + self.principal_type = principal_type + self.description = description + self.condition = condition + self.condition_version = condition_version + self.created_on = None + self.updated_on = None + self.created_by = None + self.updated_by = None + self.delegated_managed_identity_resource_id = delegated_managed_identity_resource_id + + +class RoleAssignmentCreateParameters(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Role assignment create parameters. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar scope: The role assignment scope. + :vartype scope: str + :ivar role_definition_id: The role definition ID. Required. + :vartype role_definition_id: str + :ivar principal_id: The principal ID. Required. + :vartype principal_id: str + :ivar principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :vartype principal_type: str or ~azure.mgmt.authorization.v2022_04_01.models.PrincipalType + :ivar description: Description of role assignment. + :vartype description: str + :ivar condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :vartype condition: str + :ivar condition_version: Version of the condition. Currently the only accepted value is '2.0'. + :vartype condition_version: str + :ivar created_on: Time it was created. + :vartype created_on: ~datetime.datetime + :ivar updated_on: Time it was updated. + :vartype updated_on: ~datetime.datetime + :ivar created_by: Id of the user who created the assignment. + :vartype created_by: str + :ivar updated_by: Id of the user who updated the assignment. + :vartype updated_by: str + :ivar delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :vartype delegated_managed_identity_resource_id: str + """ + + _validation = { + "scope": {"readonly": True}, + "role_definition_id": {"required": True}, + "principal_id": {"required": True}, + "created_on": {"readonly": True}, + "updated_on": {"readonly": True}, + "created_by": {"readonly": True}, + "updated_by": {"readonly": True}, + } + + _attribute_map = { + "scope": {"key": "properties.scope", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "condition": {"key": "properties.condition", "type": "str"}, + "condition_version": {"key": "properties.conditionVersion", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "updated_on": {"key": "properties.updatedOn", "type": "iso-8601"}, + "created_by": {"key": "properties.createdBy", "type": "str"}, + "updated_by": {"key": "properties.updatedBy", "type": "str"}, + "delegated_managed_identity_resource_id": { + "key": "properties.delegatedManagedIdentityResourceId", + "type": "str", + }, + } + + def __init__( + self, + *, + role_definition_id: str, + principal_id: str, + principal_type: Union[str, "_models.PrincipalType"] = "User", + description: Optional[str] = None, + condition: Optional[str] = None, + condition_version: Optional[str] = None, + delegated_managed_identity_resource_id: Optional[str] = None, + **kwargs + ): + """ + :keyword role_definition_id: The role definition ID. Required. + :paramtype role_definition_id: str + :keyword principal_id: The principal ID. Required. + :paramtype principal_id: str + :keyword principal_type: The principal type of the assigned principal ID. Known values are: + "User", "Group", "ServicePrincipal", "ForeignGroup", and "Device". + :paramtype principal_type: str or ~azure.mgmt.authorization.v2022_04_01.models.PrincipalType + :keyword description: Description of role assignment. + :paramtype description: str + :keyword condition: The conditions on the role assignment. This limits the resources it can be + assigned to. e.g.: + @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] + StringEqualsIgnoreCase 'foo_storage_container'. + :paramtype condition: str + :keyword condition_version: Version of the condition. Currently the only accepted value is + '2.0'. + :paramtype condition_version: str + :keyword delegated_managed_identity_resource_id: Id of the delegated managed identity resource. + :paramtype delegated_managed_identity_resource_id: str + """ + super().__init__(**kwargs) + self.scope = None + self.role_definition_id = role_definition_id + self.principal_id = principal_id + self.principal_type = principal_type + self.description = description + self.condition = condition + self.condition_version = condition_version + self.created_on = None + self.updated_on = None + self.created_by = None + self.updated_by = None + self.delegated_managed_identity_resource_id = delegated_managed_identity_resource_id + + +class RoleAssignmentFilter(_serialization.Model): + """Role Assignments filter. + + :ivar principal_id: Returns role assignment of the specific principal. + :vartype principal_id: str + """ + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + } + + def __init__(self, *, principal_id: Optional[str] = None, **kwargs): + """ + :keyword principal_id: Returns role assignment of the specific principal. + :paramtype principal_id: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + + +class RoleAssignmentListResult(_serialization.Model): + """Role assignment list operation result. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Role assignment list. + :vartype value: list[~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment] + :ivar next_link: The skipToken to use for getting the next set of results. + :vartype next_link: str + """ + + _validation = { + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RoleAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[List["_models.RoleAssignment"]] = None, **kwargs): + """ + :keyword value: Role assignment list. + :paramtype value: list[~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment] + """ + super().__init__(**kwargs) + self.value = value + self.next_link = None + + +class RoleDefinition(_serialization.Model): + """Role definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role definition ID. + :vartype id: str + :ivar name: The role definition name. + :vartype name: str + :ivar type: The role definition type. + :vartype type: str + :ivar role_name: The role name. + :vartype role_name: str + :ivar description: The role definition description. + :vartype description: str + :ivar role_type: The role type. + :vartype role_type: str + :ivar permissions: Role definition permissions. + :vartype permissions: list[~azure.mgmt.authorization.v2022_04_01.models.Permission] + :ivar assignable_scopes: Role definition assignable scopes. + :vartype assignable_scopes: list[str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "role_name": {"key": "properties.roleName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "role_type": {"key": "properties.type", "type": "str"}, + "permissions": {"key": "properties.permissions", "type": "[Permission]"}, + "assignable_scopes": {"key": "properties.assignableScopes", "type": "[str]"}, + } + + def __init__( + self, + *, + role_name: Optional[str] = None, + description: Optional[str] = None, + role_type: Optional[str] = None, + permissions: Optional[List["_models.Permission"]] = None, + assignable_scopes: Optional[List[str]] = None, + **kwargs + ): + """ + :keyword role_name: The role name. + :paramtype role_name: str + :keyword description: The role definition description. + :paramtype description: str + :keyword role_type: The role type. + :paramtype role_type: str + :keyword permissions: Role definition permissions. + :paramtype permissions: list[~azure.mgmt.authorization.v2022_04_01.models.Permission] + :keyword assignable_scopes: Role definition assignable scopes. + :paramtype assignable_scopes: list[str] + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.role_name = role_name + self.description = description + self.role_type = role_type + self.permissions = permissions + self.assignable_scopes = assignable_scopes + + +class RoleDefinitionFilter(_serialization.Model): + """Role Definitions filter. + + :ivar role_name: Returns role definition with the specific name. + :vartype role_name: str + :ivar type: Returns role definition with the specific type. + :vartype type: str + """ + + _attribute_map = { + "role_name": {"key": "roleName", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, role_name: Optional[str] = None, type: Optional[str] = None, **kwargs): + """ + :keyword role_name: Returns role definition with the specific name. + :paramtype role_name: str + :keyword type: Returns role definition with the specific type. + :paramtype type: str + """ + super().__init__(**kwargs) + self.role_name = role_name + self.type = type + + +class RoleDefinitionListResult(_serialization.Model): + """Role definition list operation result. + + :ivar value: Role definition list. + :vartype value: list[~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[RoleDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.RoleDefinition"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: Role definition list. + :paramtype value: list[~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RoleManagementPolicyRule(_serialization.Model): + """The role management policy rule. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + RoleManagementPolicyApprovalRule, RoleManagementPolicyAuthenticationContextRule, + RoleManagementPolicyEnablementRule, RoleManagementPolicyExpirationRule, + RoleManagementPolicyNotificationRule + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + } + + _subtype_map = { + "rule_type": { + "RoleManagementPolicyApprovalRule": "RoleManagementPolicyApprovalRule", + "RoleManagementPolicyAuthenticationContextRule": "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule": "RoleManagementPolicyEnablementRule", + "RoleManagementPolicyExpirationRule": "RoleManagementPolicyExpirationRule", + "RoleManagementPolicyNotificationRule": "RoleManagementPolicyNotificationRule", + } + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + """ + super().__init__(**kwargs) + self.id = id + self.rule_type = None # type: Optional[str] + self.target = target + + +class RoleManagementPolicyApprovalRule(RoleManagementPolicyRule): + """The role management policy approval rule. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + :ivar setting: The approval setting. + :vartype setting: ~azure.mgmt.authorization.v2022_04_01.models.ApprovalSettings + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "setting": {"key": "setting", "type": "ApprovalSettings"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + setting: Optional["_models.ApprovalSettings"] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + :keyword setting: The approval setting. + :paramtype setting: ~azure.mgmt.authorization.v2022_04_01.models.ApprovalSettings + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyApprovalRule" # type: str + self.setting = setting + + +class RoleManagementPolicyAuthenticationContextRule(RoleManagementPolicyRule): + """The role management policy authentication context rule. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + :ivar is_enabled: The value indicating if rule is enabled. + :vartype is_enabled: bool + :ivar claim_value: The claim value. + :vartype claim_value: str + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "is_enabled": {"key": "isEnabled", "type": "bool"}, + "claim_value": {"key": "claimValue", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + is_enabled: Optional[bool] = None, + claim_value: Optional[str] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + :keyword is_enabled: The value indicating if rule is enabled. + :paramtype is_enabled: bool + :keyword claim_value: The claim value. + :paramtype claim_value: str + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyAuthenticationContextRule" # type: str + self.is_enabled = is_enabled + self.claim_value = claim_value + + +class RoleManagementPolicyEnablementRule(RoleManagementPolicyRule): + """The role management policy enablement rule. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + :ivar enabled_rules: The list of enabled rules. + :vartype enabled_rules: list[str or + ~azure.mgmt.authorization.v2022_04_01.models.EnablementRules] + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "enabled_rules": {"key": "enabledRules", "type": "[str]"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + enabled_rules: Optional[List[Union[str, "_models.EnablementRules"]]] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + :keyword enabled_rules: The list of enabled rules. + :paramtype enabled_rules: list[str or + ~azure.mgmt.authorization.v2022_04_01.models.EnablementRules] + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyEnablementRule" # type: str + self.enabled_rules = enabled_rules + + +class RoleManagementPolicyExpirationRule(RoleManagementPolicyRule): + """The role management policy expiration rule. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + :ivar is_expiration_required: The value indicating whether expiration is required. + :vartype is_expiration_required: bool + :ivar maximum_duration: The maximum duration of expiration in timespan. + :vartype maximum_duration: str + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "is_expiration_required": {"key": "isExpirationRequired", "type": "bool"}, + "maximum_duration": {"key": "maximumDuration", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + is_expiration_required: Optional[bool] = None, + maximum_duration: Optional[str] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + :keyword is_expiration_required: The value indicating whether expiration is required. + :paramtype is_expiration_required: bool + :keyword maximum_duration: The maximum duration of expiration in timespan. + :paramtype maximum_duration: str + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyExpirationRule" # type: str + self.is_expiration_required = is_expiration_required + self.maximum_duration = maximum_duration + + +class RoleManagementPolicyNotificationRule(RoleManagementPolicyRule): + """The role management policy notification rule. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The id of the rule. + :vartype id: str + :ivar rule_type: The type of rule. Required. Known values are: + "RoleManagementPolicyApprovalRule", "RoleManagementPolicyAuthenticationContextRule", + "RoleManagementPolicyEnablementRule", "RoleManagementPolicyExpirationRule", and + "RoleManagementPolicyNotificationRule". + :vartype rule_type: str or + ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleType + :ivar target: The target of the current rule. + :vartype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + :ivar notification_type: The type of notification. "Email" + :vartype notification_type: str or + ~azure.mgmt.authorization.v2022_04_01.models.NotificationDeliveryMechanism + :ivar notification_level: The notification level. Known values are: "None", "Critical", and + "All". + :vartype notification_level: str or + ~azure.mgmt.authorization.v2022_04_01.models.NotificationLevel + :ivar recipient_type: The recipient type. Known values are: "Requestor", "Approver", and + "Admin". + :vartype recipient_type: str or ~azure.mgmt.authorization.v2022_04_01.models.RecipientType + :ivar notification_recipients: The list of notification recipients. + :vartype notification_recipients: list[str] + :ivar is_default_recipients_enabled: Determines if the notification will be sent to the + recipient type specified in the policy rule. + :vartype is_default_recipients_enabled: bool + """ + + _validation = { + "rule_type": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "rule_type": {"key": "ruleType", "type": "str"}, + "target": {"key": "target", "type": "RoleManagementPolicyRuleTarget"}, + "notification_type": {"key": "notificationType", "type": "str"}, + "notification_level": {"key": "notificationLevel", "type": "str"}, + "recipient_type": {"key": "recipientType", "type": "str"}, + "notification_recipients": {"key": "notificationRecipients", "type": "[str]"}, + "is_default_recipients_enabled": {"key": "isDefaultRecipientsEnabled", "type": "bool"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + target: Optional["_models.RoleManagementPolicyRuleTarget"] = None, + notification_type: Optional[Union[str, "_models.NotificationDeliveryMechanism"]] = None, + notification_level: Optional[Union[str, "_models.NotificationLevel"]] = None, + recipient_type: Optional[Union[str, "_models.RecipientType"]] = None, + notification_recipients: Optional[List[str]] = None, + is_default_recipients_enabled: Optional[bool] = None, + **kwargs + ): + """ + :keyword id: The id of the rule. + :paramtype id: str + :keyword target: The target of the current rule. + :paramtype target: ~azure.mgmt.authorization.v2022_04_01.models.RoleManagementPolicyRuleTarget + :keyword notification_type: The type of notification. "Email" + :paramtype notification_type: str or + ~azure.mgmt.authorization.v2022_04_01.models.NotificationDeliveryMechanism + :keyword notification_level: The notification level. Known values are: "None", "Critical", and + "All". + :paramtype notification_level: str or + ~azure.mgmt.authorization.v2022_04_01.models.NotificationLevel + :keyword recipient_type: The recipient type. Known values are: "Requestor", "Approver", and + "Admin". + :paramtype recipient_type: str or ~azure.mgmt.authorization.v2022_04_01.models.RecipientType + :keyword notification_recipients: The list of notification recipients. + :paramtype notification_recipients: list[str] + :keyword is_default_recipients_enabled: Determines if the notification will be sent to the + recipient type specified in the policy rule. + :paramtype is_default_recipients_enabled: bool + """ + super().__init__(id=id, target=target, **kwargs) + self.rule_type = "RoleManagementPolicyNotificationRule" # type: str + self.notification_type = notification_type + self.notification_level = notification_level + self.recipient_type = recipient_type + self.notification_recipients = notification_recipients + self.is_default_recipients_enabled = is_default_recipients_enabled + + +class RoleManagementPolicyRuleTarget(_serialization.Model): + """The role management policy rule target. + + :ivar caller: The caller of the setting. + :vartype caller: str + :ivar operations: The type of operation. + :vartype operations: list[str] + :ivar level: The assignment level to which rule is applied. + :vartype level: str + :ivar target_objects: The list of target objects. + :vartype target_objects: list[str] + :ivar inheritable_settings: The list of inheritable settings. + :vartype inheritable_settings: list[str] + :ivar enforced_settings: The list of enforced settings. + :vartype enforced_settings: list[str] + """ + + _attribute_map = { + "caller": {"key": "caller", "type": "str"}, + "operations": {"key": "operations", "type": "[str]"}, + "level": {"key": "level", "type": "str"}, + "target_objects": {"key": "targetObjects", "type": "[str]"}, + "inheritable_settings": {"key": "inheritableSettings", "type": "[str]"}, + "enforced_settings": {"key": "enforcedSettings", "type": "[str]"}, + } + + def __init__( + self, + *, + caller: Optional[str] = None, + operations: Optional[List[str]] = None, + level: Optional[str] = None, + target_objects: Optional[List[str]] = None, + inheritable_settings: Optional[List[str]] = None, + enforced_settings: Optional[List[str]] = None, + **kwargs + ): + """ + :keyword caller: The caller of the setting. + :paramtype caller: str + :keyword operations: The type of operation. + :paramtype operations: list[str] + :keyword level: The assignment level to which rule is applied. + :paramtype level: str + :keyword target_objects: The list of target objects. + :paramtype target_objects: list[str] + :keyword inheritable_settings: The list of inheritable settings. + :paramtype inheritable_settings: list[str] + :keyword enforced_settings: The list of enforced settings. + :paramtype enforced_settings: list[str] + """ + super().__init__(**kwargs) + self.caller = caller + self.operations = operations + self.level = level + self.target_objects = target_objects + self.inheritable_settings = inheritable_settings + self.enforced_settings = enforced_settings + + +class UserSet(_serialization.Model): + """The detail of a user. + + :ivar user_type: The type of user. Known values are: "User" and "Group". + :vartype user_type: str or ~azure.mgmt.authorization.v2022_04_01.models.UserType + :ivar is_backup: The value indicating whether the user is a backup fallback approver. + :vartype is_backup: bool + :ivar id: The object id of the user. + :vartype id: str + :ivar description: The description of the user. + :vartype description: str + """ + + _attribute_map = { + "user_type": {"key": "userType", "type": "str"}, + "is_backup": {"key": "isBackup", "type": "bool"}, + "id": {"key": "id", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__( + self, + *, + user_type: Optional[Union[str, "_models.UserType"]] = None, + is_backup: Optional[bool] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + description: Optional[str] = None, + **kwargs + ): + """ + :keyword user_type: The type of user. Known values are: "User" and "Group". + :paramtype user_type: str or ~azure.mgmt.authorization.v2022_04_01.models.UserType + :keyword is_backup: The value indicating whether the user is a backup fallback approver. + :paramtype is_backup: bool + :keyword id: The object id of the user. + :paramtype id: str + :keyword description: The description of the user. + :paramtype description: str + """ + super().__init__(**kwargs) + self.user_type = user_type + self.is_backup = is_backup + self.id = id + self.description = description + + +class ValidationResponse(_serialization.Model): + """Validation response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar is_valid: Whether or not validation succeeded. + :vartype is_valid: bool + :ivar error_info: Failed validation result details. + :vartype error_info: ~azure.mgmt.authorization.v2022_04_01.models.ValidationResponseErrorInfo + """ + + _validation = { + "is_valid": {"readonly": True}, + } + + _attribute_map = { + "is_valid": {"key": "isValid", "type": "bool"}, + "error_info": {"key": "errorInfo", "type": "ValidationResponseErrorInfo"}, + } + + def __init__(self, *, error_info: Optional["_models.ValidationResponseErrorInfo"] = None, **kwargs): + """ + :keyword error_info: Failed validation result details. + :paramtype error_info: ~azure.mgmt.authorization.v2022_04_01.models.ValidationResponseErrorInfo + """ + super().__init__(**kwargs) + self.is_valid = None + self.error_info = error_info + + +class ValidationResponseErrorInfo(_serialization.Model): + """Failed validation result details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: Error code indicating why validation failed. + :vartype code: str + :ivar message: Message indicating why validation failed. + :vartype message: str + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/__init__.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/__init__.py new file mode 100644 index 00000000000..bbb62cee061 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._deny_assignments_operations import DenyAssignmentsOperations +from ._provider_operations_metadata_operations import ProviderOperationsMetadataOperations +from ._role_assignments_operations import RoleAssignmentsOperations +from ._permissions_operations import PermissionsOperations +from ._role_definitions_operations import RoleDefinitionsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DenyAssignmentsOperations", + "ProviderOperationsMetadataOperations", + "RoleAssignmentsOperations", + "PermissionsOperations", + "RoleDefinitionsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_deny_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_deny_assignments_operations.py new file mode 100644 index 00000000000..a1808f1c6d9 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_deny_assignments_operations.py @@ -0,0 +1,737 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/denyAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceProviderNamespace": _SERIALIZER.url( + "resource_provider_namespace", resource_provider_namespace, "str", skip_quote=True + ), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_group_request( + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/denyAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/denyAssignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, deny_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "denyAssignmentId": _SERIALIZER.url("deny_assignment_id", deny_assignment_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(deny_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{denyAssignmentId}") + path_format_arguments = { + "denyAssignmentId": _SERIALIZER.url("deny_assignment_id", deny_assignment_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/denyAssignments") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DenyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2022_04_01.AuthorizationManagementClient`'s + :attr:`deny_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.DenyAssignment"]: + """Gets deny assignments for a resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource. Required. + :type resource_type: str + :param resource_name: The name of the resource to get deny assignments for. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny + assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny + assignments by name at specified scope. Use $filter=principalId eq '{id}' to return all deny + assignments at, above and below the scope for the specified principal. Use + $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, above and below the + scope for the specified principal. This filter is different from the principalId filter as it + returns not only those deny assignments that contain the specified principal is the Principals + list but also those deny assignments that contain the specified principal is the + ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny + assignment name and description properties are returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.DenyAssignment"]: + """Gets deny assignments for a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny + assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny + assignments by name at specified scope. Use $filter=principalId eq '{id}' to return all deny + assignments at, above and below the scope for the specified principal. Use + $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, above and below the + scope for the specified principal. This filter is different from the principalId filter as it + returns not only those deny assignments that contain the specified principal is the Principals + list but also those deny assignments that contain the specified principal is the + ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny + assignment name and description properties are returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.DenyAssignment"]: + """Gets all deny assignments for the subscription. + + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny + assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny + assignments by name at specified scope. Use $filter=principalId eq '{id}' to return all deny + assignments at, above and below the scope for the specified principal. Use + $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, above and below the + scope for the specified principal. This filter is different from the principalId filter as it + returns not only those deny assignments that contain the specified principal is the Principals + list but also those deny assignments that contain the specified principal is the + ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny + assignment name and description properties are returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore + + @distributed_trace + def get(self, scope: str, deny_assignment_id: str, **kwargs: Any) -> _models.DenyAssignment: + """Get the specified deny assignment. + + :param scope: The scope of the deny assignment. Required. + :type scope: str + :param deny_assignment_id: The ID of the deny assignment to get. Required. + :type deny_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DenyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignment] + + request = build_get_request( + scope=scope, + deny_assignment_id=deny_assignment_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DenyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId}"} # type: ignore + + @distributed_trace + def get_by_id(self, deny_assignment_id: str, **kwargs: Any) -> _models.DenyAssignment: + """Gets a deny assignment by ID. + + :param deny_assignment_id: The fully qualified deny assignment ID. For example, use the format, + /subscriptions/{guid}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} for + subscription level deny assignments, or + /providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} for tenant level deny + assignments. Required. + :type deny_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DenyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignment] + + request = build_get_by_id_request( + deny_assignment_id=deny_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DenyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{denyAssignmentId}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.DenyAssignment"]: + """Gets deny assignments for a scope. + + :param scope: The scope of the deny assignments. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all deny + assignments at or above the scope. Use $filter=denyAssignmentName eq '{name}' to search deny + assignments by name at specified scope. Use $filter=principalId eq '{id}' to return all deny + assignments at, above and below the scope for the specified principal. Use + $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, above and below the + scope for the specified principal. This filter is different from the principalId filter as it + returns not only those deny assignments that contain the specified principal is the Principals + list but also those deny assignments that contain the specified principal is the + ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is used, only the deny + assignment name and description properties are returned. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DenyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.DenyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DenyAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DenyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/denyAssignments"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_patch.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_permissions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_permissions_operations.py new file mode 100644 index 00000000000..1b862e408a1 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_permissions_operations.py @@ -0,0 +1,304 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceProviderNamespace": _SERIALIZER.url( + "resource_provider_namespace", resource_provider_namespace, "str", skip_quote=True + ), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PermissionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2022_04_01.AuthorizationManagementClient`'s + :attr:`permissions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_for_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Permission"]: + """Gets all permissions the caller has for a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PermissionGetResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions"} # type: ignore + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + **kwargs: Any + ) -> Iterable["_models.Permission"]: + """Gets all permissions the caller has for a resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource. Required. + :type resource_type: str + :param resource_name: The name of the resource to get the permissions for. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Permission or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.Permission] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PermissionGetResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PermissionGetResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_provider_operations_metadata_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_provider_operations_metadata_operations.py new file mode 100644 index 00000000000..8f10fe22401 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_provider_operations_metadata_operations.py @@ -0,0 +1,244 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(resource_provider_namespace: str, *, expand: str = "resourceTypes", **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}" + ) + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url( + "resource_provider_namespace", resource_provider_namespace, "str", skip_quote=True + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(*, expand: str = "resourceTypes", **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/providerOperations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ProviderOperationsMetadataOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2022_04_01.AuthorizationManagementClient`'s + :attr:`provider_operations_metadata` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_provider_namespace: str, expand: str = "resourceTypes", **kwargs: Any + ) -> _models.ProviderOperationsMetadata: + """Gets provider operations metadata for the specified resource provider. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". + :type expand: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ProviderOperationsMetadata or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.ProviderOperationsMetadata + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadata] + + request = build_get_request( + resource_provider_namespace=resource_provider_namespace, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ProviderOperationsMetadata", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}"} # type: ignore + + @distributed_trace + def list(self, expand: str = "resourceTypes", **kwargs: Any) -> Iterable["_models.ProviderOperationsMetadata"]: + """Gets provider operations metadata for all resource providers. + + :param expand: Specifies whether to expand the values. Default value is "resourceTypes". + :type expand: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ProviderOperationsMetadata or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.ProviderOperationsMetadata] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProviderOperationsMetadataListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ProviderOperationsMetadataListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/providerOperations"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_role_assignments_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_role_assignments_operations.py new file mode 100644 index 00000000000..bb3d960b87b --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_role_assignments_operations.py @@ -0,0 +1,1318 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_subscription_request( + subscription_id: str, *, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_group_request( + resource_group_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceProviderNamespace": _SERIALIZER.url( + "resource_provider_namespace", resource_provider_namespace, "str", skip_quote=True + ), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + scope: str, role_assignment_name: str, *, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(scope: str, role_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + scope: str, role_assignment_name: str, *, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleAssignmentName": _SERIALIZER.url("role_assignment_name", role_assignment_name, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_scope_request( + scope: str, + *, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleAssignments") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + if skip_token is not None: + _params["$skipToken"] = _SERIALIZER.query("skip_token", skip_token, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(role_assignment_id: str, *, tenant_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleAssignmentId}") + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_by_id_request(role_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleAssignmentId}") + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_id_request( + role_assignment_id: str, *, tenant_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleAssignmentId}") + path_format_arguments = { + "roleAssignmentId": _SERIALIZER.url("role_assignment_id", role_assignment_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tenant_id is not None: + _params["tenantId"] = _SERIALIZER.query("tenant_id", tenant_id, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2022_04_01.AuthorizationManagementClient`'s + :attr:`role_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_for_subscription( + self, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: + """List all role assignments that apply to a subscription. + + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignments at or above the scope. Use $filter=principalId eq {id} to return all role + assignments at, above or below the scope for the specified principal. Default value is None. + :type filter: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_subscription_request( + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: + """List all role assignments that apply to a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignments at or above the scope. Use $filter=principalId eq {id} to return all role + assignments at, above or below the scope for the specified principal. Default value is None. + :type filter: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: + """List all role assignments that apply to a resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param resource_type: The resource type name. For example the type name of a web app is 'sites' + (from Microsoft.Web/sites). Required. + :type resource_type: str + :param resource_name: The resource name. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignments at or above the scope. Use $filter=principalId eq {id} to return all role + assignments at, above or below the scope for the specified principal. Default value is None. + :type filter: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace + def get( + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> _models.RoleAssignment: + """Get a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @overload + def create( + self, + scope: str, + role_assignment_name: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + role_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + role_assignment_name: str, + parameters: Union[_models.RoleAssignmentCreateParameters, IO], + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignmentCreateParameters + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_request( + scope=scope, + role_assignment_name=role_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace + def delete( + self, scope: str, role_assignment_name: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: + """Delete a role assignment by scope and name. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param role_assignment_name: The name of the role assignment. It can be any valid GUID. + Required. + :type role_assignment_name: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_request( + scope=scope, + role_assignment_name=role_assignment_name, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"} # type: ignore + + @distributed_trace + def list_for_scope( + self, + scope: str, + filter: Optional[str] = None, + tenant_id: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RoleAssignment"]: + """List all role assignments that apply to a scope. + + :param scope: The scope of the operation or resource. Valid scopes are: subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignments at or above the scope. Use $filter=principalId eq {id} to return all role + assignments at, above or below the scope for the specified principal. Default value is None. + :type filter: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :param skip_token: The skipToken to apply on the operation. Use $skipToken={skiptoken} to + return paged role assignments following the skipToken passed. Only supported on provider level + calls. Default value is None. + :type skip_token: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignmentListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_for_scope_request( + scope=scope, + filter=filter, + tenant_id=tenant_id, + skip_token=skip_token, + api_version=api_version, + template_url=self.list_for_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleAssignments"} # type: ignore + + @distributed_trace + def get_by_id( + self, role_assignment_id: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> _models.RoleAssignment: + """Get a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + request = build_get_by_id_request( + role_assignment_id=role_assignment_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @overload + def create_by_id( + self, + role_assignment_id: str, + parameters: _models.RoleAssignmentCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignmentCreateParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_by_id( + self, role_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_by_id( + self, role_assignment_id: str, parameters: Union[_models.RoleAssignmentCreateParameters, IO], **kwargs: Any + ) -> _models.RoleAssignment: + """Create or update a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param parameters: Parameters for the role assignment. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignmentCreateParameters + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleAssignment] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RoleAssignmentCreateParameters") + + request = build_create_by_id_request( + role_assignment_id=role_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore + + @distributed_trace + def delete_by_id( + self, role_assignment_id: str, tenant_id: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.RoleAssignment]: + """Delete a role assignment by ID. + + :param role_assignment_id: The fully qualified ID of the role assignment including scope, + resource name, and resource type. Format: + /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: + /subscriptions/:code:``/resourcegroups/:code:``/providers/Microsoft.Authorization/roleAssignments/:code:``. + Required. + :type role_assignment_id: str + :param tenant_id: Tenant ID for cross-tenant request. Default value is None. + :type tenant_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleAssignment]] + + request = build_delete_by_id_request( + role_assignment_id=role_assignment_id, + tenant_id=tenant_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("RoleAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete_by_id.metadata = {"url": "/{roleAssignmentId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_role_definitions_operations.py b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_role_definitions_operations.py new file mode 100644 index 00000000000..6c9b7251799 --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/operations/_role_definitions_operations.py @@ -0,0 +1,573 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_delete_request(scope: str, role_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, role_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(scope: str, role_definition_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "roleDefinitionId": _SERIALIZER.url("role_definition_id", role_definition_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/roleDefinitions") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(role_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{roleId}") + path_format_arguments = { + "roleId": _SERIALIZER.url("role_id", role_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RoleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.authorization.v2022_04_01.AuthorizationManagementClient`'s + :attr:`role_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete(self, scope: str, role_definition_id: str, **kwargs: Any) -> Optional[_models.RoleDefinition]: + """Deletes a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition to delete. Required. + :type role_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or None or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RoleDefinition]] + + request = build_delete_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("RoleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace + def get(self, scope: str, role_definition_id: str, **kwargs: Any) -> _models.RoleDefinition: + """Get role definition by name (GUID). + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + request = build_get_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @overload + def create_or_update( + self, + scope: str, + role_definition_id: str, + role_definition: _models.RoleDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Required. + :type role_definition: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + scope: str, + role_definition_id: str, + role_definition: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Required. + :type role_definition: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, scope: str, role_definition_id: str, role_definition: Union[_models.RoleDefinition, IO], **kwargs: Any + ) -> _models.RoleDefinition: + """Creates or updates a role definition. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param role_definition_id: The ID of the role definition. Required. + :type role_definition_id: str + :param role_definition: The values for the role definition. Is either a model type or a IO + type. Required. + :type role_definition: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(role_definition, (IO, bytes)): + _content = role_definition + else: + _json = self._serialize.body(role_definition, "RoleDefinition") + + request = build_create_or_update_request( + scope=scope, + role_definition_id=role_definition_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}"} # type: ignore + + @distributed_trace + def list(self, scope: str, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.RoleDefinition"]: + """Get all role definitions that are applicable at scope and above. + + :param scope: The scope of the role definition. Required. + :type scope: str + :param filter: The filter to apply on the operation. Use atScopeAndBelow filter to search below + the given scope as well. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleDefinition or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinitionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RoleDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/roleDefinitions"} # type: ignore + + @distributed_trace + def get_by_id(self, role_id: str, **kwargs: Any) -> _models.RoleDefinition: + """Gets a role definition by ID. + + :param role_id: The fully qualified role definition ID. Use the format, + /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for + subscription level role definitions, or + /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for tenant level role + definitions. Required. + :type role_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleDefinition or the result of cls(response) + :rtype: ~azure.mgmt.authorization.v2022_04_01.models.RoleDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RoleDefinition] + + request = build_get_by_id_request( + role_id=role_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RoleDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{roleId}"} # type: ignore diff --git a/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/py.typed b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/py.typed new file mode 100644 index 00000000000..e5aff4f83af --- /dev/null +++ b/sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2022_04_01/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/authorization/azure-mgmt-authorization/tests/recordings/test_cli_mgmt_authorization.pyTestMgmtAuthorizationtest_list_by_resource.json b/sdk/authorization/azure-mgmt-authorization/tests/recordings/test_cli_mgmt_authorization.pyTestMgmtAuthorizationtest_list_by_resource.json index 4cbd8880990..cbf2c5cd229 100644 --- a/sdk/authorization/azure-mgmt-authorization/tests/recordings/test_cli_mgmt_authorization.pyTestMgmtAuthorizationtest_list_by_resource.json +++ b/sdk/authorization/azure-mgmt-authorization/tests/recordings/test_cli_mgmt_authorization.pyTestMgmtAuthorizationtest_list_by_resource.json @@ -7,7 +7,7 @@ "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive", - "User-Agent": "azsdk-python-identity/1.9.0b2 Python/3.6.2 (Windows-10-10.0.19041-SP0)" + "User-Agent": "azsdk-python-identity/1.11.0 Python/3.8.14 (Linux-5.15.0-1020-azure-x86_64-with-glibc2.2.5) VSTS_0fb41ef4-5012-48a9-bf39-4ee3de03ee35_build_2500_0" }, "RequestBody": null, "StatusCode": 200, @@ -17,13 +17,13 @@ "Cache-Control": "max-age=86400, private", "Content-Length": "1753", "Content-Type": "application/json; charset=utf-8", - "Date": "Wed, 09 Mar 2022 06:51:39 GMT", + "Date": "Tue, 11 Oct 2022 02:41:41 GMT", "P3P": "CP=\u0022DSP CUR OTPi IND OTRi ONL FIN\u0022", "Set-Cookie": "[set-cookie;]", "Strict-Transport-Security": "max-age=31536000; includeSubDomains", "X-Content-Type-Options": "nosniff", - "x-ms-ests-server": "2.1.12529.17 - SCUS ProdSlices", - "x-ms-request-id": "164ac044-db41-487c-9432-0e95a70bf700" + "x-ms-ests-server": "2.1.13871.7 - NCUS ProdSlices", + "X-XSS-Protection": "0" }, "ResponseBody": { "token_endpoint": "https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token", @@ -86,7 +86,7 @@ "email" ], "kerberos_endpoint": "https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/kerberos", - "tenant_region_scope": "NA", + "tenant_region_scope": "WW", "cloud_instance_name": "microsoftonline.com", "cloud_graph_host_name": "graph.windows.net", "msgraph_host": "graph.microsoft.com", @@ -101,7 +101,7 @@ "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive", "Cookie": "cookie;", - "User-Agent": "azsdk-python-identity/1.9.0b2 Python/3.6.2 (Windows-10-10.0.19041-SP0)" + "User-Agent": "azsdk-python-identity/1.11.0 Python/3.8.14 (Linux-5.15.0-1020-azure-x86_64-with-glibc2.2.5) VSTS_0fb41ef4-5012-48a9-bf39-4ee3de03ee35_build_2500_0" }, "RequestBody": null, "StatusCode": 200, @@ -111,13 +111,13 @@ "Cache-Control": "max-age=86400, private", "Content-Length": "945", "Content-Type": "application/json; charset=utf-8", - "Date": "Wed, 09 Mar 2022 06:51:40 GMT", + "Date": "Tue, 11 Oct 2022 02:41:41 GMT", "P3P": "CP=\u0022DSP CUR OTPi IND OTRi ONL FIN\u0022", "Set-Cookie": "[set-cookie;]", "Strict-Transport-Security": "max-age=31536000; includeSubDomains", "X-Content-Type-Options": "nosniff", - "x-ms-ests-server": "2.1.12559.5 - SEASLR1 ProdSlices", - "x-ms-request-id": "fcb8cc6d-c865-4e5d-b3f3-f11469580400" + "x-ms-ests-server": "2.1.13845.9 - SCUS ProdSlices", + "X-XSS-Protection": "0" }, "ResponseBody": { "tenant_discovery_endpoint": "https://login.microsoftonline.com/common/.well-known/openid-configuration", @@ -172,28 +172,28 @@ "RequestHeaders": { "Accept": "application/json", "Accept-Encoding": "gzip, deflate", - "client-request-id": "865a2fb0-9b9e-4e09-997f-02c6682c30e0", + "client-request-id": "95ddc384-b740-4477-a840-0bf5527bdf88", "Connection": "keep-alive", - "Content-Length": "291", + "Content-Length": "288", "Content-Type": "application/x-www-form-urlencoded", "Cookie": "cookie;", - "User-Agent": "azsdk-python-identity/1.9.0b2 Python/3.6.2 (Windows-10-10.0.19041-SP0)", + "User-Agent": "azsdk-python-identity/1.11.0 Python/3.8.14 (Linux-5.15.0-1020-azure-x86_64-with-glibc2.2.5) VSTS_0fb41ef4-5012-48a9-bf39-4ee3de03ee35_build_2500_0", "x-client-cpu": "x64", "x-client-current-telemetry": "4|730,0|", "x-client-last-telemetry": "4|0|||", - "x-client-os": "win32", + "x-client-os": "linux", "x-client-sku": "MSAL.Python", - "x-client-ver": "1.17.0", + "x-client-ver": "1.20.0", "x-ms-lib-capability": "retry-after, h429" }, "RequestBody": "client_id=00000000-0000-0000-0000-000000000000\u0026grant_type=client_credentials\u0026client_info=1\u0026client_secret=00000000-0000-0000-0000-000000000000\u0026claims=%7B%22access_token%22%3A\u002B%7B%22xms_cc%22%3A\u002B%7B%22values%22%3A\u002B%5B%22CP1%22%5D%7D%7D%7D\u0026scope=https%3A%2F%2Fmanagement.azure.com%2F.default", "StatusCode": 200, "ResponseHeaders": { "Cache-Control": "no-store, no-cache", - "client-request-id": "865a2fb0-9b9e-4e09-997f-02c6682c30e0", - "Content-Length": "93", + "client-request-id": "95ddc384-b740-4477-a840-0bf5527bdf88", + "Content-Length": "114", "Content-Type": "application/json; charset=utf-8", - "Date": "Wed, 09 Mar 2022 06:51:40 GMT", + "Date": "Tue, 11 Oct 2022 02:41:41 GMT", "Expires": "-1", "P3P": "CP=\u0022DSP CUR OTPi IND OTRi ONL FIN\u0022", "Pragma": "no-cache", @@ -201,13 +201,14 @@ "Strict-Transport-Security": "max-age=31536000; includeSubDomains", "X-Content-Type-Options": "nosniff", "x-ms-clitelem": "1,0,0,,", - "x-ms-ests-server": "2.1.12529.17 - WUS2 ProdSlices", - "x-ms-request-id": "8f51276e-c307-4ec1-b670-5d6d54ea2e01" + "x-ms-ests-server": "2.1.13871.7 - EUS ProdSlices", + "X-XSS-Protection": "0" }, "ResponseBody": { "token_type": "Bearer", - "expires_in": 3599, - "ext_expires_in": 3599, + "expires_in": 86399, + "ext_expires_in": 86399, + "refresh_in": 43199, "access_token": "access_token" } }, @@ -217,12 +218,10 @@ "RequestHeaders": { "Accept": "application/json", "Accept-Encoding": "gzip, deflate", - "Authorization": "Sanitized", "Connection": "keep-alive", "Content-Length": "22", "Content-Type": "application/json", - "User-Agent": "azsdk-python-azure-mgmt-resource/20.1.0 Python/3.6.2 (Windows-10-10.0.19041-SP0)", - "x-ms-client-request-id": "5ec8eba4-9f75-11ec-beab-c0b6f9946f2d" + "User-Agent": "azsdk-python-azure-mgmt-resource/21.1.0 Python/3.8.14 (Linux-5.15.0-1020-azure-x86_64-with-glibc2.2.5) VSTS_0fb41ef4-5012-48a9-bf39-4ee3de03ee35_build_2500_0" }, "RequestBody": { "location": "eastus" @@ -232,7 +231,7 @@ "Cache-Control": "no-cache", "Content-Encoding": "gzip", "Content-Type": "application/json; charset=utf-8", - "Date": "Wed, 09 Mar 2022 06:51:48 GMT", + "Date": "Tue, 11 Oct 2022 02:41:43 GMT", "Expires": "-1", "Pragma": "no-cache", "Server": [ @@ -243,11 +242,10 @@ "Transfer-Encoding": "chunked", "Vary": "Accept-Encoding", "X-Content-Type-Options": "nosniff", - "x-ms-correlation-request-id": "a3d83309-73ee-4051-9535-279e53cb1a9e", - "x-ms-ratelimit-remaining-resource": "Microsoft.Compute/PutVM3Min;745,Microsoft.Compute/PutVM30Min;3729", + "x-ms-correlation-request-id": "0c6d11b3-2488-46d5-be2a-79e4b53189d3", + "x-ms-ratelimit-remaining-resource": "Microsoft.Compute/PutVM3Min;239,Microsoft.Compute/PutVM30Min;1199", "x-ms-ratelimit-remaining-subscription-writes": "1199", - "x-ms-request-id": "43365a2a-6278-4dc8-a86a-4fe49b22b314", - "x-ms-routing-request-id": "SOUTHEASTASIA:20220309T065148Z:a3d83309-73ee-4051-9535-279e53cb1a9e" + "x-ms-routing-request-id": "WESTUS:20221011T024143Z:0c6d11b3-2488-46d5-be2a-79e4b53189d3" }, "ResponseBody": { "name": "resourcexxx", diff --git a/shared_requirements.txt b/shared_requirements.txt index 791e644fb14..236ad3b9f15 100644 --- a/shared_requirements.txt +++ b/shared_requirements.txt @@ -424,8 +424,8 @@ opentelemetry-sdk<2.0.0,>=1.5.0,!=1.10a0 #override azure-mgmt-communication azure-mgmt-core>=1.3.0,<2.0.0 #override azure-mgmt-marketplaceordering msrest>=0.6.21 #override azure-mgmt-marketplaceordering azure-mgmt-core>=1.3.1,<2.0.0 -#override azure-mgmt-authorization msrest>=0.6.21 -#override azure-mgmt-authorization azure-mgmt-core>=1.3.1,<2.0.0 +#override azure-mgmt-authorization msrest>=0.7.1 +#override azure-mgmt-authorization azure-mgmt-core>=1.3.2,<2.0.0 #override azure-mgmt-iothub azure-mgmt-core>=1.3.2,<2.0.0 #override azure-mgmt-devtestlabs msrest>=0.6.21 #override azure-mgmt-devtestlabs azure-mgmt-core>=1.3.1,<2.0.0