AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
AWS Marketplace 用SDK于 Python 的协议API示例 (Boto3)
以下代码示例向您展示了如何使用 with Agreement 执行操作和实现常见场 AWS Marketplace 景API。 AWS SDK for Python (Boto3)
每个示例都包含一个指向完整源代码的链接,您可以在其中找到有关如何在上下文中设置和运行代码的说明。
主题
协议
以下代码示例显示了如何获得所有同意IDs。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to get all agreement ids AG-09 """ import logging import boto3 from botocore.exceptions import ClientError mp_client = boto3.client("marketplace-agreement") logger = logging.getLogger(__name__) MAX_PAGE_RESULTS = 10 def get_agreements(): AgreementSummaryList = [] agreement_id_list = [] try: agreements = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, filters=[ {"name": "PartyType", "values": ["Proposer"]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise AgreementSummaryList.extend(agreements["agreementViewSummaries"]) while "nextToken" in agreements and agreements["nextToken"] is not None: try: agreements = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, nextToken=agreements["nextToken"], filters=[ {"name": "PartyType", "values": ["Proposer"]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise AgreementSummaryList.extend(agreements["agreementViewSummaries"]) for agreement in AgreementSummaryList: agreement_id_list.append(agreement["agreementId"]) return agreement_id_list if __name__ == "__main__": agreement_id_list = get_agreements() print(agreement_id_list)
-
有关API详细信息,请参阅SearchAgreements中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何获取所有协议。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to get all agreements AG-01 """ import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError mp_client = boto3.client("marketplace-agreement") logger = logging.getLogger(__name__) MAX_PAGE_RESULTS = 10 party_type_list = ["Proposer"] agreement_type_list = ["PurchaseAgreement"] filter_list = [ {"name": "PartyType", "values": party_type_list}, {"name": "AgreementType", "values": agreement_type_list}, ] agreement_results_list = [] def get_agreements(filter_list=filter_list): try: agreements = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, filters=filter_list, ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise e agreement_results_list.extend(agreements["agreementViewSummaries"]) while "nextToken" in agreements and agreements["nextToken"] is not None: try: agreements = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, nextToken=agreements["nextToken"], filters=filter_list, ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise e agreement_results_list.extend(agreements["agreementViewSummaries"]) return agreement_results_list if __name__ == "__main__": agreements_list = get_agreements(filter_list) helper.pretty_print_datetime(agreements_list)
-
有关API详细信息,请参阅SearchAgreements中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示如何从协议中获取客户 ID。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to get customer AWS account id from a given agreement AG-08 """ import argparse import logging import boto3 from botocore.exceptions import ClientError mp_client = boto3.client("marketplace-agreement") logger = logging.getLogger(__name__) def get_agreement_information(agreement_id): try: response = mp_client.describe_agreement(agreementId=agreement_id) except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", agreement_id) raise e else: logger.error("Unexpected error: %s", e) raise e return response if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--agreement-id", "-aid", help="Provide agreement ID to describe agreement status", required=True, ) args = parser.parse_args() response = get_agreement_information(agreement_id=args.agreement_id) print(f"Customer account: {response['acceptor']['accountId']}")
-
有关API详细信息,请参阅DescribeAgreement中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示如何从协议中获取财务细节。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Obtain financial details, such as Total Contract Value of the agreementfrom a given agreement AG-14 Example Usage: python3 get_agreement_financial_details.py --agreement-id <agreement-id> """ import argparse import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) mp_client = boto3.client("marketplace-agreement") def get_agreement_information(agreement_id): try: agreement = mp_client.describe_agreement(agreementId=agreement_id) return agreement except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", agreement_id) else: logger.error("Unexpected error: %s", e) return None if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--agreement-id", "-aid", help="Provide agreement ID to describe agreement status", required=True, ) args = parser.parse_args() agreement = get_agreement_information(args.agreement_id) if agreement is not None: print(f"Agreement Id: {args.agreement_id}") print( f"Agreement Value: {agreement['estimatedCharges']['currencyCode']} {agreement['estimatedCharges']['agreementValue']}" ) else: print(f"Agreement with ID {args.agreement_id} is not found")
-
有关API详细信息,请参阅DescribeAgreement中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示如何从协议中获取免费试用详细信息。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Obtain the details from an agreement of a free trial I have provided to the customer AG-20 Example Usage: python3 get_agreement_free_trial_details.py --agreement-id <agreement-id> """ import argparse import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError logger = logging.getLogger(__name__) mp_client = boto3.client("marketplace-agreement") def get_agreement_terms(agreement_id): try: agreement = mp_client.get_agreement_terms(agreementId=agreement_id) return agreement except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", agreement_id) else: logger.error("Unexpected error: %s", e) return None if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--agreement-id", "-aid", help="Provide agreement ID to describe agreement status", required=True, ) args = parser.parse_args() agreement = get_agreement_terms(agreement_id=args.agreement_id) if agreement is not None: freetrial_found = False for term in agreement["acceptedTerms"]: if "freeTrialPricingTerm" in term.keys(): helper.pretty_print_datetime(term) freetrial_found = True if not freetrial_found: print(f"No free trial term found for agreement: {args.agreement_id}")
-
有关API详细信息,请参阅DescribeAgreement中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何获取有关协议的信息。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to get agreement information AG-07 """ import argparse import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError mp_client = boto3.client("marketplace-agreement") logger = logging.getLogger(__name__) def get_agreement_information(agreement_id): try: response = mp_client.describe_agreement(agreementId=agreement_id) except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", agreement_id) raise e else: logger.error("Unexpected error: %s", e) raise e return response if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--agreement-id", "-aid", help="Provide agreement ID to describe agreement status", required=True, ) args = parser.parse_args() response = get_agreement_information(agreement_id=args.agreement_id) helper.pretty_print_datetime(response)
-
有关API详细信息,请参阅DescribeAgreement中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例说明如何从协议中获取产品和优惠详情。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to get product and offer details in a given agreement AG-10 """ import argparse import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError mpa_client = boto3.client("marketplace-agreement") mpc_client = boto3.client("marketplace-catalog") logger = logging.getLogger(__name__) def get_agreement_information(agreement_id): """ Returns information about a given agreement Args: agreement_id str: Entity to return Returns: dict: Dictionary of agreement information """ try: agreement = mpa_client.describe_agreement(agreementId=agreement_id) return agreement except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", agreement_id) else: logger.error("Unexpected error: %s", e) def get_entity_information(entity_id): """ Returns information about a given entity Args: entity_id str: Entity to return Returns: dict: Dictionary of entity information """ try: response = mpc_client.describe_entity( Catalog="AWSMarketplace", EntityId=entity_id, ) return response except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Entity with ID %s not found.", entity_id) else: logger.error("Unexpected error: %s", e) def get_agreement_components(agreement_id): agreement_component_list = [] agreement = get_agreement_information(agreement_id) if agreement is not None: productIds = [] for resource in agreement["proposalSummary"]["resources"]: productIds.append(resource["id"]) for product_id in productIds: product_document = get_entity_information(product_id) product_document_dict = {} product_document_dict["product_id"] = product_id product_document_dict["document"] = product_document agreement_component_list.append(product_document_dict) offerId = agreement["proposalSummary"]["offerId"] offer_document = get_entity_information(offerId) offer_document_dict = {} offer_document_dict["offer_id"] = offerId offer_document_dict["document"] = offer_document agreement_component_list.append(offer_document_dict) return agreement_component_list else: print("Agreement with ID " + args.agreement_id + " is not found") if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") parser = argparse.ArgumentParser() parser.add_argument( "--agreement_id", "-aid", help="Provide agreement ID to search for product and offer detail", required=True, ) args = parser.parse_args() product_offer_detail = get_agreement_components(agreement_id=args.agreement_id) helper.pretty_print_datetime(product_offer_detail)
-
有关API详细信息,请参阅DescribeAgreement中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何获取协议。EULA
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Obtain the EULA I have entered into with my customer via the agreement AG-18 """ import json import logging import os import boto3 import utils.helpers as helper from botocore.exceptions import ClientError logger = logging.getLogger(__name__) # agreement id AGREEMENT_ID = "agmt-1111111111111111111111111" # to use sample file or not USE_SAMPLE_FILE = False SAMPLE_FILE_NAME = "mockup_agreement_terms.json" # attribute name ROOT_ELEM = "acceptedTerms" TERM_NAME = "legalTerm" CONFIG_ELEM = "configuration" ATTRIBUTE_NAME = "documents" def get_agreement_information(mp_client, entity_id): """ Returns customer AWS Account id about a given agreement Args: entity_id str: Entity to return Returns: dict: Dictionary of agreement information """ try: if USE_SAMPLE_FILE: sample_file = os.path.join(os.path.dirname(__file__), SAMPLE_FILE_NAME) terms = open_json_file(sample_file) else: terms = mp_client.get_agreement_terms(agreementId=entity_id) legalEulaArray = [] for term in terms[ROOT_ELEM]: if TERM_NAME in term and ATTRIBUTE_NAME in term[TERM_NAME]: docs = term[TERM_NAME][ATTRIBUTE_NAME] for doc in docs: if "type" in doc: legalEulaArray.append(doc) return legalEulaArray except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", entity_id) else: logger.error("Unexpected error: %s", e) def usage_demo(): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Looking for an agreement in the AWS Marketplace.") print("-" * 88) mp_client = boto3.client("marketplace-agreement") helper.pretty_print_datetime(get_agreement_information(mp_client, AGREEMENT_ID)) # open json file from path def open_json_file(filename): with open(filename, "r") as f: return json.load(f) if __name__ == "__main__": usage_demo()
-
有关API详细信息,请参阅GetAgreementTerms中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何获取协议的 auto 续订条款。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Obtain the auto-renewal status of the agreement AG-15 """ import json import logging import os import utils.helpers as helper import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) # agreement id AGREEMENT_ID = "agmt-11111111111111111111" # to use sample file or not USE_SAMPLE_FILE = False SAMPLE_FILE_NAME = "mockup_agreement_terms.json" # attribute name ROOT_ELEM = "acceptedTerms" TERM_NAME = "renewalTerm" CONFIG_ELEM = "configuration" ATTRIBUTE_NAME = "enableAutoRenew" def get_agreement_information(mp_client, entity_id): """ Returns customer AWS Account id about a given agreement Args: entity_id str: Entity to return Returns: dict: Dictionary of agreement information """ try: if USE_SAMPLE_FILE: sample_file = os.path.join(os.path.dirname(__file__), SAMPLE_FILE_NAME) terms = open_json_file(sample_file) else: terms = mp_client.get_agreement_terms(agreementId=entity_id) auto_renewal = "No Auto Renewal" for term in terms[ROOT_ELEM]: if TERM_NAME in term: if CONFIG_ELEM in term[TERM_NAME]: auto_renewal = term[TERM_NAME][CONFIG_ELEM][ATTRIBUTE_NAME] break return auto_renewal except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", entity_id) else: logger.error("Unexpected error: %s", e) def usage_demo(): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Looking for an agreement in the AWS Marketplace.") print("-" * 88) mp_client = boto3.client("marketplace-agreement") agreement = get_agreement_information(mp_client, AGREEMENT_ID) if agreement is not None: print(f"Auto Renewal is {agreement}") else: print("Agreement with ID " + AGREEMENT_ID + " is not found") # open json file from path def open_json_file(filename): with open(filename, "r") as f: return json.load(f) if __name__ == "__main__": usage_demo()
-
有关API详细信息,请参阅GetAgreementTerms中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何获取在协议中购买的维度。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Obtain the dimensions the buyer has purchased from me via the agreement AG-28 """ import json import logging import os import boto3 import utils.helpers as helper from botocore.exceptions import ClientError logger = logging.getLogger(__name__) # agreement id AGREEMENT_ID = "agmt-1111111111111111111111111" # to use sample file or not USE_SAMPLE_FILE = False SAMPLE_FILE_NAME = "mockup_agreement_terms.json" # attribute name ROOT_ELEM = "acceptedTerms" TERM_NAME = "configurableUpfrontPricingTerm" CONFIG_ELEM = "configuration" ATTRIBUTE_NAME = "selectorValue" def get_agreement_information(mp_client, entity_id): """ Returns customer AWS Account id about a given agreement Args: entity_id str: Entity to return Returns: dict: Dictionary of agreement information """ try: if USE_SAMPLE_FILE: sample_file = os.path.join(os.path.dirname(__file__), SAMPLE_FILE_NAME) terms = open_json_file(sample_file) else: terms = mp_client.get_agreement_terms(agreementId=entity_id) dimensionKeys = [] for term in terms[ROOT_ELEM]: if TERM_NAME in term: if CONFIG_ELEM in term[TERM_NAME]: confParam = term[TERM_NAME][CONFIG_ELEM] if ATTRIBUTE_NAME in confParam: if "dimensions" in confParam: for dimension in confParam["dimensions"]: if "dimensionKey" in dimension: dimensionKey = dimension["dimensionKey"] print(f"Dimension Key: {dimensionKey}") dimensionKeys.append(dimensionKey) return dimensionKeys except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", entity_id) else: logger.error("Unexpected error: %s", e) def usage_demo(): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Looking for an agreement in the AWS Marketplace.") print("-" * 88) mp_client = boto3.client("marketplace-agreement") helper.pretty_print_datetime(get_agreement_information(mp_client, AGREEMENT_ID)) # open json file from path def open_json_file(filename): with open(filename, "r") as f: return json.load(f) if __name__ == "__main__": usage_demo()
-
有关API详细信息,请参阅GetAgreementTerms中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何获取在协议中购买的每个维度的实例。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Obtain instances of each dimension that buyer has purchased in the agreement AG-30 """ import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError logger = logging.getLogger(__name__) # agreement id AGREEMENT_ID = "agmt-1111111111111111111111111" # attribute name ROOT_ELEM = "acceptedTerms" TERM_NAME = "configurableUpfrontPricingTerm" CONFIG_ELEM = "configuration" ATTRIBUTE_NAME = "selectorValue" logger = logging.getLogger(__name__) def get_agreement_information(mp_client, entity_id): """ Returns customer AWS Account id about a given agreement Args: entity_id str: Entity to return Returns: dict: Dictionary of agreement information """ try: terms = mp_client.get_agreement_terms(agreementId=entity_id) dimensionKeyValueMap = {} for term in terms[ROOT_ELEM]: if TERM_NAME in term: if CONFIG_ELEM in term[TERM_NAME]: confParam = term[TERM_NAME][CONFIG_ELEM] if ATTRIBUTE_NAME in confParam: selectValue = confParam["selectorValue"] dimensionKeyValueMap["selectorValue"] = selectValue if "dimensions" in confParam: dimensionKeyValueMap["dimensions"] = confParam["dimensions"] """ for dimension in confParam['dimensions']: if 'dimensionKey' in dimension: dimensionValue = dimension['dimensionValue'] dimensionKey = dimension['dimensionKey'] print(f"Selector: {selectValue}, Dimension Key: {dimensionKey}, Dimension Value: {dimensionValue}") dimensionKeyValueMap[dimensionKey] = dimensionValue """ return dimensionKeyValueMap except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", entity_id) else: logger.error("Unexpected error: %s", e) def usage_demo(): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Looking for an agreement in the AWS Marketplace.") print("-" * 88) mp_client = boto3.client("marketplace-agreement") helper.pretty_print_datetime(get_agreement_information(mp_client, AGREEMENT_ID)) if __name__ == "__main__": usage_demo()
-
有关API详细信息,请参阅GetAgreementTerms中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何获取协议的付款时间表。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Obtain the payment schedule I have agreed to with the agreement, including the invoice date and invoice amount AG-17 """ import json import logging import os import boto3 import utils.helpers as helper from botocore.exceptions import ClientError logger = logging.getLogger(__name__) # agreement id AGREEMENT_ID = "agmt-1111111111111111111111111" # to use sample file or not USE_SAMPLE_FILE = False SAMPLE_FILE_NAME = "mockup_agreement_terms.json" # attribute name ROOT_ELEM = "acceptedTerms" TERM_NAME = "paymentScheduleTerm" CONFIG_ELEM = "configuration" ATTRIBUTE_NAME = "selectorValue" def get_agreement_information(mp_client, entity_id): """ Returns customer AWS Account id about a given agreement Args: entity_id str: Entity to return Returns: dict: Dictionary of agreement information """ try: if USE_SAMPLE_FILE: sample_file = os.path.join(os.path.dirname(__file__), SAMPLE_FILE_NAME) terms = open_json_file(sample_file) else: terms = mp_client.get_agreement_terms(agreementId=entity_id) paymentScheduleArray = [] currencyCode = "" for term in terms[ROOT_ELEM]: if TERM_NAME in term: paymentSchedule = term[TERM_NAME] if "currencyCode" in paymentSchedule: currencyCode = paymentSchedule["currencyCode"] if "schedule" in paymentSchedule: for sch in paymentSchedule["schedule"]: if "chargeDate" in sch: chargeDate = sch["chargeDate"] chargeAmount = sch["chargeAmount"] # print(f"chargeDate: {chargeDate}, chargeAmount: {chargeAmount}") schedule = { "currencyCode": currencyCode, "chargeDate": chargeDate, "chargeAmount": chargeAmount, } paymentScheduleArray.append(schedule) return paymentScheduleArray except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", entity_id) else: logger.error("Unexpected error: %s", e) def usage_demo(): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Looking for an agreement in the AWS Marketplace.") print("-" * 88) mp_client = boto3.client("marketplace-agreement") helper.pretty_print_datetime(get_agreement_information(mp_client, AGREEMENT_ID)) # open json file from path def open_json_file(filename): with open(filename, "r") as f: return json.load(f) if __name__ == "__main__": usage_demo()
-
有关API详细信息,请参阅GetAgreementTerms中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何在协议中获取每个维度的定价。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Obtain pricing per each dimension in the agreement AG-29 """ import json import logging import os import boto3 import utils.helpers as helper from botocore.exceptions import ClientError logger = logging.getLogger(__name__) # agreement id AGREEMENT_ID = "agmt-1111111111111111111111111" # to use sample file or not USE_SAMPLE_FILE = False SAMPLE_FILE_NAME = "mockup_agreement_terms.json" # attribute name ROOT_ELEM = "acceptedTerms" TERM_NAME = "configurableUpfrontPricingTerm" CONFIG_ELEM = "configuration" ATTRIBUTE_NAME = "selectorValue" TERMS_TO_SEARCH = [ "configurableUpfrontPricingTerm", "usageBasedPricingTerm", "fixedUpfrontPricingTerm", ] def get_agreement_information(mp_client, entity_id): """ Returns customer AWS Account id about a given agreement Args: entity_id str: Entity to return Returns: dict: Dictionary of agreement information """ try: if USE_SAMPLE_FILE: sample_file = os.path.join(os.path.dirname(__file__), SAMPLE_FILE_NAME) terms = open_json_file(sample_file) else: terms = mp_client.get_agreement_terms(agreementId=entity_id) dimentions = [] for term in terms[ROOT_ELEM]: for t in TERMS_TO_SEARCH: rateInfo = [] if t in term: if "type" in term[t]: rateInfo.append(term[t]["type"]) if "currencyCode" in term[t]: rateInfo.append(term[t]["currencyCode"]) if "rateCards" in term[t]: rateInfo.append(term[t]["rateCards"]) dimentions.append(rateInfo) return dimentions except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", entity_id) else: logger.error("Unexpected error: %s", e) def usage_demo(): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Looking for an agreement in the AWS Marketplace.") print("-" * 88) mp_client = boto3.client("marketplace-agreement") helper.pretty_print_datetime(get_agreement_information(mp_client, AGREEMENT_ID)) # open json file from path def open_json_file(filename): with open(filename, "r") as f: return json.load(f) if __name__ == "__main__": usage_demo()
-
有关API详细信息,请参阅GetAgreementTerms中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何获取协议的定价类型。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Obtain the pricing type of the agreement (contract, FPS, metered, free etc.) AG-16 """ import json import logging import boto3 from botocore.exceptions import ClientError # To search by offer id: OfferId; by product id: ResourceIdentifier; by product type: ResourceType idType = "OfferId" # replace id value as needed idValue = "offer-1111111111111" MAX_PAGE_RESULTS = 10 # catalog; switch to AWSMarketplace for release AWSMPCATALOG = "AWSMarketplace" # product types SaaSProduct = "SaaSProduct" AmiProduct = "AmiProduct" MLProduct = "MachineLearningProduct" ContainerProduct = "ContainerProduct" DataProduct = "DataProduct" ProServiceProduct = "ProfessionalServicesProduct" AiqProduct = "AiqProduct" # Define pricing types CCP = "CCP" Annual = "Annual" Contract = "Contract" SFT = "SaaS Freee Trial" HMA = "Hourly and Monthly Agreements" Hourly = "Hourly" Monthly = "Monthly" AFPS = "Annual FPS" CFPS = "Contract FPS" CCPFPS = "CCP with FPS" BYOL = "BYOL" Free = "Free" FTH = "Free Trials and Hourly" # Define Agreement Term Types legal = ["LegalTerm"] config = ["ConfigurableUpfrontPricingTerm"] usage = ["UsageBasedPricingTerm"] config_usage = ["ConfigurableUpfrontPricingTerm", "UsageBasedPricingTerm"] freeTrial = ["FreeTrialPricingTerm"] recur = ["RecurringPaymentTerm"] usage_recur = ("UsageBasedPricingTerm", "RecurringPaymentTerm") fixed_payment = ["FixedUpfrontPricingTerm", "PaymentScheduleTerm"] fixed_payment_usage = [ "FixedUpfrontPricingTerm", "PaymentScheduleTerm", "UsageBasedPricingTerm", ] byol = ["ByolPricingTerm"] freeTrial_usage = ("FreeTrialPricingTerm", "UsageBasedPricingTerm") all_agreement_types_combination = ( legal, config, usage, config_usage, freeTrial, recur, usage_recur, fixed_payment, fixed_payment_usage, byol, freeTrial_usage, ) # get pricing type method given product type, agreement temr type and offer type if needed def get_pricing_type(product_type, agreement_term_type, offer_type): pricing_types = { (SaaSProduct, frozenset(config_usage), frozenset("")): CCP, (DataProduct, frozenset(config_usage), frozenset("")): CCP, (ContainerProduct, frozenset(config), frozenset(config_usage)): Annual, (AmiProduct, frozenset(config), frozenset(config_usage)): Annual, (MLProduct, frozenset(config), frozenset(config_usage)): Annual, (ContainerProduct, frozenset(config), frozenset(config)): Contract, (AmiProduct, frozenset(config), frozenset(config)): Contract, (SaaSProduct, frozenset(config), frozenset("")): Contract, (DataProduct, frozenset(config), frozenset("")): Contract, (AiqProduct, frozenset(config), frozenset("")): Contract, (ProServiceProduct, frozenset(config), frozenset("")): Contract, (SaaSProduct, frozenset(freeTrial), frozenset("")): SFT, (AmiProduct, frozenset(usage_recur), frozenset("")): HMA, (SaaSProduct, frozenset(usage), frozenset("")): Hourly, (AmiProduct, frozenset(usage), frozenset("")): Hourly, (ContainerProduct, frozenset(usage), frozenset("")): Hourly, (MLProduct, frozenset(usage), frozenset("")): Hourly, (ContainerProduct, frozenset(recur), frozenset("")): Monthly, (AmiProduct, frozenset(recur), frozenset("")): Monthly, ( ContainerProduct, frozenset(fixed_payment), frozenset(fixed_payment_usage), ): AFPS, (AmiProduct, frozenset(fixed_payment), frozenset(fixed_payment_usage)): AFPS, (MLProduct, frozenset(fixed_payment), frozenset("")): AFPS, (ContainerProduct, frozenset(fixed_payment), frozenset(fixed_payment)): CFPS, (AmiProduct, frozenset(fixed_payment), frozenset(fixed_payment)): CFPS, (SaaSProduct, frozenset(fixed_payment), frozenset("")): CFPS, (DataProduct, frozenset(fixed_payment), frozenset("")): CFPS, (AiqProduct, frozenset(fixed_payment), frozenset("")): CFPS, (ProServiceProduct, frozenset(fixed_payment), frozenset("")): CFPS, (SaaSProduct, frozenset(fixed_payment_usage), frozenset("")): CCPFPS, (DataProduct, frozenset(fixed_payment_usage), frozenset("")): CCPFPS, (AiqProduct, frozenset(fixed_payment_usage), frozenset("")): CCPFPS, (ProServiceProduct, frozenset(fixed_payment_usage), frozenset("")): CCPFPS, (AmiProduct, frozenset(byol), frozenset("")): BYOL, (SaaSProduct, frozenset(byol), frozenset("")): BYOL, (ProServiceProduct, frozenset(byol), frozenset("")): BYOL, (AiqProduct, frozenset(byol), frozenset("")): BYOL, (MLProduct, frozenset(byol), frozenset("")): BYOL, (ContainerProduct, frozenset(byol), frozenset("")): BYOL, (DataProduct, frozenset(byol), frozenset("")): BYOL, (ContainerProduct, frozenset(legal), frozenset("")): Free, (AmiProduct, frozenset(freeTrial_usage), frozenset("")): FTH, (ContainerProduct, frozenset(freeTrial_usage), frozenset("")): FTH, (MLProduct, frozenset(freeTrial_usage), frozenset("")): FTH, } key = (product_type, agreement_term_type, offer_type) if key in pricing_types: return pricing_types[key] else: return "Unknown" # Example usage for testing purpose """ product_type = SaaSProduct agreement_term_type = frozenset(config_usage) offer_type = frozenset('') pricing_type = get_pricing_type(product_type, agreement_term_type, offer_type) print("pricing type = " + pricing_type) # Output: CCP """ # check if offer term types are needed; if Y, needed def get_offer_term_type(product_type, agreement_term_type): offer_term_types = { (ContainerProduct, frozenset(config)): "Y", (AmiProduct, frozenset(config)): "Y", (ContainerProduct, frozenset(fixed_payment)): "Y", (AmiProduct, frozenset(fixed_payment)): "Y", (AmiProduct, frozenset(fixed_payment), frozenset(fixed_payment)): "Y", } key = (product_type, agreement_term_type) if key in offer_term_types: return offer_term_types[key] else: return logger = logging.getLogger(__name__) def get_agreements(mp_client): AgreementSummaryList = [] partyTypes = ["Proposer"] for value in partyTypes: try: agreement = mp_client.search_agreements( catalog=AWSMPCATALOG, maxResults=MAX_PAGE_RESULTS, filters=[ {"name": "PartyType", "values": [value]}, {"name": idType, "values": [idValue]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise AgreementSummaryList.extend(agreement["agreementViewSummaries"]) while "nextToken" in agreement and agreement["nextToken"] is not None: try: agreement = mp_client.search_agreements( catalog=AWSMPCATALOG, maxResults=MAX_PAGE_RESULTS, nextToken=agreement["nextToken"], filters=[ {"name": "PartyType", "values": [value]}, {"name": idType, "values": [idValue]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise AgreementSummaryList.extend(agreement["agreementViewSummaries"]) return AgreementSummaryList def usage_demo(): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Looking for an agreement in the AWS Marketplace Catalog.") print("-" * 88) mp_client = boto3.client("marketplace-agreement") # find all agreements matching the specified idType and idValue agreements = get_agreements(mp_client) for item in agreements: pricingType = "" agreement_id = item["agreementId"] # get term types inside offer offer_term_types = get_offer_term_types(item) # even though multiple product types are allowed for one agreement, only need the first one productType = item["resourceSummaries"][0]["resourceType"] # get agreement terms types agreementTerm = mp_client.get_agreement_terms(agreementId=agreement_id) agreementTermTypes = get_agreement_term_types(agreementTerm) # match with agreement term type group matchedTermType = getMatchedTermTypesCombination(agreementTermTypes) # check if offer term type is needed. offer_term_type_needed = get_offer_term_type( productType, frozenset(matchedTermType) ) # get pricing type given product type, agreement term types and offer type if needed; # one excpetion is Container with Legal term. LegalTerm needs to be the only term present if offer_term_type_needed is not None: matchedOfferTermTypes = getMatchedTermTypesCombination(offer_term_types) print(f"matchedOfferTermType = {matchedOfferTermTypes}") pricingType = get_pricing_type( productType, frozenset(matchedTermType), frozenset(matchedOfferTermTypes), ) elif set(matchedTermType) == set(legal): pricingType = Free else: pricingType = get_pricing_type( productType, frozenset(matchedTermType), frozenset("") ) print( f"agreementId={agreement_id};productType={productType}; agreementTermTypes={agreementTermTypes}; matchedTermType={matchedTermType}; offerTermTypeNeeded={offer_term_type_needed}; offer_term_types={offer_term_types}" ) print(f"pricing type={pricingType}") def getMatchedTermTypesCombination(agreementTermTypes): matchedCombination = () for element in all_agreement_types_combination: if check_elements(agreementTermTypes, element): matchedCombination = element return matchedCombination def get_offer_term_types(item): offer_id = item["agreementTokenSummary"]["offerId"] mp_catalogAPI_client = boto3.client("marketplace-catalog") offer_document = get_entity_information(mp_catalogAPI_client, offer_id) offerDetail = offer_document["Details"] offerDetail_json_object = json.loads(offerDetail) offer_term_types = [term["Type"] for term in offerDetail_json_object["Terms"]] return offer_term_types # make sure all elements in array2 exist in array1 def check_elements(array1, array2): for element in array2: if element not in array1: return False return True def get_entity_information(mp_client, entity_id): """ Returns information about a given entity Args: entity_id str: Entity to return Returns: dict: Dictionary of entity information """ try: response = mp_client.describe_entity( Catalog="AWSMarketplace", EntityId=entity_id, ) return response except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Entity with ID %s not found.", entity_id) else: logger.error("Unexpected error: %s", e) def get_agreement_term_types(agreementTerm): types = [] for term in agreementTerm["acceptedTerms"]: for value in term.values(): if isinstance(value, dict) and "type" in value: types.append(value["type"]) return types if __name__ == "__main__": usage_demo()
-
有关API详细信息,请参阅DescribeAgreement中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何获取协议的产品类型。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Obtain the Product Type of the product the agreement was created on AG-11 """ import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) # agreement id AGREEMENT_ID = "agmt-1111111111111111111111111" def get_agreement_information(mp_client, entity_id): """ Returns information about a given agreement Args: entity_id str: Entity to return Returns: dict: Dictionary of agreement information """ try: agreement = mp_client.describe_agreement(agreementId=entity_id) return agreement except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", entity_id) else: logger.error("Unexpected error: %s", e) def usage_demo(): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Looking for offer and product details in a given agreement by agreement id.") print("-" * 88) mp_client = boto3.client("marketplace-agreement") agreement = get_agreement_information(mp_client, AGREEMENT_ID) if agreement is not None: productHash = {} for resource in agreement["resourceSummaries"]: productHash[resource["resourceId"]] = resource["resourceType"] for key, value in productHash.items(): print(f"Product ID: {key} | Product Type: {value}") else: print("Agreement with ID " + AGREEMENT_ID + " is not found") if __name__ == "__main__": usage_demo()
-
有关API详细信息,请参阅DescribeAgreement中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何获取协议的状态。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to get all agreement status AG-13 Example Usage: python3 get_agreement_status.py --agreement-id <agreement-id> """ import argparse import logging import boto3 from botocore.exceptions import ClientError mp_client = boto3.client("marketplace-agreement") logger = logging.getLogger(__name__) def get_agreement(agreement_id): try: response = mp_client.describe_agreement(agreementId=agreement_id) return response except ClientError as e: logger.error(f"Could not complete search_agreements request. {e}") return None if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--agreement-id", "-aid", help="Provide agreement ID to describe agreement status", required=True, ) args = parser.parse_args() response = get_agreement(agreement_id=args.agreement_id) if response is not None: print(f"Agreement status: {response['status']}") else: print(f"No agreement found for {args.agreement_id}")
-
有关API详细信息,请参阅DescribeAgreement中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何获取协议的支持条款。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Obtain the support and refund policy I have provided to the customer for an agreement AG-19 Example Usage: python3 get_agreement_support_terms.py --agreement-id <agreement-id> """ import argparse import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError logger = logging.getLogger(__name__) mp_client = boto3.client("marketplace-agreement") def get_agreement_terms(agreement_id): try: agreement = mp_client.get_agreement_terms(agreementId=agreement_id) return agreement except ClientError as e: if e.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Agreement with ID %s not found.", agreement_id) else: logger.error("Unexpected error: %s", e) return None if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--agreement-id", "-aid", help="Provide agreement ID to describe agreement status", required=True, ) args = parser.parse_args() agreement = get_agreement_terms(agreement_id=args.agreement_id) if agreement is not None: support_found = False for term in agreement["acceptedTerms"]: if "supportTerm" in term.keys(): helper.pretty_print_datetime(term) support_found = True if not support_found: print(f"No support term found for agreement: {args.agreement_id}")
-
有关API详细信息,请参阅GetAgreementTerms中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例说明如何按账户 ID 搜索协议。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to get agreement by customer AWS account ID AG-02 """ import argparse import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError mp_client = boto3.client("marketplace-agreement") logger = logging.getLogger(__name__) MAX_PAGE_RESULTS = 10 def get_agreements(account_id): AgreementSummaryList = [] try: agreement = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, filters=[ {"name": "PartyType", "values": ["Proposer"]}, {"name": "AcceptorId", "values": [account_id]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise e AgreementSummaryList.extend(agreement["agreementViewSummaries"]) while "nextToken" in agreement and agreement["nextToken"] is not None: try: agreement = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, nextToken=agreement["nextToken"], filters=[ {"name": "PartyType", "values": ["Proposer"]}, {"name": "AcceptorId", "values": [account_id]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise e AgreementSummaryList.extend(agreement["agreementViewSummaries"]) return AgreementSummaryList if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--account_id", "-aid", help="Provide accepting account ID to search for agreements", required=True, ) args = parser.parse_args() response = get_agreements(account_id=args.account_id) helper.pretty_print_datetime(response)
-
有关API详细信息,请参阅SearchAgreements中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例说明如何按协议 ID 搜索协议。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to search for agreements give id information AG-02-A """ import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError # To search by offer id: OfferId; by product id: ResourceIdentifier; by product type: ResourceType idType = "ResourceType" # replace id value as needed idValue = "SaaSProduct" MAX_PAGE_RESULTS = 10 logger = logging.getLogger(__name__) def get_agreements(mp_client): AgreementSummaryList = [] partyTypes = ["Proposer"] for value in partyTypes: try: agreement = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, filters=[ {"name": "PartyType", "values": [value]}, {"name": idType, "values": [idValue]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise e AgreementSummaryList.extend(agreement["agreementViewSummaries"]) while "nextToken" in agreement and agreement["nextToken"] is not None: try: agreement = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, nextToken=agreement["nextToken"], filters=[ {"name": "PartyType", "values": [value]}, {"name": idType, "values": [idValue]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise e AgreementSummaryList.extend(agreement["agreementViewSummaries"]) return AgreementSummaryList def usage_demo(): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Looking for an agreement in the AWS Marketplace Catalog.") print("-" * 88) mp_client = boto3.client("marketplace-agreement") helper.pretty_print_datetime(get_agreements(mp_client)) if __name__ == "__main__": usage_demo()
-
有关API详细信息,请参阅SearchAgreements中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例说明如何按结束日期搜索协议。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to search for agreement information before or after end date AG-03 """ import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError mp_client = boto3.client("marketplace-agreement") # change to 'AfterEndTime' if after endtime is desired beforeOrAfterEndtimeFilterName = "BeforeEndTime" # Make sure to use the same date format as below cutoffDate = "2322-11-18T00:00:00Z" MAX_PAGE_RESULTS = 10 logger = logging.getLogger(__name__) def get_agreements(): AgreementSummaryList = [] try: agreement = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, filters=[ {"name": "PartyType", "values": ["Proposer"]}, {"name": beforeOrAfterEndtimeFilterName, "values": [cutoffDate]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise AgreementSummaryList.extend(agreement["agreementViewSummaries"]) while "nextToken" in agreement: try: agreement = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, nextToken=agreement["nextToken"], filters=[ {"name": "PartyType", "values": ["Proposer"]}, { "name": beforeOrAfterEndtimeFilterName, "values": [cutoffDate], }, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise AgreementSummaryList.extend(agreement["agreementViewSummaries"]) return AgreementSummaryList if __name__ == "__main__": agreements = get_agreements() helper.pretty_print_datetime(agreements)
-
有关API详细信息,请参阅SearchAgreements中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例显示了如何按选件编号搜索协议。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to search for agreements by offer id AG-0 """ import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError # offer id to search by offerId = "1111111111111111111111111" MAX_PAGE_RESULTS = 10 logger = logging.getLogger(__name__) def get_agreements(mp_client): AgreementSummaryList = [] partyTypes = ["Proposer"] for value in partyTypes: try: agreement = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, filters=[ {"name": "PartyType", "values": [value]}, {"name": "OfferId", "values": [offerId]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise AgreementSummaryList.extend(agreement["agreementViewSummaries"]) while "nextToken" in agreement and agreement["nextToken"] is not None: try: agreement = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, nextToken=agreement["nextToken"], filters=[ {"name": "PartyType", "values": [value]}, {"name": "OfferId", "values": [offerId]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise AgreementSummaryList.extend(agreement["agreementViewSummaries"]) return AgreementSummaryList def usage_demo(): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Looking for an agreement by offer id.") print("-" * 88) mp_client = boto3.client("marketplace-agreement") helper.pretty_print_datetime(get_agreements(mp_client)) if __name__ == "__main__": usage_demo()
-
有关API详细信息,请参阅SearchAgreements中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例说明如何按产品 ID 搜索协议。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to search for agreement by product id AG-02 """ import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError # product id to search by resourceId = "prod-1111111111111" MAX_PAGE_RESULTS = 10 logger = logging.getLogger(__name__) def get_agreements(mp_client): AgreementSummaryList = [] partyTypes = ["Proposer"] for value in partyTypes: try: agreement = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, filters=[ {"name": "PartyType", "values": [value]}, {"name": "ResourceIdentifier", "values": [resourceId]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete list_entities request.") raise AgreementSummaryList.extend(agreement["agreementViewSummaries"]) while "nextToken" in agreement: try: agreement = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, nextToken=agreement["nextToken"], filters=[ {"name": "PartyType", "values": [value]}, {"name": "ResourceIdentifier", "values": [resourceId]}, {"name": "AgreementType", "values": ["PurchaseAgreement"]}, ], ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise AgreementSummaryList.extend(agreement["agreementViewSummaries"]) return AgreementSummaryList def usage_demo(): logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Looking for an agreement in the AWS Marketplace Catalog.") print("-" * 88) mp_client = boto3.client("marketplace-agreement") helper.pretty_print_datetime(get_agreements(mp_client)) if __name__ == "__main__": usage_demo()
-
有关API详细信息,请参阅SearchAgreements中的 AWS SDKPython (Boto3) API 参考。
-
以下代码示例说明如何按状态搜索协议。
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整的示例,学习如何在AWS Marketplace API参考代码库存储库
中设置和运行。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) to filter agreements by status AG-04 Example Usage: python3 search_agreements_by_status.py """ import logging import boto3 import utils.helpers as helper from botocore.exceptions import ClientError mp_client = boto3.client("marketplace-agreement") logger = logging.getLogger(__name__) MAX_PAGE_RESULTS = 10 party_type_list = ["Proposer"] agreement_type_list = ["PurchaseAgreement"] # Accepted values: "ACTIVE", "TERMINATED", "CANCELED", "EXPIRED", "REPLACED", "RENEWED" status_list = ["ACTIVE"] filter_list = [ {"name": "PartyType", "values": party_type_list}, {"name": "AgreementType", "values": agreement_type_list}, {"name": "Status", "values": status_list}, ] agreement_results_list = [] def get_agreements(filter_list=filter_list): try: agreements = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, filters=filter_list, ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise e agreement_results_list.extend(agreements["agreementViewSummaries"]) while "nextToken" in agreements and agreements["nextToken"] is not None: try: agreements = mp_client.search_agreements( catalog="AWSMarketplace", maxResults=MAX_PAGE_RESULTS, nextToken=agreements["nextToken"], filters=filter_list, ) except ClientError as e: logger.error("Could not complete search_agreements request.") raise e agreement_results_list.extend(agreements["agreementViewSummaries"]) helper.pretty_print_datetime(agreement_results_list) return agreement_results_list if __name__ == "__main__": agreements_list = get_agreements(filter_list)
-
有关API详细信息,请参阅SearchAgreements中的 AWS SDKPython (Boto3) API 参考。
-