├── alibabacloud ├── services │ ├── __init__.py │ ├── ens.py │ ├── vpc.py │ └── slb.py ├── utils │ ├── __init__.py │ ├── protocol_type.py │ ├── validation.py │ ├── method_type.py │ ├── load_json_from_data_dir.py │ ├── parameter_helper.py │ ├── format_type.py │ └── ini_helper.py ├── vendored │ ├── __init__.py │ └── requests │ │ ├── packages │ │ ├── chardet │ │ │ ├── cli │ │ │ │ ├── __init__.py │ │ │ │ └── chardetect.py │ │ │ ├── version.py │ │ │ ├── compat.py │ │ │ ├── __init__.py │ │ │ ├── euctwprober.py │ │ │ ├── euckrprober.py │ │ │ ├── gb2312prober.py │ │ │ ├── big5prober.py │ │ │ ├── enums.py │ │ │ ├── cp949prober.py │ │ │ ├── mbcsgroupprober.py │ │ │ └── utf8prober.py │ │ ├── urllib3 │ │ │ ├── contrib │ │ │ │ ├── __init__.py │ │ │ │ └── _securetransport │ │ │ │ │ └── __init__.py │ │ │ ├── packages │ │ │ │ ├── backports │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── makefile.py │ │ │ │ ├── __init__.py │ │ │ │ └── ssl_match_hostname │ │ │ │ │ └── __init__.py │ │ │ ├── util │ │ │ │ ├── __init__.py │ │ │ │ ├── wait.py │ │ │ │ └── response.py │ │ │ ├── filepost.py │ │ │ └── __init__.py │ │ ├── certifi │ │ │ ├── __main__.py │ │ │ ├── __init__.py │ │ │ └── core.py │ │ └── __init__.py │ │ ├── __version__.py │ │ ├── certs.py │ │ ├── packages.py │ │ ├── hooks.py │ │ ├── _internal_utils.py │ │ ├── compat.py │ │ ├── __init__.py │ │ └── structures.py ├── clients │ ├── __init__.py │ ├── nls_cloud_meta_20180518.py │ ├── saf_20180919.py │ ├── xspace_20170720.py │ ├── dybaseapi_20170525.py │ ├── teslastream_20180115.py │ ├── pts_20190522.py │ ├── alimt_20190107.py │ ├── sts_20150401.py │ ├── ubsms_20150623.py │ ├── oms_20150212.py │ ├── yundun_20150227.py │ └── tesladam_20180118.py ├── retry │ ├── __init__.py │ ├── retry_policy_context.py │ └── retry_policy.py ├── resources │ ├── __init__.py │ └── base.py ├── session.py ├── endpoint │ ├── __init__.py │ ├── resolver_endpoint_request.py │ ├── endpoint_resolver_base.py │ ├── user_customized_endpoint_resolver.py │ ├── local_config_global_endpoint_resolver.py │ ├── location_endpoint_caller.py │ ├── default_endpoint_resolver.py │ └── chained_endpoint_resolver.py ├── handlers │ ├── credentials_handler.py │ ├── endpoint_handler.py │ ├── __init__.py │ ├── signer_handler.py │ ├── timeout_config_reader.py │ └── retry_handler.py ├── signer │ └── __init__.py ├── credentials │ ├── __init__.py │ └── assume_role_caller.py ├── compat.py └── request.py ├── python-function-test ├── __init__.py ├── alibabacloud_useragent_test.py ├── test_check_params.py ├── alibabacloud_logger_test.py ├── test_client.py ├── alibabacloud_legacy_api_test.py ├── alibabacloud_edas_test.py └── alibabacloud_verify_test.py ├── scripts ├── code-coverage-report.sh ├── run-test.sh ├── release.sh ├── test.sh ├── code-style-check.sh └── release-tool.sh ├── docs ├── source │ ├── reference │ │ ├── 01_client.rst │ │ ├── index.rst │ │ ├── 03_api.rst │ │ └── 02_resource.rst │ ├── quickstart │ │ ├── 02_usage.rst │ │ ├── index.rst │ │ ├── 01_installations.rst │ │ └── usage │ │ │ ├── 01_client.rst │ │ │ └── 02_resource.rst │ ├── advance │ │ ├── index.rst │ │ ├── 01_client.rst │ │ ├── 03_logger.rst │ │ ├── credentials │ │ │ ├── 04_instance.rst │ │ │ ├── 02_env.rst │ │ │ ├── 01_func.rst │ │ │ └── 03_file.rst │ │ ├── client │ │ │ ├── 02_timeout.rst │ │ │ ├── 05_retry.rst │ │ │ ├── 04_header.rst │ │ │ ├── 03_proxy.rst │ │ │ └── 01_region.rst │ │ ├── 02_credentials.rst │ │ └── logger │ │ │ ├── 01_console.rst │ │ │ └── 02_file.rst │ ├── questions │ │ ├── index.rst │ │ └── 01_pyinstaller.rst │ ├── higher │ │ ├── index.rst │ │ ├── 05_exceptions.rst │ │ ├── 01_retry.rst │ │ ├── 03_endpoint.rst │ │ ├── 02_credentials.rst │ │ └── 04_client.rst │ ├── index.rst │ └── conf.py ├── Makefile └── make.bat ├── .gitignore ├── .travis.yml ├── tests ├── mock_data │ ├── eip_addres.json │ └── instance_full_status.json ├── __init__.py ├── test_common_usage.py └── base.py └── setup.py /alibabacloud/services/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /alibabacloud/utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /alibabacloud/vendored/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /python-function-test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /alibabacloud/clients/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '' 2 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/cli/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/urllib3/contrib/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/urllib3/packages/backports/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /scripts/code-coverage-report.sh: -------------------------------------------------------------------------------- 1 | coverage report --include="./alibabacloud/*" 2 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/urllib3/contrib/_securetransport/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/source/reference/01_client.rst: -------------------------------------------------------------------------------- 1 | .. _usage-client: 2 | 3 | 可用客户端 4 | ============= -------------------------------------------------------------------------------- /scripts/run-test.sh: -------------------------------------------------------------------------------- 1 | coverage run -a --source="./alibabacloud" --branch -m pytest tests 2 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/certifi/__main__.py: -------------------------------------------------------------------------------- 1 | from certifi import where 2 | print(where()) 3 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from . import urllib3 -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/certifi/__init__.py: -------------------------------------------------------------------------------- 1 | from .core import where, old_where 2 | 3 | __version__ = "2018.01.18" 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | venv/ 3 | .idea/ 4 | *.egg-info/ 5 | dist/ 6 | build/ 7 | .cache/ 8 | .coverage 9 | .vscode 10 | 11 | -------------------------------------------------------------------------------- /scripts/release.sh: -------------------------------------------------------------------------------- 1 | sh -xe scripts/release-core.sh dist 2 | sh -xe scripts/release-core.sh test 3 | sh -xe scripts/release-core.sh release 4 | -------------------------------------------------------------------------------- /docs/source/quickstart/02_usage.rst: -------------------------------------------------------------------------------- 1 | 使用 2 | ============ 3 | 4 | .. toctree:: 5 | :maxdepth: 3 6 | 7 | usage/01_client 8 | usage/02_resource -------------------------------------------------------------------------------- /docs/source/quickstart/index.rst: -------------------------------------------------------------------------------- 1 | 快速开始 2 | ************** 3 | 4 | 5 | .. toctree:: 6 | :maxdepth: 3 7 | :numbered: 2 8 | 9 | 01_installations 10 | 02_usage -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/urllib3/packages/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from . import ssl_match_hostname 4 | 5 | __all__ = ('ssl_match_hostname', ) 6 | -------------------------------------------------------------------------------- /docs/source/advance/index.rst: -------------------------------------------------------------------------------- 1 | 进阶 2 | ************** 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | :numbered: 2 7 | 8 | 01_client 9 | 02_credentials 10 | 03_logger 11 | -------------------------------------------------------------------------------- /docs/source/questions/index.rst: -------------------------------------------------------------------------------- 1 | FAQ 2 | ************** 3 | 4 | 这一部分是处理一些共性问题,suchas pyinstaller 5 | 6 | 7 | .. toctree:: 8 | :maxdepth: 2 9 | :numbered: 2 10 | 11 | 01_pyinstaller 12 | -------------------------------------------------------------------------------- /docs/source/reference/index.rst: -------------------------------------------------------------------------------- 1 | 用户指南 2 | ************** 3 | 这部分主要是API文档说明 4 | 5 | 6 | .. toctree:: 7 | :maxdepth: 2 8 | :numbered: 2 9 | 10 | 01_client 11 | 02_resource 12 | 03_api 13 | 14 | -------------------------------------------------------------------------------- /docs/source/higher/index.rst: -------------------------------------------------------------------------------- 1 | 高级实践 2 | ************** 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | :numbered: 2 7 | 8 | 01_retry 9 | 02_credentials 10 | 03_endpoint 11 | 04_client 12 | 05_exceptions -------------------------------------------------------------------------------- /docs/source/quickstart/01_installations.rst: -------------------------------------------------------------------------------- 1 | 安装 2 | ============ 3 | 4 | **Alibaba Cloud Python SDK** 目前暂没有发布 **pypi** 版本,只能通过源代码安装: 5 | 6 | :: 7 | 8 | git clone https://github.com/aliyun/alibabacloud-python-sdk-v2.git 9 | cd alibabacloud-python-sdk-v2 10 | python setup.py install 11 | -------------------------------------------------------------------------------- /docs/source/advance/01_client.rst: -------------------------------------------------------------------------------- 1 | 客户端配置 2 | ================== 3 | 4 | ``Alibaba Cloud Python SDK`` 提供了一系列的客户端配置,帮助您初始化 ``Client`` ,但是,您也可以修改默认值。 5 | 6 | 7 | .. toctree:: 8 | :maxdepth: 2 9 | 10 | client/01_region 11 | client/02_timeout 12 | client/03_proxy 13 | client/04_header 14 | client/05_retry 15 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/version.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module exists only to simplify retrieving the version number of chardet 3 | from within setup.py and from chardet subpackages. 4 | 5 | :author: Dan Blanchard (dan.blanchard@gmail.com) 6 | """ 7 | 8 | __version__ = "3.0.4" 9 | VERSION = __version__.split('.') 10 | -------------------------------------------------------------------------------- /docs/source/advance/03_logger.rst: -------------------------------------------------------------------------------- 1 | 使用Alibaba Cloud Python SDK 日志 2 | ================================= 3 | 4 | 日志是 ``Alibaba Cloud Python SDK`` 提供的新功能。您可以通过 5 | ``Alibaba Cloud Python SDK`` 6 | 创建控制台日志或者文件日志。我们支持您对日志的级别、格式、名称进行定制。 7 | 8 | .. toctree:: 9 | :maxdepth: 2 10 | 11 | logger/01_console 12 | logger/02_file 13 | -------------------------------------------------------------------------------- /scripts/test.sh: -------------------------------------------------------------------------------- 1 | echo "Run code style check ..." 2 | #sh -xe scripts/code-style-check.sh 3 | 4 | echo "get env ACCESS_KEY_ID for test" 5 | printenv 6 | echo "get env ACCESS_KEY_ID for test over" 7 | 8 | echo "Run functional tests ..." 9 | sh -xe scripts/run-test.sh 10 | 11 | echo "Run code coverage reports ..." 12 | sh -xe scripts/code-coverage-report.sh 13 | 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: python 4 | 5 | python: 6 | - "2.7" 7 | - "3.4" 8 | - "3.5" 9 | - "3.6" 10 | - "3.7-dev" 11 | 12 | install: 13 | - pip install unittest2 14 | - pip install coverage 15 | - pip install pycodestyle 16 | - pip install mock 17 | - pip install jmespath 18 | 19 | 20 | script: 21 | - sh -xe scripts/test.sh 22 | 23 | after_success: 24 | - bash <(curl -s https://codecov.io/bash) 25 | -------------------------------------------------------------------------------- /scripts/code-style-check.sh: -------------------------------------------------------------------------------- 1 | #pycodestyle --statistics alibabacloud/ --max-line-length=100 --ignore=W391,E121,E123,E126,E226,E24,E704,W503,W504 --exclude=DescribeEndpointsRequest.py,vendored,clients,services 2 | pycodestyle --statistics tests/ --max-line-length=100 --ignore=W391,E121,E123,E126,E226,E24,E704,W503,W504 3 | pycodestyle --statistics python-function-test/ --max-line-length=100 --ignore=W391,E121,E123,E126,E226,E24,E704,W503,W504 4 | 5 | -------------------------------------------------------------------------------- /docs/source/advance/credentials/04_instance.rst: -------------------------------------------------------------------------------- 1 | .. _instance-credentials: 2 | 3 | 实例凭证配置 4 | -------------- 5 | 6 | 使用实例凭证,该实例必须是\ **专有网络**\ 下配置了\ **RAMRole**\ 的ECS实例,配置方式参照:\ `使用 7 | RAM 对云服务器 ECS 8 | 进行权限管理 `__ 9 | 10 | 在该实例的环境变量配置 ``ALIBABA_CLOUD_ROLE_NAME`` 11 | ,即可通过该实例实现无AK访问阿里云的资源和服务。 12 | 13 | 环境变量配置以 Linux 为例: 14 | 15 | .. code:: 16 | 17 | export ALIBABA_CLOUD_ROLE_NAME= YourRamRoleName 18 | -------------------------------------------------------------------------------- /docs/source/reference/03_api.rst: -------------------------------------------------------------------------------- 1 | API文档 2 | ========== 3 | 4 | .. module:: alibabacloud 5 | 6 | 获取Client 7 | -------------- 8 | 9 | .. autofunction:: alibabacloud.get_client 10 | 11 | 获取Resource 12 | --------------- 13 | .. autofunction:: alibabacloud.get_resource 14 | 15 | Client 基类 16 | ------------------- 17 | .. autoclass:: alibabacloud.client.AlibabaCloudClient 18 | 19 | Config 类 20 | ------------------- 21 | .. autoclass:: alibabacloud.client.ClientConfig 22 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/__version__.py: -------------------------------------------------------------------------------- 1 | # .-. .-. .-. . . .-. .-. .-. .-. 2 | # |( |- |.| | | |- `-. | `-. 3 | # ' ' `-' `-`.`-' `-' `-' ' `-' 4 | 5 | __title__ = 'requests' 6 | __description__ = 'Python HTTP for Humans.' 7 | __url__ = 'http://python-requests.org' 8 | __version__ = '2.18.3' 9 | __build__ = 0x021803 10 | __author__ = 'Kenneth Reitz' 11 | __author_email__ = 'me@kennethreitz.org' 12 | __license__ = 'Apache 2.0' 13 | __copyright__ = 'Copyright 2017 Kenneth Reitz' 14 | __cake__ = u'\u2728 \U0001f370 \u2728' 15 | -------------------------------------------------------------------------------- /docs/source/advance/credentials/02_env.rst: -------------------------------------------------------------------------------- 1 | 环境变量配置 2 | --------------- 3 | 4 | ``Alibaba Cloud Python SDK`` 将检查您环境变量当中的访问秘钥: 5 | 6 | ``ALIBABA_CLOUD_ACCESS_KEY_ID``\ :您的访问密钥AccessKeyID 7 | 8 | ``ALIBABA_CLOUD_ACCESS_KEY_SECRET``\ :您的访问密钥AccessKeySecret 9 | 10 | **访问秘钥** 11 | 访问秘钥的获取参照:\ `AccessKey `__ 12 | 13 | 环境变量配置 14 | ^^^^^^^^^^^^^^^ 15 | 16 | 以Linux为例 17 | 18 | .. code:: 19 | 20 | $ export ALIBABA_CLOUD_ACCESS_KEY_ID= 21 | $ export ALIBABA_CLOUD_ACCESS_KEY_SECRET= 22 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/certs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | requests.certs 6 | ~~~~~~~~~~~~~~ 7 | 8 | This module returns the preferred default CA certificate bundle. There is 9 | only one — the one from the certifi package. 10 | 11 | If you are packaging Requests, e.g., for a Linux distribution or a managed 12 | environment, you can change the definition of where() to return a separately 13 | packaged CA bundle. 14 | """ 15 | import os.path 16 | 17 | from .packages.certifi import where 18 | 19 | if __name__ == '__main__': 20 | print(where()) 21 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | # This code exists for backwards compatibility reasons. 4 | # I don't like it either. Just look the other way. :) 5 | 6 | for package in ('urllib3', 'idna', 'chardet'): 7 | locals()[package] = __import__(package) 8 | # This traversal is apparently necessary such that the identities are 9 | # preserved (requests.packages.urllib3.* is urllib3.*) 10 | for mod in list(sys.modules): 11 | if mod == package or mod.startswith(package + '.'): 12 | sys.modules['requests.packages.' + mod] = sys.modules[mod] 13 | 14 | # Kinda cool, though, right? 15 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SOURCEDIR = source 8 | BUILDDIR = build 9 | 10 | # Put it first so that "make" without argument is like "make help". 11 | help: 12 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 13 | 14 | .PHONY: help Makefile 15 | 16 | # Catch-all target: route all unknown targets to Sphinx using the new 17 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 18 | %: Makefile 19 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | 阿里云 Python SDK 使用文档 2 | ################################ 3 | ``Alibaba Cloud Python SDK`` 包含 ECS、RDS、SLB、RAM、VPC、CDN 等在内的 ``client`` 功能和更高级的封装资源可用。 4 | 通过使用它,开发人员可以更便捷的管理其相应资源,并获得比当前的 ``aliyun-openapi-python-sdk`` 具有更好的编程体验。 5 | 6 | 7 | .. toctree:: 8 | :maxdepth: 2 9 | :glob: 10 | 11 | quickstart/index 12 | advance/index 13 | higher/index 14 | reference/index 15 | questions/index 16 | 17 | 18 | Introduction 19 | ################################ 20 | This is the introduction of demo。 21 | 22 | Indices and tables 23 | ################################ 24 | * :ref:`genindex` 25 | * :ref:`modindex` 26 | * :ref:`search` -------------------------------------------------------------------------------- /alibabacloud/retry/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /alibabacloud/resources/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /docs/source/reference/02_resource.rst: -------------------------------------------------------------------------------- 1 | .. _usage-resources: 2 | 3 | 可用资源 4 | ============ 5 | 6 | .. module:: alibabacloud 7 | 8 | 9 | ECS 资源类 10 | -------------------- 11 | .. autoclass:: alibabacloud.services.ecs.ECSResource 12 | .. autoclass:: alibabacloud.services.ecs.ECSInstanceResource 13 | .. autoclass:: alibabacloud.services.ecs.ECSInstanceFullStatus 14 | .. autoclass:: alibabacloud.services.ecs.ECSDiskResource 15 | .. autoclass:: alibabacloud.services.ecs.ECSImageResource 16 | .. autoclass:: alibabacloud.services.ecs.ECSSystemEventResource 17 | 18 | 19 | SLB 资源类 20 | -------------------- 21 | .. autoclass:: alibabacloud.services.slb.SLBResource 22 | 23 | 24 | VPC 资源类 25 | -------------------- 26 | .. autoclass:: alibabacloud.services.vpc.VPCResource -------------------------------------------------------------------------------- /tests/mock_data/eip_addres.json: -------------------------------------------------------------------------------- 1 | { 2 | "PageNumber":"1", 3 | "EipAddresses":{ 4 | "EipAddress":{ 5 | "ChargeType":"PostPaid", 6 | "Status":"Available", 7 | "RegionId":"cn-beijing", 8 | "ResourceGroupId":"rg-acfmxazb4ph6aiy", 9 | "AllocationTime":"2018-01-15T11:17:30Z", 10 | "IpAddress":"59.110.xx.xx", 11 | "AllocationId":"eip-2ze88m67qx5zxxxxx", 12 | "AvailableRegions":{ 13 | "AvailableRegion":"cn-beijing" 14 | }, 15 | "InternetChargeType":"PayByTraffic", 16 | "Bandwidth":"1" 17 | } 18 | }, 19 | "TotalCount":"1", 20 | "PageSize":"10", 21 | "RequestId":"7EEF2D6B-D207-4197-AE37-01279C888757" 22 | } -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | try: 4 | # Our match_hostname function is the same as 3.5's, so we only want to 5 | # import the match_hostname function if it's at least that good. 6 | if sys.version_info < (3, 5): 7 | raise ImportError("Fallback to vendored code") 8 | 9 | from ssl import CertificateError, match_hostname 10 | except ImportError: 11 | try: 12 | # Backport of the function from a pypi module 13 | from backports.ssl_match_hostname import CertificateError, match_hostname 14 | except ImportError: 15 | # Our vendored copy 16 | from ._implementation import CertificateError, match_hostname 17 | 18 | # Not needed, but documenting what we provide. 19 | __all__ = ('CertificateError', 'match_hostname') 20 | -------------------------------------------------------------------------------- /docs/source/advance/client/02_timeout.rst: -------------------------------------------------------------------------------- 1 | 超时 2 | ----- 3 | 4 | ``Alibaba Cloud Python SDK`` 超时分为连接超时( ``connection_timeout`` 5 | )和读超时( ``read_timeout`` )。 6 | 7 | **connection_timeout:** 8 | 连接超时。TCP建立连接的时间阈值,单位为秒。默认5秒 9 | 10 | **read_timeout :** 11 | 读超时。 客户端接收到服务端响应的时间阈值,单位为秒。默认10秒 12 | 13 | 例如,您想自定义超时时间,请使用以下代码。 14 | 15 | .. code:: python 16 | 17 | from alibabacloud import get_client, ClientConfig 18 | 19 | client_config = ClientConfig(connection_timeout=10, read_timeout=20) 20 | # 创建ecs client 21 | ecs_client = get_client('ecs', access_key_id=access_key_id, 22 | access_key_secret=access_key_secret, 23 | region_id='cn-hangzhou', 24 | config=client_config) 25 | response = ecs_client.describe_regions() 26 | print(response) 27 | 28 | 我们提供了多种方式的配置超时,参照 ::ref:`handle-client` 29 | -------------------------------------------------------------------------------- /alibabacloud/session.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # TODO the Session interface needs to be specified 16 | 17 | 18 | class Session: 19 | 20 | def __init__(self): 21 | pass 22 | 23 | def get_client(self, service_name, client_config): 24 | pass 25 | -------------------------------------------------------------------------------- /docs/source/advance/02_credentials.rst: -------------------------------------------------------------------------------- 1 | .. _credentials-config: 2 | 3 | 使用Alibaba Cloud Python SDK 凭证 4 | ==================================== 5 | 6 | ``Alibaba Cloud Python SDK`` 7 | 有两种类型的凭证数据:凭证提供者(\ ``credentials_provider``\ )和凭证(\ ``credentials`` 8 | )。 9 | 10 | **凭证提供者( credentials_provider ):** ``credentials_ovider`` 11 | 是您存放凭证相关信息的位置,\ ``Alibaba Cloud Python SDK`` 寻址 12 | ``credentials_provider`` 链,获取凭证( ``credentials`` )后立即停止。 13 | 14 | **凭证( credentials ):** ``credentials`` 是 ``client`` 15 | 发送API请求必须携带的凭证,\ ``Alibaba Cloud`` 16 | 以此验证您是否是阿里云的合法用户。 凭证包含\ ``access_key_id`` , 17 | ``access_key_secret``\ ,\ ``security_token`` 以及 ``bearer_token`` 18 | 等3种凭证。 19 | 20 | ``Alibaba Cloud Python SDK`` 搜索 ``credentials_provider`` 链 的顺序是: 21 | 22 | .. toctree:: 23 | :maxdepth: 2 24 | 25 | credentials/01_func 26 | credentials/02_env 27 | credentials/03_file 28 | credentials/04_instance 29 | -------------------------------------------------------------------------------- /docs/source/advance/client/05_retry.rst: -------------------------------------------------------------------------------- 1 | 重试 2 | --------- 3 | 4 | ``Alibaba Cloud Python SDK`` 对当前仅对 ECS 产品的API 5 | 设置了默认重试。但是您可以在配置当中关闭默认重试或者定制自己的重试策略。 6 | 7 | **max\ retry\ times**\ :单个请求的最大重试次数。默认为3次。 8 | **enable_retry**\ :是否重试的开关,默认True开启。一旦关闭,则该 client 9 | 下所有请求不重试,\ ``max_retry_times`` 配置将不启用。 10 | 11 | 例如,您想自定义是否重试,请使用以下代码。 12 | 13 | .. code:: python 14 | 15 | from alibabacloud import get_client, ClientConfig 16 | # 您也可以配置enable_retry=false,关闭默认的重试 17 | client_config = ClientConfig(max_retry_times=5) 18 | # 创建ecs client 19 | ecs_client = get_client('ecs', access_key_id=access_key_id, 20 | access_key_secret=access_key_secret, 21 | region_id='cn-hangzhou', 22 | config=client_config) 23 | response = ecs_client.describe_regions() 24 | print(response) 25 | 26 | 当然,您也可以使用其他方式配置重试,参照 ::ref:`handle-retry` 27 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=source 11 | set BUILDDIR=build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /alibabacloud/utils/protocol_type.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | 19 | HTTP = "http" 20 | HTTPS = "https" 21 | -------------------------------------------------------------------------------- /docs/source/advance/client/04_header.rst: -------------------------------------------------------------------------------- 1 | 自定制请求头 2 | ------------- 3 | 4 | ``Alibaba Cloud Python SDK`` 5 | 为客户端发送的每一个请求自定义请求头 `User-Agent` 。默认的 `User-Agent` 6 | 包含您的Python版本以及 ``Alibaba Cloud Python SDK`` 的版本信息。 7 | 我们同样支持您 **追加** 自己的 `User-Agent` 信息。 8 | 9 | 例如,淘宝公司想定制自己的 `User-Agent` ,请使用以下代码,\ *当前仅支持追加*\ 。 10 | 11 | .. code:: python 12 | 13 | from alibabacloud import get_client, ClientConfig 14 | 15 | client_config = ClientConfig(user_agent="taobao/1.3.2") 16 | 17 | ecs_client = get_client('ecs', access_key_id=access_key_id, 18 | access_key_secret=access_key_secret, 19 | region_id='cn-hangzhou', 20 | config=client_config) 21 | response = ecs_client.describe_regions() 22 | # 请求User-Agent 为:AlibabaCloud (Windows 10;AMD64) Python/3.7.2 Alibabacloud/0.4.4 python-requests/2.18.3 taobao/1.3.2 23 | 24 | 追加 `User-Agent` 的配置方式有多种,参照 ::ref:`handle-client` 25 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/hooks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.hooks 5 | ~~~~~~~~~~~~~~ 6 | 7 | This module provides the capabilities for the Requests hooks system. 8 | 9 | Available hooks: 10 | 11 | ``response``: 12 | The response generated from a Request. 13 | """ 14 | HOOKS = ['response'] 15 | 16 | 17 | def default_hooks(): 18 | return dict((event, []) for event in HOOKS) 19 | 20 | # TODO: response is the only one 21 | 22 | 23 | def dispatch_hook(key, hooks, hook_data, **kwargs): 24 | """Dispatches a hook dictionary on a given piece of data.""" 25 | hooks = hooks or dict() 26 | hooks = hooks.get(key) 27 | if hooks: 28 | if hasattr(hooks, '__call__'): 29 | hooks = [hooks] 30 | for hook in hooks: 31 | _hook_data = hook(hook_data, **kwargs) 32 | if _hook_data is not None: 33 | hook_data = _hook_data 34 | return hook_data 35 | -------------------------------------------------------------------------------- /alibabacloud/utils/validation.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.exceptions import ParamTypeInvalidException 16 | 17 | 18 | def assert_integer_positive(integer, name): 19 | if isinstance(integer, int) and integer > 0: 20 | return 21 | raise ParamTypeInvalidException(param=name, param_type='positive integer') 22 | -------------------------------------------------------------------------------- /alibabacloud/endpoint/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with self work for additional information 4 | # regarding copyright ownership. The ASF licenses self file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use self file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | 19 | class EndpointResolver(object): 20 | 21 | def resolve(self, request): 22 | pass 23 | -------------------------------------------------------------------------------- /alibabacloud/utils/method_type.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | 19 | GET = "GET" 20 | PUT = "PUT" 21 | POST = "POST" 22 | DELETE = "DELETE" 23 | HEAD = "HEAD" 24 | OPTIONS = "OPTIONS" 25 | -------------------------------------------------------------------------------- /alibabacloud/utils/load_json_from_data_dir.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import json 16 | import os.path 17 | import alibabacloud 18 | 19 | 20 | def _load_json_from_data_dir(basename): 21 | base_dir = os.path.dirname(os.path.abspath(alibabacloud.__file__)) 22 | json_file = os.path.join(base_dir, "data", basename) 23 | with open(json_file) as fp: 24 | return json.loads(fp.read()) 25 | -------------------------------------------------------------------------------- /docs/source/advance/credentials/01_func.rst: -------------------------------------------------------------------------------- 1 | 方法参数显示传递 2 | ----------------- 3 | 4 | 显式传递方式存在硬编码以及安全问题,请您慎重使用,并保管好自己的 5 | AccessKey 6 | 7 | get_client方法显式传递凭证信息 8 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 9 | 10 | 即 ``access_key_id`` 和 ``access_key_secret`` 11 | 12 | .. code:: python 13 | 14 | import alibabacloud 15 | client = alibabacloud.get_client(service_name='Ecs', 16 | access_key_id=access_key_id, 17 | access_key_secret=access_key_secret, 18 | region_id="cn-hangzhou") 19 | 20 | get_resource方法显式传递凭证信息 21 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 22 | 23 | 即 ``access_key_id`` 和 ``access_key_secret`` 24 | 25 | .. code:: python 26 | 27 | import alibabacloud 28 | resource = alibabacloud.get_resource(service_name='Ecs', 29 | access_key_id=access_key_id, 30 | access_key_secret=access_key_secret, 31 | region_id="cn-hangzhou") 32 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/certifi/core.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | certifi.py 6 | ~~~~~~~~~~ 7 | 8 | This module returns the installation location of cacert.pem. 9 | """ 10 | import os 11 | import warnings 12 | 13 | 14 | class DeprecatedBundleWarning(DeprecationWarning): 15 | """ 16 | The weak security bundle is being deprecated. Please bother your service 17 | provider to get them to stop using cross-signed roots. 18 | """ 19 | 20 | 21 | def where(): 22 | f = os.path.dirname(__file__) 23 | 24 | return os.path.join(f, 'cacert.pem') 25 | 26 | 27 | def old_where(): 28 | warnings.warn( 29 | "The weak security bundle has been removed. certifi.old_where() is now an alias " 30 | "of certifi.where(). Please update your code to use certifi.where() instead. " 31 | "certifi.old_where() will be removed in 2018.", 32 | DeprecatedBundleWarning 33 | ) 34 | return where() 35 | 36 | if __name__ == '__main__': 37 | print(where()) 38 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | import datetime 15 | import time 16 | 17 | 18 | def epoch_time_to_timestamp(epoch_time): 19 | epoch_time += time.timezone 20 | return datetime.datetime.fromtimestamp(float(epoch_time)).strftime('%Y-%m-%dT%H:%M:%SZ') 21 | 22 | 23 | def timestamp_to_epoch_time(timestamp, time_format="%Y-%m-%dT%H:%M:%SZ"): 24 | return time.mktime( 25 | datetime.datetime.strptime(timestamp, time_format).timetuple() 26 | ) - time.timezone 27 | -------------------------------------------------------------------------------- /docs/source/higher/05_exceptions.rst: -------------------------------------------------------------------------------- 1 | 异常处理 2 | ======== 3 | 4 | ``Alibaba Cloud Python SDK`` 提供了一系列的异常帮助您排查您的应用在执行当中 5 | 6 | 7 | AlibabaCloudException及其子类 8 | ----------------------------- 9 | 10 | ``AlibabaCloudException`` 指示在尝试将请求发送到 阿里云 11 | 或者在尝试解析来自 阿里云 12 | 的响应时,客户端代码内出现问题。在一般情况下,``AlibabaCloudException`` 比 13 | ``ServerException`` 严重,前者指示出现严重问题,导致客户端无法对 阿里云 服务进行服务调用。在某些情况下,会引发 ``AlibabaCloudException`` 14 | 的一个子类,使开发人员能够通过捕获模块精细控制如何处理错误情况。 15 | 16 | 例如,如果您在尝试对一个客户端执行操作时网络连接不可用,\ ``Alibaba Cloud Python SDK``\ 会引发 17 | ``HttpErrorException``。 18 | 19 | 20 | ServerException 21 | --------------- 22 | 23 | ``ServerException`` 24 | 是在使用\ ``Alibaba Cloud Python SDK``\ 时最常遇到的异常。该异常是指来自Alibaba 25 | Cloud 服务的错误响应。例如,如果您尝试终止不存在的 ECS 实例,ECS 26 | 会返回错误响应,而且引发的 ``ServerException`` 27 | 中会包含该错误响应的所有详细信息。 28 | 29 | 当您遇到 ``ServerException`` 时,您就会知道,您的请求已成功发送到阿里云 30 | 服务,但无法成功处理。这可能是因为请求的参数中存在错误,或者是因为服务端的问题。 31 | 32 | ``ServerException`` 为您提供很多信息,例如: 33 | 34 | - 返回的 HTTP 状态代码 35 | 36 | - 调用API的产品code 37 | 38 | - 解析到的endpoint 39 | 40 | - 返回的 Alibaba Cloud 错误代码 41 | 42 | - 来自服务的详细错误消息 43 | 44 | - 已失败请求的 请求 ID 45 | -------------------------------------------------------------------------------- /alibabacloud/resources/base.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from alibabacloud.vendored.six import iteritems 15 | from alibabacloud.utils.utils import _convert_name_from_camel_case_to_snake_case 16 | 17 | 18 | class ServiceResource(object): 19 | 20 | def __init__(self, service_name, _client=None): 21 | self._service_name = service_name 22 | self._client = _client 23 | 24 | def _assign_attributes(self, attrs): 25 | for key, value in iteritems(attrs): 26 | setattr(self, _convert_name_from_camel_case_to_snake_case(key), value) 27 | -------------------------------------------------------------------------------- /docs/source/quickstart/usage/01_client.rst: -------------------------------------------------------------------------------- 1 | 客户端使用 2 | ----------- 3 | 4 | 客户端( ``client`` )是 ``Alibaba Cloud Python SDK`` 5 | 比较底层的实现,您构造的所有的API请求或者服务都通过 ``client`` 来实现。 6 | 7 | 8 | 创建服务客户端 9 | ^^^^^^^^^^^^^^^^^ 10 | 11 | 要访问 ``Alibaba Cloud Python SDK`` 的服务或资源,您需要创建一个客户端( 12 | ``client``)。创建的时候,您需要指定 访问凭证 13 | 、地域和可用区(``region_id`` )以及即将访问的 service 。 14 | 15 | **访问凭证:** 16 | 访问凭证相当于您在阿里云的身份标识。为了您的账号安全,我们强烈建议您使用 ::ref:`instance-credentials` 。 17 | 当然,您也可以使用其他凭证,详情参考 ::ref:`credentials-config` 18 | 19 | **region_id:** region_id 20 | 是您创建资源的所在区域,查找参考 \ `地域和可用区 `_ 21 | 22 | **service:** service 23 | 是您即将访问的服务,可用服务参照 ::ref:`usage-client` 24 | 25 | .. code:: python 26 | 27 | from alibabacloud import get_client 28 | # 创建一个ecs client 29 | ecs_client = get_client('ecs', access_key_id=your_access_key_id, 30 | access_key_secret=your_access_key_secret, 31 | region_id=your_region_id) 32 | 33 | 创建 ``client`` 后,您可以通过该 ``client`` 调用其提供的API: 34 | 35 | .. code:: python 36 | 37 | result = ecs_client.describe_regions() 38 | print(result.get("Regions")) # 获取alibabacloud全球19个region 39 | -------------------------------------------------------------------------------- /alibabacloud/handlers/credentials_handler.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.handlers import RequestHandler 16 | from alibabacloud.exceptions import NoCredentialsException 17 | 18 | 19 | class CredentialsHandler(RequestHandler): 20 | 21 | def handle_request(self, context): 22 | if context.http_request.credentials is None: 23 | credentials = context.client.credentials_provider.provide() 24 | if not credentials: 25 | raise NoCredentialsException() 26 | context.http_request.credentials = credentials 27 | -------------------------------------------------------------------------------- /docs/source/quickstart/usage/02_resource.rst: -------------------------------------------------------------------------------- 1 | 资源使用 2 | -------------- 3 | 4 | 资源( ``resource`` ) 代表 ``Alibaba Cloud Python SDK`` 5 | 面向对象的接口,提供比 ``client`` 进行的原始低级调用更高级别的抽象接口。 6 | 7 | 创建服务资源 8 | ^^^^^^^^^^^^^^^^^^^ 9 | 10 | 要访问 ``Alibaba Cloud Python SDK`` 的资源,您需要创建该资源对象( 11 | ``resource`` 12 | )。创建的时候,您需要指定 访问凭证 以及地域和可用区( 13 | ``region_id``\ ) 以及即将访问的 resource。 14 | 15 | **访问凭证:** 16 | 访问凭证相当于您在阿里云的身份标识。为了您的账号安全,我们强烈建议您使用 ::ref:`instance-credentials` 。 17 | 当然,您也可以使用其他凭证,详情参考 ::ref:`credentials-config` 18 | 19 | **region_id:** region_id 20 | 是您创建资源的所在区域,查找参考: \ `地域和可用区 `_ 21 | 22 | **resource:** resource 23 | 是您即将访问的资源,可用资源参照 ::ref:`usage-resources` 24 | 25 | .. code:: python 26 | 27 | import alibabacloud 28 | # 创建ecs资源 29 | ecs_resource = alibabacloud.get_resource('ecs', access_key_id=access_key_id, 30 | access_key_secret=access_key_secret, 31 | region_id=region_id) 32 | 33 | 创建 ``resource`` 后,您可以通过该 ``resource`` 操作其对应服务: 34 | 35 | .. code:: python 36 | 37 | for instance in ecs_resource.instances.all(): 38 | print(instance.instance_id) 39 | -------------------------------------------------------------------------------- /docs/source/advance/client/03_proxy.rst: -------------------------------------------------------------------------------- 1 | 代理 2 | ---------- 3 | 4 | ``Alibaba Cloud Python SDK`` 支持用户使用网络代理。代理分为HTTP代理( 5 | ``http_proxy`` )和HTTPS代理( ``https_proxy`` 6 | )。如果您想使用代理,参照以下的使用方式 7 | 8 | config接口显式传递 9 | ^^^^^^^^^^^^^^^^^^^ 10 | 11 | .. code:: python 12 | 13 | from alibabacloud import get_client, ClientConfig 14 | 15 | 16 | client_config = ClientConfig(http_proxy="http://...",https_proxy="https://...") 17 | ecs_client = get_client('ecs', access_key_id=access_key_id, 18 | access_key_secret=access_key_secret, 19 | region_id='cn-hangzhou', 20 | config=client_config) 21 | response = ecs_client.describe_regions() 22 | print(response) 23 | 24 | 我们提供多种方式配置代理,参照 ::ref:`handle-client` 25 | 26 | 27 | 配置文件 28 | ^^^^^^^^^^^^^^^^^^^ 29 | 30 | 您也可以在配置文件进行配置环境变量,参照 ::ref:`handle-client` 31 | 32 | 33 | 环境变量 34 | ^^^^^^^^^^^^^^^^^^^ 35 | 36 | 阿里云 Python SDK支持从环境变量读取代理相关的配置: 37 | 38 | `HTTP_PROXY`: HTTP代理 39 | 40 | `HTTPS_PROXY`: HTTPS代理 41 | 42 | 以Linux为例,配置方式: 43 | 44 | .. code:: 45 | 46 | $ export ALIBABA_CLOUD_ACCESS_KEY_ID= 47 | $ export ALIBABA_CLOUD_ACCESS_KEY_SECRET= 48 | -------------------------------------------------------------------------------- /docs/source/advance/logger/01_console.rst: -------------------------------------------------------------------------------- 1 | 生成控制台日志 2 | --------------------- 3 | 4 | 日志文件,我们使用logging模块下的 ``RotatingFileHandler`` , 单文件最大字节为 10M ,备份文件为 5 个。 5 | 因此,使用我们默认的日志文件配置,请确保磁盘最低有 60M 可用空间。 6 | 7 | client创建控制台日志 8 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 9 | 10 | 使用 ``Alibaba Cloud Python SDK`` 创建的 Client 创建控制台日志 11 | 12 | .. code:: python 13 | 14 | from alibabacloud import get_client 15 | client = get_client('ecs', access_key_id=access_key_id, 16 | access_key_secret=access_key_secret, 17 | region_id='cn-hangzhou') 18 | client.add_stream_log_handler() 19 | 20 | resource创建控制台日志 21 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 22 | 23 | 使用 ``Alibaba Cloud Python SDK`` 创建的 Resource 创建控制台日志 24 | 25 | .. code:: python 26 | 27 | from alibabacloud import get_resource 28 | 29 | ecs_resource = get_resource('ecs', access_key_id=access_key_id, 30 | access_key_secret=access_key_secret, 31 | region_id='cn-hangzhou', enable_stream_logger=True) 32 | 33 | 当然,您还可以选择可选配置参数,修改输出日志的格式: 34 | stream\ *log*\ level:Logging level, 比如: ``logging.INFO`` 35 | stream\ *log*\ name:日志名字 stream=None, 36 | stream\ *format*\ string:日志信息输出格式 37 | -------------------------------------------------------------------------------- /docs/source/questions/01_pyinstaller.rst: -------------------------------------------------------------------------------- 1 | PyInstaller 打包出现【No such file or directory】 2 | ================================================= 3 | 4 | 不少用户在Windows平台下使用\ ``PyInstaller`` 打包自己通过 5 | ``Alibaba Cloud Python SDK`` 6 | 构造的应用,都会出现\ ``FileNotFoundError:No such file or directory:'...\retry_config.json'`` 7 | 这样的问题。 8 | 9 | 10 | 原因 11 | --------------- 12 | 13 | 该问题产生的原因是\ ``Alibaba Cloud Python SDK`` 14 | 使用了\ ``__file__``\ 来获取\ ``retry_config.json``\ 文件的完整路径,然而\ ``PyInstaller`` 15 | 在打包期间冻结二进制文件,\ ``PyInstaller`` 16 | 搜索的相对路径是针对自己的打包文件bundle文件,因此\ ``PyInstaller`` 打包 17 | ``Alibaba Cloud Python SDK`` 构造的应用会出现以上错误。 18 | 19 | 20 | 解决方案: 21 | --------------- 22 | 23 | 24 | 1,使用py2exe 或者 freeze 来代替PyInstaller 25 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 26 | 27 | 当前有三种方式生成冻结二进制 28 | 29 | - `py2exe `__ ,仅支持在Windows下使用 30 | 31 | - `freeze `__ 最初始的版本 32 | 33 | - `PyInstaller `__ 34 | ,和py2exe类似,它能够在Linux及Unix上使用,并且能够生成自安装的二进制文件 35 | 36 | 37 | 2,PyInstaller 提供的方法 38 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 39 | 40 | ``PyInstaller``\ 针对 41 | ``__file__``\ 提供了解决方案:https://pyinstaller.readthedocs.io/en/stable/spec-files.html#adding-files-to-the-bundle 42 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/_internal_utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests._internal_utils 5 | ~~~~~~~~~~~~~~ 6 | 7 | Provides utility functions that are consumed internally by Requests 8 | which depend on extremely few external helpers (such as compat) 9 | """ 10 | 11 | from .compat import is_py2, builtin_str, str 12 | 13 | 14 | def to_native_string(string, encoding='ascii'): 15 | """Given a string object, regardless of type, returns a representation of 16 | that string in the native string type, encoding and decoding where 17 | necessary. This assumes ASCII unless told otherwise. 18 | """ 19 | if isinstance(string, builtin_str): 20 | out = string 21 | else: 22 | if is_py2: 23 | out = string.encode(encoding) 24 | else: 25 | out = string.decode(encoding) 26 | 27 | return out 28 | 29 | 30 | def unicode_is_ascii(u_string): 31 | """Determine if unicode string only contains ASCII characters. 32 | 33 | :param str u_string: unicode string to check. Must be unicode 34 | and not Python 2 `str`. 35 | :rtype: bool 36 | """ 37 | assert isinstance(u_string, str) 38 | try: 39 | u_string.encode('ascii') 40 | return True 41 | except UnicodeEncodeError: 42 | return False 43 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/compat.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # Contributor(s): 3 | # Dan Blanchard 4 | # Ian Cordasco 5 | # 6 | # This library is free software; you can redistribute it and/or 7 | # modify it under the terms of the GNU Lesser General Public 8 | # License as published by the Free Software Foundation; either 9 | # version 2.1 of the License, or (at your option) any later version. 10 | # 11 | # This library is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | # Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public 17 | # License along with this library; if not, write to the Free Software 18 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 19 | # 02110-1301 USA 20 | ######################### END LICENSE BLOCK ######################### 21 | 22 | import sys 23 | 24 | 25 | if sys.version_info < (3, 0): 26 | PY2 = True 27 | PY3 = False 28 | base_str = (str, unicode) 29 | text_type = unicode 30 | else: 31 | PY2 = False 32 | PY3 = True 33 | base_str = (bytes, str) 34 | text_type = str 35 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/urllib3/util/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | # For backwards compatibility, provide imports that used to be here. 3 | from .connection import is_connection_dropped 4 | from .request import make_headers 5 | from .response import is_fp_closed 6 | from .ssl_ import ( 7 | SSLContext, 8 | HAS_SNI, 9 | IS_PYOPENSSL, 10 | IS_SECURETRANSPORT, 11 | assert_fingerprint, 12 | resolve_cert_reqs, 13 | resolve_ssl_version, 14 | ssl_wrap_socket, 15 | ) 16 | from .timeout import ( 17 | current_time, 18 | Timeout, 19 | ) 20 | 21 | from .retry import Retry 22 | from .url import ( 23 | get_host, 24 | parse_url, 25 | split_first, 26 | Url, 27 | ) 28 | from .wait import ( 29 | wait_for_read, 30 | wait_for_write 31 | ) 32 | 33 | __all__ = ( 34 | 'HAS_SNI', 35 | 'IS_PYOPENSSL', 36 | 'IS_SECURETRANSPORT', 37 | 'SSLContext', 38 | 'Retry', 39 | 'Timeout', 40 | 'Url', 41 | 'assert_fingerprint', 42 | 'current_time', 43 | 'is_connection_dropped', 44 | 'is_fp_closed', 45 | 'get_host', 46 | 'parse_url', 47 | 'make_headers', 48 | 'resolve_cert_reqs', 49 | 'resolve_ssl_version', 50 | 'split_first', 51 | 'ssl_wrap_socket', 52 | 'wait_for_read', 53 | 'wait_for_write' 54 | ) 55 | -------------------------------------------------------------------------------- /docs/source/advance/logger/02_file.rst: -------------------------------------------------------------------------------- 1 | 生成文件日志 2 | --------------- 3 | 4 | 5 | Client 创建文件日志 6 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 7 | 8 | 使用 ``Alibaba Cloud Python SDK`` 创建的 Client 在当前目录下创建一个名为 9 | ``ecs.log`` 的日志文件 10 | 11 | .. code:: python 12 | 13 | from alibabacloud import get_client 14 | client = get_client('ecs', access_key_id=access_key_id, 15 | access_key_secret=access_key_secret, 16 | region_id='cn-hangzhou') 17 | ecs_client.add_rotating_file_log_handler(path="ecs.log") 18 | 19 | 20 | Resource 创建文件日志 21 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 22 | 23 | 使用 ``Alibaba Cloud Python SDK`` 创建的 Resource 24 | 在当前目录下创建一个名为 ``ecs.log`` 的日志文件 25 | 26 | .. code:: python 27 | 28 | from alibabacloud import get_resource 29 | 30 | ecs_resource = get_resource('ecs', access_key_id=access_key_id, 31 | access_key_secret=access_key_secret, 32 | region_id='cn-hangzhou', enable_file_logger=True, 33 | file_logger_path="ecs.log") 34 | 35 | 当然,您还可以选择可选配置参数,修改输出日志的格式: 36 | file\ *log*\ level:Logging level, 比如: ``logging.INFO`` 37 | file\ *log*\ name:日志名称 file\ *logger*\ path:文件日志位置 38 | file\ *maxBytes:文件最大字节数,默认10485760字节 39 | file*\ backupCount:最多保存的文件个数,默认5个文件 40 | file\ *logger*\ format_string:日志信息输出格式 41 | -------------------------------------------------------------------------------- /alibabacloud/retry/retry_policy_context.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.retry.retry_condition import RetryCondition 16 | 17 | import logging 18 | 19 | logger = logging.getLogger(__name__) 20 | 21 | 22 | class RetryPolicyContext: 23 | 24 | def __init__(self, original_request, exception, retries_attempted, http_status_code, 25 | product_code, api_version, logger=logger): 26 | self.original_request = original_request 27 | self.exception = exception 28 | self.retries_attempted = retries_attempted 29 | self.http_status_code = http_status_code 30 | self.retryable = RetryCondition.BLANK_STATUS 31 | self.product_info = (product_code, api_version) 32 | self.logger = logger 33 | -------------------------------------------------------------------------------- /docs/source/higher/01_retry.rst: -------------------------------------------------------------------------------- 1 | .. _handle-retry: 2 | 3 | 管理重试策略 4 | =============== 5 | 6 | ``Alibaba Cloud Python SDK`` 提供默认的重试和退避策略,由 7 | ``Alibaba Cloud`` 定义为可重试 API,\ ``Alibaba Cloud Python SDK`` 8 | 才允许重试,重试当前仅支持 ECS 产品。\ **除 ECS 外的其他产品,当前均不支持重试。** 9 | 10 | 11 | 默认重试策略 12 | ------------------------------- 13 | 14 | (API文档) 15 | 16 | 17 | 用户自定义重试策略 18 | ------------------------------- 19 | 20 | 您自定义的重试策略需要实现一个 ``should_retry`` 的接口。 21 | 22 | 例如,您想自定义一个名为 ``CustomRetryPolicy`` 的重试策略,可以参照以下代码: 23 | 24 | .. code:: python 25 | 26 | class CustomRetryPolicy(object): 27 | def __init__(self): 28 | pass 29 | 30 | def should_retry(self, retry_policy_context): 31 | pass 32 | 33 | 34 | 使用用户自定义的重试策略 35 | ------------------------------- 36 | 例如, 您自定义了一个名为 ``CustomRetryPolicy`` 的重试策略,您可以使用以下方式引用它,替代我们默认的重试策略。 37 | 38 | .. code:: python 39 | 40 | from alibabacloud import get_client, ClientConfig 41 | 42 | client_config = ClientConfig(connection_timeout=10, read_timeout=20) 43 | ecs_client = get_client('ecs', access_key_id=access_key_id, 44 | access_key_secret=access_key_secret, 45 | region_id='cn-hangzhou', config=client_config, 46 | retry_policy=CustomRetryPolicy()) 47 | response = ecs_client.describe_regions() 48 | print(response) 49 | -------------------------------------------------------------------------------- /docs/source/advance/client/01_region.rst: -------------------------------------------------------------------------------- 1 | 地域配置 2 | ---------------- 3 | 4 | 使用地域可以访问实际位于特定地理区域的 阿里云 服务。 5 | 6 | 选择地域 7 | ^^^^^^^^^^^^ 8 | 9 | 您可以指定地域名称,\ ``Alibaba Cloud Python SDK`` 内置了访问域名( 10 | ``Endpoint`` )寻址模块,当您调用 ``Alibaba Cloud Python SDK`` 11 | 对一个阿里云服务发起请求时,\ ``Alibaba Cloud Python SDK`` 12 | 会自动根据您在创建 ``Client`` 时指定的地域ID(Region ID)和产品ID来找到 13 | ``Endpoint`` 。 14 | 15 | 有关所有 阿里云 服务的区域最新列表,请参阅 16 | `地域与可用区 `__ 17 | 18 | 例如,要将 ECS 客户端配置为使用 中国(杭州)区域,请使用以下代码。 19 | 20 | .. code:: python 21 | 22 | from alibabacloud import get_client 23 | # 创建一个ecs client 24 | ecs_client = get_client('ecs', access_key_id=your_access_key_id, 25 | access_key_secret=your_access_key_secret, 26 | region_id='cn-hangzhou') 27 | 28 | 注意:如果要为同一项服务使用多个区域,请创建多个客户端 — 29 | 即每个区域一个客户端。 30 | 31 | 使用特定访问域名 32 | ^^^^^^^^^^^^^^^^^^^^^^^^ 33 | 34 | 您也可以使用 ``Endpoint`` 配置,为各个 ``Alibaba Cloud Python SDK`` 35 | 客户端配置使用一个区域内的特定访问域名。 36 | 37 | 例如,要将 ECS 客户端配置为使用 38 | 中国(杭州)的特定访问域名,请使用以下代码。 39 | 40 | .. code:: python 41 | 42 | from alibabacloud import get_client 43 | # 创建一个ecs client 44 | ecs_client = get_client('ecs', access_key_id=your_access_key_id, 45 | access_key_secret=your_access_key_secret, 46 | endpoint="ecs-cn-hangzhou.aliyuncs.com) 47 | 48 | 如果您存在多个 ``Endpoint`` 的配置,您可以参照 ::ref:`handle-client` 49 | 50 | 地域以及访问域名更多配置参照 ::ref:`handle-endpoint` 51 | -------------------------------------------------------------------------------- /alibabacloud/handlers/endpoint_handler.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.endpoint.resolver_endpoint_request import ResolveEndpointRequest 16 | from alibabacloud.handlers import RequestHandler 17 | 18 | 19 | class EndpointHandler(RequestHandler): 20 | 21 | def handle_request(self, context): 22 | if context.config.endpoint is not None: 23 | context.endpoint = context.config.endpoint 24 | else: 25 | resolve_request = ResolveEndpointRequest( 26 | context.config.region_id, 27 | context.client.product_code, 28 | context.client.location_service_code, 29 | context.client.location_endpoint_type, 30 | ) 31 | context.endpoint = context.client.endpoint_resolver.resolve(resolve_request) 32 | 33 | context.client.logger.debug('Endpoint Resolved. Endpoint:%s', context.endpoint) 34 | -------------------------------------------------------------------------------- /alibabacloud/handlers/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | class RequestContext: 17 | 18 | def __init__(self, api_request=None, http_request=None, api_response=None, http_response=None, 19 | exception=None, retry_flag=True, retry_backoff=0, config=None, client=None, 20 | result=None): 21 | self.api_request = api_request 22 | self.http_request = http_request 23 | self.api_response = api_response 24 | self.http_response = http_response 25 | self.exception = exception 26 | self.result = result 27 | 28 | self.config = config 29 | self.client = client 30 | 31 | self.retry_flag = retry_flag 32 | self.retry_backoff = retry_backoff 33 | 34 | 35 | class RequestHandler: 36 | 37 | def handle_request(self, context): 38 | pass 39 | 40 | def handle_response(self, context): 41 | pass 42 | -------------------------------------------------------------------------------- /alibabacloud/services/ens.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | import json 15 | 16 | from alibabacloud import ClientException 17 | from alibabacloud.services._ens import _ENSInstanceResource 18 | from alibabacloud.utils.utils import _new_get_key_in_response 19 | 20 | 21 | class ENSInstanceResource(_ENSInstanceResource): 22 | 23 | def __init__(self, instance_id, _client=None): 24 | _ENSInstanceResource.__init__(self, instance_id, _client=_client) 25 | 26 | def refresh(self): 27 | result = self._client.describe_instances(instance_ids=json.dumps([self.instance_id, ])) 28 | items = _new_get_key_in_response(result, 'Instances.Instance') 29 | if not items: 30 | raise ClientException( 31 | msg="Failed to find instance data from DescribeInstances response. " 32 | "InstanceId = {0}".format( 33 | self.instance_id)) 34 | self._assign_attributes(items[0]) 35 | -------------------------------------------------------------------------------- /alibabacloud/utils/parameter_helper.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | 19 | import hashlib 20 | import base64 21 | import uuid 22 | import time 23 | 24 | from alibabacloud.compat import ensure_bytes, ensure_string 25 | 26 | TIME_ZONE = "GMT" 27 | FORMAT_ISO_8601 = "%Y-%m-%dT%H:%M:%SZ" 28 | FORMAT_RFC_2616 = "%a, %d %b %Y %X GMT" 29 | 30 | 31 | def get_uuid(): 32 | return str(uuid.uuid4()) 33 | 34 | 35 | def get_iso_8061_date(): 36 | return time.strftime(FORMAT_ISO_8601, time.gmtime()) 37 | 38 | 39 | def get_rfc_2616_date(): 40 | return time.strftime(FORMAT_RFC_2616, time.gmtime()) 41 | 42 | 43 | def md5_sum(content): 44 | content_bytes = ensure_bytes(content) 45 | md5_bytes = hashlib.md5(content_bytes).digest() 46 | return ensure_string(base64.standard_b64encode(md5_bytes)) 47 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/urllib3/util/wait.py: -------------------------------------------------------------------------------- 1 | from .selectors import ( 2 | HAS_SELECT, 3 | DefaultSelector, 4 | EVENT_READ, 5 | EVENT_WRITE 6 | ) 7 | 8 | 9 | def _wait_for_io_events(socks, events, timeout=None): 10 | """ Waits for IO events to be available from a list of sockets 11 | or optionally a single socket if passed in. Returns a list of 12 | sockets that can be interacted with immediately. """ 13 | if not HAS_SELECT: 14 | raise ValueError('Platform does not have a selector') 15 | if not isinstance(socks, list): 16 | # Probably just a single socket. 17 | if hasattr(socks, "fileno"): 18 | socks = [socks] 19 | # Otherwise it might be a non-list iterable. 20 | else: 21 | socks = list(socks) 22 | with DefaultSelector() as selector: 23 | for sock in socks: 24 | selector.register(sock, events) 25 | return [key[0].fileobj for key in 26 | selector.select(timeout) if key[1] & events] 27 | 28 | 29 | def wait_for_read(socks, timeout=None): 30 | """ Waits for reading to be available from a list of sockets 31 | or optionally a single socket if passed in. Returns a list of 32 | sockets that can be read from immediately. """ 33 | return _wait_for_io_events(socks, EVENT_READ, timeout) 34 | 35 | 36 | def wait_for_write(socks, timeout=None): 37 | """ Waits for writing to be available from a list of sockets 38 | or optionally a single socket if passed in. Returns a list of 39 | sockets that can be written to immediately. """ 40 | return _wait_for_io_events(socks, EVENT_WRITE, timeout) 41 | -------------------------------------------------------------------------------- /alibabacloud/signer/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | 20 | from alibabacloud.signer.algorithm import NoHandle, ShaHmac1 21 | from alibabacloud.signer.composer import SIGNER_MAP 22 | 23 | 24 | class Signer(object): 25 | 26 | @staticmethod 27 | def sign(credentials, context): 28 | signer = ShaHmac1 29 | if getattr(credentials, 'bearer_token') is not None: 30 | signer = NoHandle 31 | 32 | request = context.api_request 33 | region_id = context.config.region_id 34 | version = context.client.api_version 35 | # which token 36 | cls = SIGNER_MAP[request.style] 37 | auth = cls(credentials, request, region_id, version, signer=signer) 38 | signature, headers, params = auth.signature, auth.headers, auth.params 39 | return signature, headers, params 40 | -------------------------------------------------------------------------------- /alibabacloud/utils/format_type.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | 19 | XML = 'XML' 20 | JSON = 'JSON' 21 | RAW = 'RAW' 22 | APPLICATION_FORM = 'application/x-www-form-urlencoded' 23 | APPLICATION_XML = 'application/xml' 24 | APPLICATION_JSON = 'application/json' 25 | # APPLICATION_JSON = 'application/json;charset=utf-8' 26 | APPLICATION_OCTET_STREAM = 'application/octet-stream' 27 | TEXT_XML = 'text/xml' 28 | 29 | 30 | def map_format_to_accept(format): 31 | if format == XML: 32 | return APPLICATION_XML 33 | if format == JSON: 34 | return APPLICATION_JSON 35 | return APPLICATION_OCTET_STREAM 36 | 37 | 38 | def map_accept_to_format(accept): 39 | if accept.lower() == APPLICATION_XML or accept.lower() == TEXT_XML: 40 | return XML 41 | if accept.lower() == APPLICATION_JSON: 42 | return JSON 43 | return RAW 44 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/urllib3/packages/backports/makefile.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | backports.makefile 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Backports the Python 3 ``socket.makefile`` method for use with anything that 7 | wants to create a "fake" socket object. 8 | """ 9 | import io 10 | 11 | from socket import SocketIO 12 | 13 | 14 | def backport_makefile(self, mode="r", buffering=None, encoding=None, 15 | errors=None, newline=None): 16 | """ 17 | Backport of ``socket.makefile`` from Python 3.5. 18 | """ 19 | if not set(mode) <= set(["r", "w", "b"]): 20 | raise ValueError( 21 | "invalid mode %r (only r, w, b allowed)" % (mode,) 22 | ) 23 | writing = "w" in mode 24 | reading = "r" in mode or not writing 25 | assert reading or writing 26 | binary = "b" in mode 27 | rawmode = "" 28 | if reading: 29 | rawmode += "r" 30 | if writing: 31 | rawmode += "w" 32 | raw = SocketIO(self, rawmode) 33 | self._makefile_refs += 1 34 | if buffering is None: 35 | buffering = -1 36 | if buffering < 0: 37 | buffering = io.DEFAULT_BUFFER_SIZE 38 | if buffering == 0: 39 | if not binary: 40 | raise ValueError("unbuffered streams must be binary") 41 | return raw 42 | if reading and writing: 43 | buffer = io.BufferedRWPair(raw, raw, buffering) 44 | elif reading: 45 | buffer = io.BufferedReader(raw, buffering) 46 | else: 47 | assert writing 48 | buffer = io.BufferedWriter(raw, buffering) 49 | if binary: 50 | return buffer 51 | text = io.TextIOWrapper(buffer, encoding, errors, newline) 52 | text.mode = mode 53 | return text 54 | -------------------------------------------------------------------------------- /docs/source/higher/03_endpoint.rst: -------------------------------------------------------------------------------- 1 | .. _handle-endpoint: 2 | 3 | 管理 Endpoint 4 | =============== 5 | 6 | Endpoint 是您使用 ``Alibaba Cloud SDK`` 访问某个产品或者服务的访问域名。 7 | ``Alibaba Cloud Python SDK``\ 内部封装 ``Endpoint`` 寻址流程,获取 ``Endpoint`` 。您也可以通过直接指定 ``Endpoint`` 的方式省略寻址。 8 | 9 | 10 | 默认Endpoint寻址流程 11 | -------------------- 12 | 13 | .. autoclass:: alibabacloud.endpoint.default_endpoint_resolver.DefaultEndpointResolver 14 | 15 | 16 | 用户自定义Endpoint寻址 17 | ---------------------- 18 | 19 | 您的 ``Endpoint`` 解析需要实现一个 ``resolve`` 的接口,返回一个可用的 ``endpoint`` 20 | 21 | 例如,您想自定义一个名为 ``CustomEndpointResolve`` 的 ``Endpoint`` 管理工具 ,可以参照以下代码: 22 | 23 | .. code:: python 24 | 25 | class CustomEndpointResolve(object): 26 | def __init__(self): 27 | pass 28 | 29 | def resolve(self, retry_policy_context): 30 | # 返回一个可用的endpoint 31 | pass 32 | 33 | 34 | 使用用户自定义的寻址 35 | ------------------------ 36 | 37 | 例如, 您自定义了一个名为 ``CustomEndpointResolve`` 的 ``Endpoint`` 管理工具 ,您可以使用以下方式引用它,替代我们默认的 ``Endpoint`` 寻址。 38 | 39 | .. code:: python 40 | 41 | from alibabacloud import get_client, ClientConfig 42 | 43 | class CustomEndpointResolve(object): 44 | def __init__(self): 45 | pass 46 | 47 | def resolve(self, retry_policy_context): 48 | # 返回一个可用的endpoint 49 | pass 50 | 51 | client_config = ClientConfig(connection_timeout=10, read_timeout=20) 52 | ecs_client = get_client('ecs', access_key_id=access_key_id, 53 | access_key_secret=access_key_secret, 54 | region_id='cn-hangzhou', config=client_config, 55 | endpoint_resolver=CustomEndpointResolve()) 56 | response = ecs_client.describe_regions() 57 | print(response) 58 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/__init__.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # This library is free software; you can redistribute it and/or 3 | # modify it under the terms of the GNU Lesser General Public 4 | # License as published by the Free Software Foundation; either 5 | # version 2.1 of the License, or (at your option) any later version. 6 | # 7 | # This library is distributed in the hope that it will be useful, 8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | # Lesser General Public License for more details. 11 | # 12 | # You should have received a copy of the GNU Lesser General Public 13 | # License along with this library; if not, write to the Free Software 14 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 15 | # 02110-1301 USA 16 | ######################### END LICENSE BLOCK ######################### 17 | 18 | __version__ = "3.0.4" 19 | from .compat import PY2, PY3 20 | from .universaldetector import UniversalDetector 21 | from .version import __version__, VERSION 22 | 23 | 24 | def detect(byte_str): 25 | """ 26 | Detect the encoding of the given byte string. 27 | 28 | :param byte_str: The byte sequence to examine. 29 | :type byte_str: ``bytes`` or ``bytearray`` 30 | """ 31 | if not isinstance(byte_str, bytearray): 32 | if not isinstance(byte_str, bytes): 33 | raise TypeError('Expected object of type bytes or bytearray, got: ' 34 | '{0}'.format(type(byte_str))) 35 | else: 36 | byte_str = bytearray(byte_str) 37 | detector = UniversalDetector() 38 | detector.feed(byte_str) 39 | return detector.close() 40 | -------------------------------------------------------------------------------- /scripts/release-tool.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -xe 2 | 3 | OPERATION=$1 4 | PYTHON_BIN=`which python3` 5 | if [ $PYTHON_BIN == "" ]; then 6 | echo "Python 3.x required." 7 | exit 1 8 | fi 9 | PYTHON_VERSION=`python3 --version | cut -d ' ' -f 2 | cut -d . -f 1,2` 10 | 11 | PACKAGE_NAME="alibaba-cloud-python-sdk-v2" 12 | STAGING_DIR=${HOME}/python-sdk-v2-distribute-staging 13 | SOURCE_NAME=aliyun-python-sdk-v2 14 | SOURCE_DIR=`pwd` 15 | COPY_DIR=${STAGING_DIR}/copy 16 | UNPACK_DIR=${STAGING_DIR}/unpack 17 | INSTALL_DIR=${STAGING_DIR}/install 18 | 19 | 20 | if [ $OPERATION == "dist" ]; then 21 | echo "making package" 22 | rm ${STAGING_DIR} -rf 23 | mkdir -p ${COPY_DIR} 24 | cp -r ${SOURCE_NAME} ${COPY_DIR}/ 25 | cd ${COPY_DIR}/${SOURCE_NAME} 26 | 27 | rm dist *.egg-info -rf; python3 setup.py sdist 28 | 29 | fi 30 | 31 | if [ $OPERATION == "test" ]; then 32 | echo "testing package" 33 | rm $UNPACK_DIR -rf 34 | rm $INSTALL_DIR -rf 35 | mkdir -p $UNPACK_DIR 36 | mkdir -p $INSTALL_DIR 37 | TAR_FILE=`find ${COPY_DIR}/${SOURCE_NAME}/dist -name $PACKAGE_NAME*.tar.gz` 38 | cd $UNPACK_DIR; tar xvf $TAR_FILE 39 | cd `find . -name $PACKAGE_NAME*` 40 | SITE_PACKAGES=$INSTALL_DIR/lib/python$PYTHON_VERSION/site-packages 41 | mkdir $SITE_PACKAGES -p 42 | cp -r $SOURCE_DIR/$SOURCE_NAME/tests $SITE_PACKAGES/ 43 | export PYTHONPATH=$SITE_PACKAGES 44 | python3 setup.py install --prefix=$INSTALL_DIR 45 | 46 | cd $SOURCE_DIR 47 | # export PYTHONPATH=$PYTHONPATH:`ls | grep aliyun-python-sdk- | grep -v core | xargs | sed 's/ /:/g'` 48 | python3 -m pytest tests 49 | fi 50 | 51 | 52 | if [ $OPERATION == "release" ]; then 53 | echo "releasing package" 54 | cd ${COPY_DIR}/${SOURCE_NAME} 55 | twine upload dist/* 56 | fi 57 | -------------------------------------------------------------------------------- /alibabacloud/clients/nls_cloud_meta_20180518.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class NlscloudmetaClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'nls-cloud-meta' 29 | self.api_version = '2018-05-18' 30 | self.location_service_code = None 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def create_token(self,): 34 | api_request = APIRequest('CreateToken', 'POST', 'http', 'ROA', '') 35 | api_request.uri_pattern = '/pop/2018-05-18/tokens' 36 | 37 | return self._handle_request(api_request).result 38 | -------------------------------------------------------------------------------- /alibabacloud/credentials/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | class AlibabaCloudCredentials: 17 | 18 | def __init__(self): 19 | self.access_key_id = None 20 | self.access_key_secret = None 21 | self.security_token = None 22 | self.bearer_token = None 23 | 24 | 25 | # credentials 26 | class AccessKeyCredentials(AlibabaCloudCredentials): 27 | 28 | def __init__(self, access_key_id, access_key_secret): 29 | AlibabaCloudCredentials.__init__(self) 30 | self.access_key_id = access_key_id 31 | self.access_key_secret = access_key_secret 32 | 33 | 34 | class BearerTokenCredentials(AlibabaCloudCredentials): 35 | 36 | def __init__(self, bearer_token): 37 | AlibabaCloudCredentials.__init__(self) 38 | self.bearer_token = bearer_token 39 | 40 | 41 | class SecurityCredentials(AlibabaCloudCredentials): 42 | 43 | def __init__(self, access_key_id, access_key_secret, security_token): 44 | AlibabaCloudCredentials.__init__(self) 45 | self.access_key_id = access_key_id 46 | self.access_key_secret = access_key_secret 47 | self.security_token = security_token 48 | -------------------------------------------------------------------------------- /alibabacloud/endpoint/resolver_endpoint_request.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with self work for additional information 4 | # regarding copyright ownership. The ASF licenses self file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use self file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | from alibabacloud.exceptions import NoRegionException 18 | 19 | ENDPOINT_TYPE_INNER = "innerAPI" 20 | ENDPOINT_TYPE_OPEN = "openAPI" 21 | 22 | 23 | class ResolveEndpointRequest(object): 24 | 25 | # just a request include some common info 26 | def __init__(self, region_id, product_code, location_service_code, endpoint_type): 27 | if region_id is None: 28 | raise NoRegionException() 29 | 30 | self.region_id = region_id 31 | self.product_code = product_code 32 | self.product_code_lower = self.product_code.lower() 33 | 34 | if not endpoint_type: 35 | self.endpoint_type = ENDPOINT_TYPE_OPEN 36 | else: 37 | self.endpoint_type = endpoint_type 38 | 39 | self.location_service_code = location_service_code 40 | 41 | def is_open_api_endpoint(self): 42 | return ENDPOINT_TYPE_OPEN == self.endpoint_type 43 | -------------------------------------------------------------------------------- /alibabacloud/retry/retry_policy.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.retry.retry_condition import * 16 | from alibabacloud.retry.backoff_strategy import * 17 | 18 | 19 | class RetryPolicy(RetryCondition, BackoffStrategy): 20 | 21 | def __init__(self, retry_condition, backoff_strategy): 22 | self.retry_condition = retry_condition 23 | self.backoff_strategy = backoff_strategy 24 | 25 | def should_retry(self, retry_policy_context): 26 | return self.retry_condition.should_retry(retry_policy_context) 27 | 28 | def compute_delay_before_next_retry(self, retry_policy_context): 29 | return self.backoff_strategy.compute_delay_before_next_retry( 30 | retry_policy_context) 31 | 32 | 33 | PREDEFINED_DEFAULT_RETRY_POLICY = RetryPolicy(DefaultConfigRetryCondition(), 34 | DefaultMixedBackoffStrategy()) 35 | NO_RETRY_POLICY = RetryPolicy(NoRetryCondition(), NoDelayStrategy()) 36 | 37 | 38 | def get_default_retry_policy(max_retry_times=None): 39 | return RetryPolicy(DefaultConfigRetryCondition(max_retry_times=max_retry_times), 40 | DefaultMixedBackoffStrategy()) 41 | -------------------------------------------------------------------------------- /alibabacloud/clients/saf_20180919.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class SafClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'saf' 29 | self.api_version = '2018-09-19' 30 | self.location_service_code = 'saf' 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def execute_request(self, service_parameters=None, service=None): 34 | api_request = APIRequest('ExecuteRequest', 'GET', 'https', 'RPC', 'query') 35 | api_request._params = {"ServiceParameters": service_parameters, "Service": service} 36 | return self._handle_request(api_request).result 37 | -------------------------------------------------------------------------------- /alibabacloud/endpoint/endpoint_resolver_base.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with self work for additional information 4 | # regarding copyright ownership. The ASF licenses self file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use self file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | from alibabacloud.endpoint import EndpointResolver 19 | 20 | 21 | class EndpointResolverBase(EndpointResolver): 22 | 23 | def __init__(self): 24 | EndpointResolver.__init__(self) 25 | self.endpoints_data = dict() 26 | 27 | def fetch_endpoint_entry(self, request): 28 | key = self.get_endpoint_key_from_request(request) 29 | return self.endpoints_data.get(key) 30 | 31 | def put_endpoint_entry(self, key, endpoint): 32 | self.endpoints_data[key] = endpoint 33 | 34 | def is_product_code_valid(self, request): 35 | for key in self.endpoints_data.keys(): 36 | if key.startswith(request.product_code_lower): 37 | return True 38 | return False 39 | 40 | def is_region_id_valid(self, request): 41 | raise NotImplementedError() 42 | 43 | def get_endpoint_key_from_request(self, request): 44 | raise NotImplementedError() 45 | 46 | def get_valid_region_ids_by_product(self, product_code): 47 | # Only local config can tell 48 | return None 49 | -------------------------------------------------------------------------------- /alibabacloud/credentials/assume_role_caller.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | 18 | 19 | class MiniRAMClient(AlibabaCloudClient): 20 | 21 | def __init__(self, client_config, credentials_provider): 22 | AlibabaCloudClient.__init__(self, client_config, credentials_provider) 23 | self.product_code = "Sts" 24 | self.api_version = "2015-04-01" 25 | self.location_service_code = 'sts' 26 | self.location_endpoint_type = "openAPI" 27 | 28 | def assume_role(self, role_arn=None, role_session_name=None, duration_seconds=None): 29 | api_request = APIRequest('AssumeRole', 'GET', 'https', 'RPC', 'query') 30 | api_request._params = { 31 | "RoleArn": role_arn, 32 | "RoleSessionName": role_session_name, 33 | "DurationSeconds": duration_seconds, 34 | } 35 | return self._handle_request(api_request) 36 | 37 | 38 | class AssumeRoleCaller: 39 | 40 | def __init__(self, client_config, credentials_provider): 41 | self._client = MiniRAMClient(client_config, credentials_provider) 42 | 43 | def fetch(self, role_arn, role_session_name, session_period): 44 | return self._client.assume_role(role_arn, role_session_name, session_period) 45 | -------------------------------------------------------------------------------- /python-function-test/alibabacloud_useragent_test.py: -------------------------------------------------------------------------------- 1 | from alibabacloud.clients.ecs_20140526 import EcsClient 2 | from base import SDKTestBase, MyServer 3 | 4 | 5 | class UserAgentTest(SDKTestBase): 6 | 7 | @staticmethod 8 | def joint_default_user_agent(): 9 | import platform 10 | base = '%s (%s %s;%s) Python/%s Alibabacloud/%s python-requests/%s' \ 11 | % ('AlibabaCloud', 12 | platform.system(), 13 | platform.release(), 14 | platform.machine(), 15 | platform.python_version(), 16 | __import__('alibabacloud').__version__, 17 | __import__( 18 | 'alibabacloud.vendored.requests.__version__', globals(), locals(), 19 | ['vendored', 'requests', '__version__'], 0).__version__) 20 | return base 21 | 22 | def init_temp_client_config(self): 23 | client_config = self.client_config 24 | client_config.http_port = 51352 25 | client_config.endpoint = "localhost" 26 | return client_config 27 | 28 | def test_default_user_agent(self): 29 | client_config = self.init_temp_client_config() 30 | client = EcsClient(client_config, self.init_credentials_provider()) 31 | with MyServer() as s: 32 | client.describe_instances() 33 | user_agent = s.headers.get('User-Agent') 34 | self.assertEqual(self.joint_default_user_agent(), user_agent) 35 | 36 | def test_append_user_agent(self): 37 | client_config = self.init_temp_client_config() 38 | client_config.user_agent = 'alibabacloudpythonsdk' 39 | client = EcsClient(client_config, self.init_credentials_provider()) 40 | with MyServer() as s: 41 | client.describe_instances() 42 | user_agent = s.headers.get('User-Agent') 43 | self.assertEqual(self.joint_default_user_agent() + ' alibabacloudpythonsdk', user_agent) 44 | -------------------------------------------------------------------------------- /tests/mock_data/instance_full_status.json: -------------------------------------------------------------------------------- 1 | { 2 | "PageNumber":1, 3 | "TotalCount":2, 4 | "PageSize":10, 5 | "InstanceFullStatusSet":{ 6 | "InstanceFullStatusType":[ 7 | { 8 | "Status":{ 9 | "Name":"Running", 10 | "Code":1 11 | }, 12 | "HealthStatus":{ 13 | "Name":"Maintaining", 14 | "Code":0 15 | }, 16 | "InstanceId":"i-instance1", 17 | "ScheduledSystemEventSet":{ 18 | "ScheduledSystemEventType":[ 19 | { 20 | "EventPublishTime":"2017-11-30T06:32:31Z", 21 | "NotBefore":"2017-12-01T06:32:31Z", 22 | "EventId":"e-event1", 23 | "EventType":{ 24 | "Name":"SystemMaintenance.Reboot", 25 | "Code":1 26 | }, 27 | "EventCycleStatus":{ 28 | "Name":"Scheduled", 29 | "Code":24 30 | } 31 | }, 32 | { 33 | "EventPublishTime":"2017-11-30T00:00:00Z", 34 | "NotBefore":"2017-12-07T00:00:00Z", 35 | "EventId":"e-event2", 36 | "EventType":{ 37 | "Name":"InstanceExpiration.Stop", 38 | "Code":34 39 | }, 40 | "EventCycleStatus":{ 41 | "Name":"Scheduled", 42 | "Code":24 43 | } 44 | } 45 | ] 46 | } 47 | }, 48 | { 49 | "Status":{ 50 | "Name":"Running", 51 | "Code":1 52 | }, 53 | "HealthStatus":{ 54 | "Name":"Warning", 55 | "Code":64 56 | }, 57 | "InstanceId":"i-instance2", 58 | "ScheduledSystemEventSet":{ 59 | "ScheduledSystemEventType":[ 60 | { 61 | "EventPublishTime":"2017-11-30T06:32:31Z", 62 | "NotBefore":"2017-12-01T06:32:31Z", 63 | "EventId":"e-event3", 64 | "EventType":{ 65 | "Name":"SystemFailure.Reboot", 66 | "Code":65 67 | }, 68 | "EventCycleStatus":{ 69 | "Name":"Scheduled", 70 | "Code":24 71 | } 72 | } 73 | ] 74 | } 75 | } 76 | ] 77 | }, 78 | "RequestId":"AAC49D3E-ED6F-4F00-XXXX-377C551B1DD4" 79 | } -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/euctwprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCTWDistributionAnalysis 31 | from .mbcssm import EUCTW_SM_MODEL 32 | 33 | class EUCTWProber(MultiByteCharSetProber): 34 | def __init__(self): 35 | super(EUCTWProber, self).__init__() 36 | self.coding_sm = CodingStateMachine(EUCTW_SM_MODEL) 37 | self.distribution_analyzer = EUCTWDistributionAnalysis() 38 | self.reset() 39 | 40 | @property 41 | def charset_name(self): 42 | return "EUC-TW" 43 | 44 | @property 45 | def language(self): 46 | return "Taiwan" 47 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/euckrprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCKRDistributionAnalysis 31 | from .mbcssm import EUCKR_SM_MODEL 32 | 33 | 34 | class EUCKRProber(MultiByteCharSetProber): 35 | def __init__(self): 36 | super(EUCKRProber, self).__init__() 37 | self.coding_sm = CodingStateMachine(EUCKR_SM_MODEL) 38 | self.distribution_analyzer = EUCKRDistributionAnalysis() 39 | self.reset() 40 | 41 | @property 42 | def charset_name(self): 43 | return "EUC-KR" 44 | 45 | @property 46 | def language(self): 47 | return "Korean" 48 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/gb2312prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import GB2312DistributionAnalysis 31 | from .mbcssm import GB2312_SM_MODEL 32 | 33 | class GB2312Prober(MultiByteCharSetProber): 34 | def __init__(self): 35 | super(GB2312Prober, self).__init__() 36 | self.coding_sm = CodingStateMachine(GB2312_SM_MODEL) 37 | self.distribution_analyzer = GB2312DistributionAnalysis() 38 | self.reset() 39 | 40 | @property 41 | def charset_name(self): 42 | return "GB2312" 43 | 44 | @property 45 | def language(self): 46 | return "Chinese" 47 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/big5prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Communicator client code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import Big5DistributionAnalysis 31 | from .mbcssm import BIG5_SM_MODEL 32 | 33 | 34 | class Big5Prober(MultiByteCharSetProber): 35 | def __init__(self): 36 | super(Big5Prober, self).__init__() 37 | self.coding_sm = CodingStateMachine(BIG5_SM_MODEL) 38 | self.distribution_analyzer = Big5DistributionAnalysis() 39 | self.reset() 40 | 41 | @property 42 | def charset_name(self): 43 | return "Big5" 44 | 45 | @property 46 | def language(self): 47 | return "Chinese" 48 | -------------------------------------------------------------------------------- /python-function-test/test_check_params.py: -------------------------------------------------------------------------------- 1 | # from alibabacloud.clients.eci_20180808 import EciClient 2 | from alibabacloud.clients.ecs_20140526 import EcsClient 3 | from alibabacloud.exceptions import ParamValidationException 4 | from alibabacloud.vendored import six 5 | from base import SDKTestBase 6 | 7 | 8 | class GenTestCheckParams(SDKTestBase): 9 | 10 | def test_rpc_query_list(self): 11 | # check one 12 | ecs_client = EcsClient(self.client_config, self.init_credentials_provider()) 13 | tag = 'hi' 14 | try: 15 | context = ecs_client.describe_tags(list_of_tag=tag) 16 | assert False 17 | except ParamValidationException as e: 18 | if six.PY2: 19 | self.assertEqual(e.error_message, 20 | "Parameter validation failed: Invalid type for parameter Tag, value: hi, type: , valid types: ") 21 | else: 22 | self.assertEqual(e.error_message, 23 | "Parameter validation failed: Invalid type for parameter Tag, value: hi, type: , valid types: ") 24 | 25 | def test_rpc_query_list1(self): 26 | # check two 27 | ecs_client = EcsClient(self.client_config, self.init_credentials_provider()) 28 | tag = [ 29 | 'hi' 30 | ] 31 | try: 32 | context = ecs_client.describe_tags(list_of_tag=tag) 33 | assert False 34 | except ParamValidationException as e: 35 | if six.PY2: 36 | self.assertEqual(e.error_message, 37 | "Parameter validation failed: Invalid type for parameter Tag.0.Tag, value: hi, type: , valid types: ") 38 | 39 | else: 40 | self.assertEqual(e.error_message, 41 | "Parameter validation failed: Invalid type for parameter Tag.0.Tag, value: hi, type: , valid types: ") 42 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/enums.py: -------------------------------------------------------------------------------- 1 | """ 2 | All of the Enums that are used throughout the chardet package. 3 | 4 | :author: Dan Blanchard (dan.blanchard@gmail.com) 5 | """ 6 | 7 | 8 | class InputState(object): 9 | """ 10 | This enum represents the different states a universal detector can be in. 11 | """ 12 | PURE_ASCII = 0 13 | ESC_ASCII = 1 14 | HIGH_BYTE = 2 15 | 16 | 17 | class LanguageFilter(object): 18 | """ 19 | This enum represents the different language filters we can apply to a 20 | ``UniversalDetector``. 21 | """ 22 | CHINESE_SIMPLIFIED = 0x01 23 | CHINESE_TRADITIONAL = 0x02 24 | JAPANESE = 0x04 25 | KOREAN = 0x08 26 | NON_CJK = 0x10 27 | ALL = 0x1F 28 | CHINESE = CHINESE_SIMPLIFIED | CHINESE_TRADITIONAL 29 | CJK = CHINESE | JAPANESE | KOREAN 30 | 31 | 32 | class ProbingState(object): 33 | """ 34 | This enum represents the different states a prober can be in. 35 | """ 36 | DETECTING = 0 37 | FOUND_IT = 1 38 | NOT_ME = 2 39 | 40 | 41 | class MachineState(object): 42 | """ 43 | This enum represents the different states a state machine can be in. 44 | """ 45 | START = 0 46 | ERROR = 1 47 | ITS_ME = 2 48 | 49 | 50 | class SequenceLikelihood(object): 51 | """ 52 | This enum represents the likelihood of a character following the previous one. 53 | """ 54 | NEGATIVE = 0 55 | UNLIKELY = 1 56 | LIKELY = 2 57 | POSITIVE = 3 58 | 59 | @classmethod 60 | def get_num_categories(cls): 61 | """:returns: The number of likelihood categories in the enum.""" 62 | return 4 63 | 64 | 65 | class CharacterCategory(object): 66 | """ 67 | This enum represents the different categories language models for 68 | ``SingleByteCharsetProber`` put characters into. 69 | 70 | Anything less than CONTROL is considered a letter. 71 | """ 72 | UNDEFINED = 255 73 | LINE_BREAK = 254 74 | SYMBOL = 253 75 | DIGIT = 252 76 | CONTROL = 251 77 | -------------------------------------------------------------------------------- /python-function-test/alibabacloud_logger_test.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import logging 16 | import os 17 | import tempfile 18 | 19 | import mock 20 | 21 | from alibabacloud.clients.ecs_20140526 import EcsClient 22 | from base import SDKTestBase 23 | 24 | 25 | class AlibabaLoggerTest(SDKTestBase): 26 | 27 | def test_no_retry(self): 28 | client = EcsClient(self.client_config, self.init_credentials_provider()) 29 | tempdir = tempfile.mkdtemp() 30 | 31 | temp_file = os.path.join(tempdir, 'file_logger') 32 | 33 | client.add_rotating_file_log_handler(log_level=logging.DEBUG, path=temp_file) 34 | context = client.describe_instances() 35 | self.assertTrue(os.path.isfile(temp_file)) 36 | with open(temp_file) as logfile: 37 | s = logfile.read() 38 | self.assertTrue('alibabacloud-' in s) 39 | self.assertTrue('DEBUG' in s) 40 | 41 | @mock.patch('logging.getLogger') 42 | @mock.patch('logging.Formatter') 43 | def test_stream_logger(self, formatter, get_logger): 44 | client = EcsClient(self.client_config, self.init_credentials_provider()) 45 | client.add_stream_log_handler(logger_name='foo.bar', log_level=40, format_string='foo') 46 | get_logger.assert_called_with('foo.bar') 47 | get_logger.return_value.setLevel.assert_called_with(logging.ERROR) 48 | formatter.assert_called_with('foo') 49 | -------------------------------------------------------------------------------- /alibabacloud/endpoint/user_customized_endpoint_resolver.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with self work for additional information 4 | # regarding copyright ownership. The ASF licenses self file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use self file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | from alibabacloud.endpoint.endpoint_resolver_base import EndpointResolverBase 19 | 20 | 21 | class UserCustomizedEndpointResolver(EndpointResolverBase): 22 | 23 | def __init__(self): 24 | EndpointResolverBase.__init__(self) 25 | self._valid_region_ids = set() 26 | 27 | def put_endpoint_entry(self, region_id, product_code, endpoint): 28 | EndpointResolverBase.put_endpoint_entry( 29 | self, self._make_endpoint_entry_key(product_code, region_id), endpoint) 30 | self._valid_region_ids.add(region_id) 31 | 32 | def resolve(self, request): 33 | return self.fetch_endpoint_entry(request) 34 | 35 | def get_endpoint_key_from_request(self, request): 36 | return self._make_endpoint_entry_key(request.product_code, request.region_id) 37 | 38 | def _make_endpoint_entry_key(self, product_code, region_id): 39 | ret = product_code.lower() + "." + region_id.lower() 40 | return ret 41 | 42 | def is_region_id_valid(self, request): 43 | return request.region_id in self._valid_region_ids 44 | 45 | def reset(self): 46 | self.endpoints_data = dict() 47 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/compat.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.compat 5 | ~~~~~~~~~~~~~~~ 6 | 7 | This module handles import compatibility issues between Python 2 and 8 | Python 3. 9 | """ 10 | 11 | from .packages import chardet 12 | 13 | import sys 14 | 15 | # ------- 16 | # Pythons 17 | # ------- 18 | 19 | # Syntax sugar. 20 | _ver = sys.version_info 21 | 22 | #: Python 2.x? 23 | is_py2 = (_ver[0] == 2) 24 | 25 | #: Python 3.x? 26 | is_py3 = (_ver[0] == 3) 27 | 28 | try: 29 | import simplejson as json 30 | except ImportError: 31 | import json 32 | 33 | # --------- 34 | # Specifics 35 | # --------- 36 | 37 | if is_py2: 38 | from urllib import ( 39 | quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, 40 | proxy_bypass, proxy_bypass_environment, getproxies_environment) 41 | from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag 42 | from urllib2 import parse_http_list 43 | import cookielib 44 | from Cookie import Morsel 45 | from StringIO import StringIO 46 | from collections import Callable, Mapping, MutableMapping 47 | 48 | from .packages.urllib3.packages.ordered_dict import OrderedDict 49 | 50 | builtin_str = str 51 | bytes = str 52 | str = unicode 53 | basestring = basestring 54 | numeric_types = (int, long, float) 55 | integer_types = (int, long) 56 | 57 | elif is_py3: 58 | from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag 59 | from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment 60 | from http import cookiejar as cookielib 61 | from http.cookies import Morsel 62 | from io import StringIO 63 | from collections import OrderedDict 64 | from collections.abc import Callable, Mapping, MutableMapping 65 | 66 | builtin_str = str 67 | str = str 68 | bytes = bytes 69 | basestring = (str, bytes) 70 | numeric_types = (int, float) 71 | integer_types = (int,) 72 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/cp949prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .chardistribution import EUCKRDistributionAnalysis 29 | from .codingstatemachine import CodingStateMachine 30 | from .mbcharsetprober import MultiByteCharSetProber 31 | from .mbcssm import CP949_SM_MODEL 32 | 33 | 34 | class CP949Prober(MultiByteCharSetProber): 35 | def __init__(self): 36 | super(CP949Prober, self).__init__() 37 | self.coding_sm = CodingStateMachine(CP949_SM_MODEL) 38 | # NOTE: CP949 is a superset of EUC-KR, so the distribution should be 39 | # not different. 40 | self.distribution_analyzer = EUCKRDistributionAnalysis() 41 | self.reset() 42 | 43 | @property 44 | def charset_name(self): 45 | return "CP949" 46 | 47 | @property 48 | def language(self): 49 | return "Korean" 50 | -------------------------------------------------------------------------------- /docs/source/higher/02_credentials.rst: -------------------------------------------------------------------------------- 1 | 管理用户凭证 2 | ============ 3 | 4 | ``credentials_provider`` 是 ``Alibaba Cloud Python SDK`` 5 | 提供的新特性。它是阿里云的访问凭证( ``credentials`` )的提供者,通过\ ``credentials_provider``\ 的\ ``provider``\ 接口可以获取真实的访问凭证 6 | ``credentials``\ 。 7 | 8 | 9 | 默认的 ``credentials_provider`` 10 | ------------------------------- 11 | 12 | ``Alibaba Cloud Python SDK`` 提供3种类型的 ``credentials_provider``\ 。 13 | 14 | .. module:: alibabacloud 15 | 16 | .. autoclass:: alibabacloud.credentials.provider.PredefinedChainCredentialsProvider 17 | .. autoclass:: alibabacloud.credentials.provider.EnvCredentialsProvider 18 | .. autoclass:: alibabacloud.credentials.provider.ProfileCredentialsProvider 19 | .. autoclass:: alibabacloud.credentials.provider.InstanceProfileCredentialsProvider 20 | 21 | 22 | 用户自定义的 ``credentials_provider`` 23 | ------------------------------------- 24 | 25 | ``Alibaba Cloud Python SDK`` 支持用户使用自定义的 26 | ``credentials_provider`` ,但是该 ``credentials_provider`` 必须实现一个 27 | ``provide`` 返回最终的 ``credentials`` . 28 | 29 | 例如,您想自定义一个名为 ``CustomCredentialsProvider`` 的 ``credentials_provider`` ,可以参照以下代码: 30 | 31 | .. code:: python 32 | 33 | class CustomCredentialsProvider(object): 34 | def __init__(self): 35 | pass 36 | 37 | def provide(self, retry_policy_context): 38 | # 返回 credentials 39 | pass 40 | 41 | 42 | 使用用户自定义的 ``credentials_provider`` 43 | ----------------------------------------- 44 | 45 | 例如, 您自定义了一个名为 ``CustomCredentialsProvider`` 的 ``credentials_provider`` ,您可以使用以下方式引用它,替代我们默认的 ``credentials_provider``。 46 | 47 | .. code:: python 48 | 49 | from alibabacloud import get_client, ClientConfig 50 | 51 | client_config = ClientConfig(connection_timeout=10, read_timeout=20) 52 | ecs_client = get_client('ecs', access_key_id=access_key_id, 53 | access_key_secret=access_key_secret, 54 | region_id='cn-hangzhou', config=client_config, 55 | credentials_provider=CustomCredentialsProvider()) 56 | response = ecs_client.describe_regions() 57 | print(response) 58 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from setuptools import setup, find_packages 17 | 18 | PACKAGE = "alibaba-cloud-python-sdk-v2" 19 | VERSION = __import__("alibabacloud").__version__ 20 | 21 | requires = [ 22 | 'jmespath>=0.9.3,<1.0.0', 23 | 'mock>=2.0.0', 24 | ] 25 | 26 | setup( 27 | name=PACKAGE, 28 | version=VERSION, 29 | description='Alibaba Cloud Python SDK 2.0', 30 | author='Alibaba Cloud', 31 | author_email='alibaba-cloud-sdk-dev-team@list.alibaba-inc.com', 32 | url='https://github.com/aliyun/alibabacloud-python-sdk-v2', 33 | packages=find_packages(exclude=['tests*']), 34 | package_data={'alibabacloud': ['data/*.json'], 35 | 'alibabacloud.vendored.requests.packages.certifi': ['cacert.pem']}, 36 | install_requires=requires, 37 | license="Apache License 2.0", 38 | classifiers=[ 39 | 'Development Status :: 1 - Planning', 40 | 'Intended Audience :: Developers', 41 | 'Natural Language :: English', 42 | 'License :: OSI Approved :: Apache Software License', 43 | 'Programming Language :: Python', 44 | 'Programming Language :: Python :: 2.7', 45 | 'Programming Language :: Python :: 3', 46 | 'Programming Language :: Python :: 3.3', 47 | 'Programming Language :: Python :: 3.4', 48 | 'Programming Language :: Python :: 3.5', 49 | 'Programming Language :: Python :: 3.6', 50 | 'Programming Language :: Python :: 3.7', 51 | ], 52 | ) 53 | -------------------------------------------------------------------------------- /docs/source/advance/credentials/03_file.rst: -------------------------------------------------------------------------------- 1 | 凭证文件配置 2 | ---------------- 3 | 4 | ``Alibaba Cloud Python SDK`` 5 | 凭证文件的默认位置为:\ ``~/.alibabacloud/credentials`` 。 6 | 您可以通过环境变量 ``ALIBABA_CLOUD_CREDENTIALS_FILE`` 7 | 来更改此默认位置。配置文件是 INI 格式。 您可以在配置文件中设置以下 ``type`` 8 | 的 ``Credentials`` 9 | 10 | 11 | 基于 AccessKey 的凭证配置 12 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 13 | 14 | AccessKey 可以是主账号或者子账号,为了安全考虑,建议您使用子账号进行 15 | AccessKey 的凭证配置 16 | 17 | .. code:: 18 | 19 | [default] 20 | type = access_key 21 | access_key_id = YOUR_ACCESS_KEY_ID 22 | access_key_secret = YOUR_ACCESS_KEY_SECRET 23 | 24 | 基于 RAM 子用户的凭证配置 25 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 26 | 27 | 创建RAM子账号流程,参照 28 | `准备RAM子账号 `__ 29 | 30 | .. code:: 31 | 32 | [default] 33 | type = ram_role_arn 34 | access_key_id = YOUR_ACCESS_KEY_ID 35 | access_key_secret = YOUR_ACCESS_KEY_SECRET 36 | role_arn = YOUR_ROLE_ARN 37 | role_session_name = YOUR_ROLE_SESSION_NAME 38 | 39 | 40 | 基于实例 ECS 实例的凭证配置 41 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 42 | 43 | 阿里云 SDK 支持通过实例元数据服务来获取 ECS RAM 44 | 角色的授权信息来访问阿里云资源和服务。使用这种方式,您部署在 ECS 45 | 上的应用程序,无需在 SDK 上配置授权信息即可访问阿里云API(即不需要配置 46 | AccessKey )。通过这种方式授权的 SDK ,可以拥有这个 ECS RAM 角色的权限。 47 | 48 | .. code:: 49 | 50 | [default] 51 | type = ecs_ram_role 52 | role_name = YOUR_ROLE_NAME 53 | 54 | 注意:确保 ECS 实例已经配置了 RAM 角色。 55 | 56 | 57 | 基于 BearerToken 的凭证配置 58 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 59 | 60 | BearerToken 当前仅支持 CCC (云呼叫中心)产品的加密,请**慎重使用** 61 | 62 | .. code:: 63 | 64 | [default] 65 | type = bearer_token 66 | bearer_token = YOUR BEAR TOKEN 67 | 68 | 基于 STS Token 的凭证配置 69 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 70 | 71 | 参照 `配置STS 72 | Token `__ 73 | 74 | .. code:: 75 | 76 | [default] 77 | type = sts_token 78 | type = ram_role_arn 79 | access_key_id = YOUR_ACCESS_KEY_ID 80 | access_key_secret = YOUR_ACCESS_KEY_SECRET 81 | user_name = YOUR_USER_NAME 82 | role_arn = YOUR_ROLE_ARN 83 | role_session_name = YOUR_ROLE_SESSION_NAME 84 | 85 | 您可以配置多个客户端凭证,但是我们目前仅支持读取 section 为 default 86 | 的凭证。 87 | -------------------------------------------------------------------------------- /alibabacloud/clients/xspace_20170720.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class XspaceClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'xspace' 29 | self.api_version = '2017-07-20' 30 | self.location_service_code = None 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def query_customer_by_id(self, id_=None): 34 | api_request = APIRequest('QueryCustomerById', 'GET', 'http', 'ROA', 'query') 35 | api_request.uri_pattern = '/customer' 36 | api_request._params = {"Id": id_} 37 | return self._handle_request(api_request).result 38 | 39 | def query_customer_by_phone(self, phone=None): 40 | api_request = APIRequest('QueryCustomerByPhone', 'GET', 'http', 'ROA', 'query') 41 | api_request.uri_pattern = '/customerbyphone' 42 | api_request._params = {"Phone": phone} 43 | return self._handle_request(api_request).result 44 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # __ 4 | # /__) _ _ _ _ _/ _ 5 | # / ( (- (/ (/ (- _) / _) 6 | # / 7 | 8 | """ 9 | Requests HTTP Library 10 | ~~~~~~~~~~~~~~~~~~~~~ 11 | 12 | Requests is an HTTP library, written in Python, for human beings. Basic GET 13 | usage: 14 | 15 | >>> import requests 16 | >>> r = requests.get('https://www.python.org') 17 | >>> r.status_code 18 | 200 19 | >>> 'Python is a programming language' in r.content 20 | True 21 | 22 | ... or POST: 23 | 24 | >>> payload = dict(key1='value1', key2='value2') 25 | >>> r = requests.post('http://httpbin.org/post', data=payload) 26 | >>> print(r.text) 27 | { 28 | ... 29 | "form": { 30 | "key2": "value2", 31 | "key1": "value1" 32 | }, 33 | ... 34 | } 35 | 36 | The other HTTP methods are supported - see `requests.api`. Full documentation 37 | is at . 38 | 39 | :copyright: (c) 2017 by Kenneth Reitz. 40 | :license: Apache 2.0, see LICENSE for more details. 41 | """ 42 | 43 | __title__ = 'requests' 44 | __version__ = '2.18.3' 45 | 46 | # Attempt to enable urllib3's SNI support, if possible 47 | try: 48 | from .packages.urllib3.contrib import pyopenssl 49 | pyopenssl.inject_into_urllib3() 50 | except ImportError: 51 | pass 52 | 53 | 54 | from . import utils 55 | from .models import Request, Response, PreparedRequest 56 | from .api import request, get, head, post, patch, put, delete, options 57 | from .sessions import session, Session 58 | from .status_codes import codes 59 | from .exceptions import ( 60 | RequestException, Timeout, URLRequired, 61 | TooManyRedirects, HTTPError, ConnectionError, 62 | FileModeWarning, ConnectTimeout, ReadTimeout 63 | ) 64 | 65 | # Set default logging handler to avoid "No handler found" warnings. 66 | import logging 67 | try: # Python 2.7+ 68 | from logging import NullHandler 69 | except ImportError: 70 | class NullHandler(logging.Handler): 71 | def emit(self, record): 72 | pass 73 | 74 | logging.getLogger(__name__).addHandler(NullHandler()) 75 | logging.getLogger(__name__).setLevel(logging.CRITICAL) 76 | 77 | 78 | -------------------------------------------------------------------------------- /alibabacloud/clients/dybaseapi_20170525.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class DybaseapiClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'Dybaseapi' 29 | self.api_version = '2017-05-25' 30 | self.location_service_code = 'dybaseapi' 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def query_token_for_mns_queue( 34 | self, 35 | queue_name=None, 36 | resource_owner_id=None, 37 | resource_owner_account=None, 38 | message_type=None, 39 | owner_id=None): 40 | api_request = APIRequest('QueryTokenForMnsQueue', 'GET', 'http', 'RPC', 'query') 41 | api_request._params = { 42 | "QueueName": queue_name, 43 | "ResourceOwnerId": resource_owner_id, 44 | "ResourceOwnerAccount": resource_owner_account, 45 | "MessageType": message_type, 46 | "OwnerId": owner_id} 47 | return self._handle_request(api_request).result 48 | -------------------------------------------------------------------------------- /alibabacloud/services/vpc.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from alibabacloud.exceptions import ClientException 15 | from alibabacloud.resources.collection import _create_resource_collection 16 | from alibabacloud.services._vpc import _VPCResource 17 | from alibabacloud.services._vpc import _VPCEipAddressResource 18 | from alibabacloud.utils.utils import transfer, _new_get_key_in_response 19 | 20 | 21 | class VPCEipAddressResource(_VPCEipAddressResource): 22 | 23 | def __init__(self, allocation_id, _client=None): 24 | _VPCEipAddressResource.__init__(self, allocation_id, _client=_client) 25 | self.allocation_id = allocation_id 26 | 27 | @transfer({"Tags": "list_of_tags"}) 28 | def refresh(self): 29 | response = self._client.describe_eip_addresses(allocation_id=self.allocation_id) 30 | items = _new_get_key_in_response(response, 'EipAddresses.EipAddress') 31 | if not items: 32 | raise ClientException(msg="Failed to find EIP Address data from DescribeEipAddresses " 33 | "response. " 34 | "AllocationId = {0}".format(self.allocation_id)) 35 | self._assign_attributes(items[0]) 36 | 37 | 38 | class VPCResource(_VPCResource): 39 | 40 | def __init__(self, _client=None): 41 | _VPCResource.__init__(self, _client=_client) 42 | self.eip_addresses = _create_resource_collection( 43 | VPCEipAddressResource, _client, _client.describe_eip_addresses, 44 | 'EipAddresses.EipAddress', 'AllocationId', 45 | param_aliases={"Tags": "list_of_tags"} 46 | ) 47 | -------------------------------------------------------------------------------- /alibabacloud/endpoint/local_config_global_endpoint_resolver.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with self work for additional information 4 | # regarding copyright ownership. The ASF licenses self file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use self file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | from alibabacloud.endpoint.local_config_regional_endpoint_resolver \ 19 | import LocalConfigRegionalEndpointResolver 20 | from alibabacloud.vendored.six import iteritems 21 | 22 | 23 | class LocalConfigGlobalEndpointResolver(LocalConfigRegionalEndpointResolver): 24 | 25 | def _init_local_config(self, obj): 26 | self._init_global_endpoint_data(obj) 27 | self._init_region_ids(obj) 28 | self._init_location_code_mapping(obj) 29 | 30 | def _init_global_endpoint_data(self, obj): 31 | if "global_endpoints" not in obj: 32 | return 33 | 34 | global_endpoints = obj["global_endpoints"] 35 | for location_service_code, endpoint in iteritems(global_endpoints): 36 | self.put_endpoint_entry(self._make_endpoint_entry_key(location_service_code), 37 | endpoint) 38 | 39 | def resolve(self, request): 40 | if request.is_open_api_endpoint() and self.is_region_id_valid(request): 41 | return self.fetch_endpoint_entry(request) 42 | else: 43 | return None 44 | 45 | def get_endpoint_key_from_request(self, request): 46 | return self._make_endpoint_entry_key(request.product_code) 47 | 48 | def _make_endpoint_entry_key(self, product_code): 49 | return self._get_normalized_product_code(product_code) 50 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/mbcsgroupprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # Proofpoint, Inc. 13 | # 14 | # This library is free software; you can redistribute it and/or 15 | # modify it under the terms of the GNU Lesser General Public 16 | # License as published by the Free Software Foundation; either 17 | # version 2.1 of the License, or (at your option) any later version. 18 | # 19 | # This library is distributed in the hope that it will be useful, 20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 22 | # Lesser General Public License for more details. 23 | # 24 | # You should have received a copy of the GNU Lesser General Public 25 | # License along with this library; if not, write to the Free Software 26 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 27 | # 02110-1301 USA 28 | ######################### END LICENSE BLOCK ######################### 29 | 30 | from .charsetgroupprober import CharSetGroupProber 31 | from .utf8prober import UTF8Prober 32 | from .sjisprober import SJISProber 33 | from .eucjpprober import EUCJPProber 34 | from .gb2312prober import GB2312Prober 35 | from .euckrprober import EUCKRProber 36 | from .cp949prober import CP949Prober 37 | from .big5prober import Big5Prober 38 | from .euctwprober import EUCTWProber 39 | 40 | 41 | class MBCSGroupProber(CharSetGroupProber): 42 | def __init__(self, lang_filter=None): 43 | super(MBCSGroupProber, self).__init__(lang_filter=lang_filter) 44 | self.probers = [ 45 | UTF8Prober(), 46 | SJISProber(), 47 | EUCJPProber(), 48 | GB2312Prober(), 49 | EUCKRProber(), 50 | CP949Prober(), 51 | Big5Prober(), 52 | EUCTWProber() 53 | ] 54 | self.reset() 55 | -------------------------------------------------------------------------------- /alibabacloud/services/slb.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from alibabacloud.exceptions import ClientException 15 | from alibabacloud.resources.collection import _create_resource_collection 16 | from alibabacloud.services._slb import _SLBResource, _SLBLoadBalancerResource 17 | from alibabacloud.utils.utils import transfer, _new_get_key_in_response 18 | 19 | 20 | class LoadBalancerResource(_SLBLoadBalancerResource): 21 | 22 | def __init__(self, load_balancer_id, _client=None): 23 | _SLBLoadBalancerResource.__init__(self, load_balancer_id, _client=_client) 24 | self.load_balancer_id = load_balancer_id 25 | 26 | @transfer({"Tags": "list_of_tags",}) 27 | def refresh(self): 28 | response = self._client.describe_load_balancers(load_balancer_id=self.load_balancer_id) 29 | items = _new_get_key_in_response(response, 'LoadBalancers.LoadBalancer') 30 | if not items: 31 | raise ClientException( 32 | msg="Failed to find load balancer data from DescribeLoadBalancers " 33 | "response. " 34 | "LoadBalancerId = {0}".format( 35 | self.load_balancer_id)) 36 | self._assign_attributes(items[0]) 37 | 38 | 39 | class SLBResource(_SLBResource): 40 | 41 | def __init__(self, _client=None): 42 | _SLBResource.__init__(self, _client=_client) 43 | self.load_balancers = _create_resource_collection( 44 | LoadBalancerResource, _client, _client.describe_load_balancers, 45 | 'LoadBalancers.LoadBalancer', 'LoadBalancerId', 46 | param_aliases={ 47 | "Tags": "list_of_tags", 48 | } 49 | ) 50 | -------------------------------------------------------------------------------- /alibabacloud/clients/teslastream_20180115.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class TeslaStreamClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'TeslaStream' 29 | self.api_version = '2018-01-15' 30 | self.location_service_code = 'teslastream' 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def get_job_topology(self, job_name=None): 34 | api_request = APIRequest('GetJobTopology', 'GET', 'http', 'RPC', 'query') 35 | api_request._params = {"JobName": job_name} 36 | return self._handle_request(api_request).result 37 | 38 | def batch_get_plugin_config_info(self, plugin_infos=None): 39 | api_request = APIRequest('BatchGetPluginConfigInfo', 'GET', 'http', 'RPC', 'query') 40 | api_request._params = {"PluginInfos": plugin_infos} 41 | return self._handle_request(api_request).result 42 | 43 | def batch_get_job_metric_info(self, job_infos=None): 44 | api_request = APIRequest('BatchGetJobMetricInfo', 'GET', 'http', 'RPC', 'query') 45 | api_request._params = {"JobInfos": job_infos} 46 | return self._handle_request(api_request).result 47 | -------------------------------------------------------------------------------- /python-function-test/test_client.py: -------------------------------------------------------------------------------- 1 | import os 2 | # from base import TestCase 3 | from unittest import TestCase 4 | 5 | import alibabacloud 6 | from alibabacloud.clients.ecs_20140526 import EcsClient 7 | from alibabacloud.exceptions import ServiceNameInvalidException, ApiVersionInvalidException 8 | 9 | 10 | class AlibabaClientTest(TestCase): 11 | 12 | def setUp(self): 13 | self.access_key_id = os.environ.get("ACCESS_KEY_ID") 14 | self.access_key_secret = os.environ.get("ACCESS_KEY_SECRET") 15 | self.region_id = os.environ.get("REGION_ID") 16 | 17 | def test_ecs_client(self): 18 | client = alibabacloud.get_client(service_name='Ecs', api_version='2014-05-26', 19 | access_key_id=self.access_key_id, 20 | access_key_secret=self.access_key_secret, 21 | region_id=self.region_id) 22 | self.assertTrue(isinstance(client, EcsClient)) 23 | result = client.describe_regions() 24 | self.assertTrue(result.get('Regions')) 25 | 26 | def test_not_support_client(self): 27 | try: 28 | client = alibabacloud.get_client(service_name='Ems', api_version='2014-05-26', 29 | access_key_id=self.access_key_id, 30 | access_key_secret=self.access_key_secret, 31 | region_id=self.region_id) 32 | assert False 33 | except ServiceNameInvalidException as e: 34 | self.assertTrue(e.error_message, 'No such service_name Ems') 35 | 36 | def test_not_support_version(self): 37 | try: 38 | client = alibabacloud.get_client(service_name='ECS', api_version='2015-05-26', 39 | access_key_id=self.access_key_id, 40 | access_key_secret=self.access_key_secret, 41 | region_id=self.region_id) 42 | assert False 43 | except ApiVersionInvalidException as e: 44 | self.assertTrue(e.error_message, 45 | "ECS no such api_version '2015-05-26'. Please check your API Version.\n" 46 | "We now support api_version: 2014-05-26") 47 | -------------------------------------------------------------------------------- /alibabacloud/endpoint/location_endpoint_caller.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import threading 16 | 17 | from alibabacloud.client import AlibabaCloudClient 18 | from alibabacloud.request import APIRequest 19 | 20 | lock = threading.Lock() 21 | 22 | 23 | class MiniLocationClient(AlibabaCloudClient): 24 | 25 | def __init__(self, client_config, credentials_provider): 26 | AlibabaCloudClient.__init__(self, client_config, credentials_provider) 27 | 28 | self.product_code = "Location" 29 | self.api_version = "2015-06-12" 30 | self.location_service_code = None 31 | self.location_endpoint_type = "openAPI" 32 | 33 | def describe_endpoint(self, region_id=None, endpoint_type=None, 34 | location_service_code=None, location_endpoint=None): 35 | api_request = APIRequest('DescribeEndpoints', 'GET', 'https', 'RPC') 36 | api_request._params = { 37 | "Id": region_id, 38 | "Type": endpoint_type, 39 | "ServiceCode": location_service_code, 40 | } 41 | # TODO endpoint a special request 42 | self.config.endpoint = location_endpoint 43 | return self._handle_request(api_request) 44 | 45 | 46 | class DescribeEndpointCaller: 47 | 48 | def __init__(self, client_config, credentials_provider): 49 | # TODO enable https 50 | client_config.enable_https = True 51 | self._client = MiniLocationClient(client_config, credentials_provider) 52 | 53 | def fetch(self, region_id, endpoint_type, location_service_code, location_endpoint): 54 | return self._client.describe_endpoint(region_id, endpoint_type, 55 | location_service_code, location_endpoint) 56 | -------------------------------------------------------------------------------- /alibabacloud/handlers/signer_handler.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.compat import urlencode 16 | from alibabacloud.handlers import RequestHandler 17 | from alibabacloud.signer import Signer 18 | from alibabacloud.utils import format_type 19 | from alibabacloud.utils import parameter_helper as helper 20 | 21 | 22 | class SignerHandler(RequestHandler): 23 | content_md5 = "Content-MD5" 24 | content_length = "Content-Length" 25 | content_type = "Content-Type" 26 | """ 27 | handle signature, headers,params 28 | """ 29 | 30 | def handle_request(self, context): 31 | http_request = context.http_request 32 | api_request = context.api_request 33 | credentials = http_request.credentials 34 | 35 | signature, headers, params = Signer().sign(credentials, context) 36 | http_request.signature = signature 37 | http_request.params = params 38 | # modify headers 39 | body_params = api_request._body_params 40 | 41 | if body_params: 42 | body = urlencode(body_params) 43 | headers = self._modify_http_headers(headers, body, format_type.APPLICATION_FORM) 44 | context.http_request.headers = headers 45 | 46 | def _modify_http_headers(self, headers, body, format_type='JSON'): 47 | if body is None: 48 | headers.pop(self.content_md5, None) 49 | headers.pop(self.content_type, None) 50 | headers.pop(self.content_length, None) 51 | else: 52 | str_md5 = helper.md5_sum(body) 53 | content_length = len(body) 54 | headers[self.content_md5] = str_md5 55 | headers[self.content_length] = str(content_length) 56 | headers[self.content_type] = format_type 57 | return headers 58 | -------------------------------------------------------------------------------- /alibabacloud/clients/pts_20190522.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class PTSClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'PTS' 29 | self.api_version = '2019-05-22' 30 | self.location_service_code = None 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def get_aliware_report(self, report_id=None): 34 | api_request = APIRequest('GetAliwareReport', 'GET', 'http', 'RPC', 'query') 35 | api_request._params = {"ReportId": report_id} 36 | return self._handle_request(api_request).result 37 | 38 | def get_report(self, report_id=None): 39 | api_request = APIRequest('GetReport', 'GET', 'http', 'RPC', 'query') 40 | api_request._params = {"ReportId": report_id} 41 | return self._handle_request(api_request).result 42 | 43 | def start_scene(self, team_id=None, scene_id=None, user_id=None, task_id=None): 44 | api_request = APIRequest('StartScene', 'GET', 'http', 'RPC', 'query') 45 | api_request._params = { 46 | "TeamId": team_id, 47 | "SceneId": scene_id, 48 | "UserId": user_id, 49 | "TaskId": task_id} 50 | return self._handle_request(api_request).result 51 | -------------------------------------------------------------------------------- /python-function-test/alibabacloud_legacy_api_test.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import os 16 | 17 | from alibabacloud.clients.ecs_20140526 import EcsClient 18 | from base import SDKTestBase 19 | 20 | 21 | class AlibabaCloudTest(SDKTestBase): 22 | 23 | def test_config_enable_default(self): 24 | config = self.client_config 25 | self.assertEqual(config.enable_https, True) 26 | self.assertEqual(config.enable_retry, True) 27 | self.assertEqual(config.enable_http_debug, False) 28 | client = EcsClient(config, self.init_credentials_provider()) 29 | self.assertEqual(client.config.enable_https, True) 30 | self.assertEqual(client.config.enable_retry, True) 31 | self.assertEqual(client.config.enable_http_debug, False) 32 | 33 | def test_config_enable_custom(self): 34 | config = self.client_config 35 | config.enable_http_debug = True 36 | config.enable_https = False 37 | config.enable_retry = False 38 | client = EcsClient(config, self.init_credentials_provider()) 39 | self.assertEqual(client.config.enable_https, False) 40 | self.assertEqual(client.config.enable_retry, False) 41 | self.assertEqual(client.config.enable_http_debug, True) 42 | 43 | def test_config_from_env(self): 44 | config = self.client_config 45 | os.environ.setdefault('HTTPS_PROXY', 'https://alibabacloud-sdk.com') 46 | os.environ.setdefault('HTTP_PROXY', 'http://alibabacloud-sdk.com') 47 | os.environ.setdefault('DEBUG', 'sdk') 48 | 49 | client = EcsClient(config, self.init_credentials_provider()) 50 | self.assertEqual(client.config.enable_http_debug, False) 51 | os.environ.pop('HTTPS_PROXY') 52 | os.environ.pop('HTTP_PROXY') 53 | os.environ.pop('DEBUG') 54 | -------------------------------------------------------------------------------- /alibabacloud/compat.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import sys 16 | 17 | from alibabacloud.vendored import six 18 | 19 | 20 | if six.PY2: 21 | from base64 import encodestring as b64_encode_bytes 22 | from base64 import decodestring as b64_decode_bytes 23 | from urllib import urlencode 24 | 25 | def ensure_bytes(s, encoding='utf-8', errors='strict'): 26 | if isinstance(s, unicode): 27 | return s.encode(encoding, errors) 28 | if isinstance(s, str): 29 | return s 30 | raise ValueError("Expected str or unicode, received %s." % type(s)) 31 | 32 | def ensure_string(s, encoding='utf-8', errors='strict'): 33 | if isinstance(s, unicode): 34 | return s.encode(encoding, errors) 35 | if isinstance(s, str): 36 | return s 37 | raise ValueError("Expected str or unicode, received %s." % type(s)) 38 | 39 | else: 40 | from base64 import encodebytes as b64_encode_bytes 41 | from base64 import decodebytes as b64_decode_bytes 42 | from urllib.parse import urlencode 43 | 44 | def ensure_bytes(s, encoding='utf-8', errors='strict'): 45 | if isinstance(s, str): 46 | return bytes(s, encoding=encoding) 47 | if isinstance(s, bytes): 48 | return s 49 | if isinstance(s, bytearray): 50 | return bytes(s) 51 | raise ValueError( 52 | "Expected str or bytes or bytearray, received %s." % 53 | type(s)) 54 | 55 | def ensure_string(s, encoding='utf-8', errors='strict'): 56 | if isinstance(s, str): 57 | return s 58 | if isinstance(s, (bytes, bytearray)): 59 | return str(s, encoding='utf-8') 60 | raise ValueError( 61 | "Expected str or bytes or bytearray, received %s." % 62 | type(s)) 63 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # http://www.sphinx-doc.org/en/master/config 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | 13 | import os 14 | import sys 15 | sys.path.insert(0, os.path.dirname(os.path.abspath('..'))) 16 | import alibabacloud 17 | # -- Project information ----------------------------------------------------- 18 | 19 | project = '阿里云Python SDK使用文档' 20 | copyright = '2019, sdk' 21 | author = 'sdk' 22 | 23 | # The full version, including alpha/beta/rc tags 24 | release = '0.0.1' 25 | 26 | 27 | # -- General configuration --------------------------------------------------- 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = ['sphinx.ext.autodoc', 33 | 'sphinx.ext.doctest', 34 | 'sphinx.ext.intersphinx', 35 | 'sphinx.ext.mathjax', 36 | 'sphinx.ext.githubpages', 37 | 'sphinx.ext.todo', 38 | 'sphinx.ext.viewcode',] 39 | 40 | 41 | # Add any paths that contain templates here, relative to this directory. 42 | templates_path = ['_templates'] 43 | 44 | source_suffix = '.rst' 45 | 46 | master_doc = 'index' 47 | 48 | language = 'zh_CN' 49 | 50 | pygments_style = 'sphinx' 51 | 52 | # List of patterns, relative to source directory, that match files and 53 | # directories to ignore when looking for source files. 54 | # This pattern also affects html_static_path and html_extra_path. 55 | exclude_patterns = [] 56 | 57 | 58 | # -- Options for HTML output ------------------------------------------------- 59 | 60 | # The theme to use for HTML and HTML Help pages. See the documentation for 61 | # a list of builtin themes. 62 | # 63 | html_theme = 'sphinx_rtd_theme' 64 | # html_theme = 'alabaster' 65 | # html_theme = 'default' 66 | 67 | # Add any paths that contain custom static files (such as style sheets) here, 68 | # relative to this directory. They are copied after the builtin static files, 69 | # so a file named "default.css" will overwrite the builtin "default.css". 70 | html_static_path = ['_static'] 71 | 72 | 73 | -------------------------------------------------------------------------------- /alibabacloud/endpoint/default_endpoint_resolver.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2018 Alibaba Cloud Inc. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from alibabacloud.endpoint import EndpointResolver 17 | from alibabacloud.endpoint.chained_endpoint_resolver import ChainedEndpointResolver 18 | from alibabacloud.endpoint.local_config_global_endpoint_resolver \ 19 | import LocalConfigGlobalEndpointResolver 20 | from alibabacloud.endpoint.local_config_regional_endpoint_resolver \ 21 | import LocalConfigRegionalEndpointResolver 22 | from alibabacloud.endpoint.location_service_endpoint_resolver \ 23 | import LocationServiceEndpointResolver 24 | from alibabacloud.endpoint.user_customized_endpoint_resolver import UserCustomizedEndpointResolver 25 | 26 | 27 | class DefaultEndpointResolver(EndpointResolver): 28 | """ 29 | `Alibaba Cloud Python` endpoint resolve chain 30 | 31 | .. note:: 32 | Deprecated use for add_endpoint and modify_endpoint 33 | Not recommended 34 | 35 | """ 36 | predefined_endpoint_resolver = UserCustomizedEndpointResolver() 37 | 38 | def __init__(self, config, credentials_provider, user_config=None): 39 | self._user_customized_endpoint_resolver = UserCustomizedEndpointResolver() 40 | 41 | endpoint_resolvers = [ 42 | self.predefined_endpoint_resolver, 43 | self._user_customized_endpoint_resolver, 44 | LocalConfigRegionalEndpointResolver(user_config), 45 | LocalConfigGlobalEndpointResolver(user_config), 46 | LocationServiceEndpointResolver(config, credentials_provider), 47 | ] 48 | 49 | self._resolver = ChainedEndpointResolver(endpoint_resolvers) 50 | 51 | def resolve(self, request): 52 | return self._resolver.resolve(request) 53 | 54 | def put_endpoint_entry(self, region_id, product_code, endpoint): 55 | self._user_customized_endpoint_resolver.put_endpoint_entry(region_id, product_code, 56 | endpoint) 57 | -------------------------------------------------------------------------------- /tests/test_common_usage.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import unittest 16 | from tests.base import SDKTestBase 17 | import alibabacloud 18 | from alibabacloud.exceptions import ClientException, ServiceNameInvalidException 19 | 20 | 21 | class CommonTest(SDKTestBase): 22 | 23 | def test_get_resource_with_invalid_resource_name(self): 24 | try: 25 | ecs = alibabacloud.get_resource("blah") 26 | assert False 27 | except ServiceNameInvalidException as e: 28 | self.assertTrue(e.error_message.startswith("No such service_name 'blah'. Please check your Service Name.")) 29 | 30 | def test_get_resource(self): 31 | alibabacloud.get_resource("ecs", 32 | access_key_id=self.access_key_id, 33 | access_key_secret=self.access_key_secret, 34 | region_id=self.region_id) 35 | alibabacloud.get_resource("ecs.instance", "i-instance-id", 36 | access_key_id=self.access_key_id, 37 | access_key_secret=self.access_key_secret, 38 | region_id=self.region_id) 39 | alibabacloud.get_resource("ecs.system_event", "e-event-id", 40 | access_key_id=self.access_key_id, 41 | access_key_secret=self.access_key_secret, 42 | region_id=self.region_id) 43 | 44 | def test_get_resource_failed(self): 45 | try: 46 | alibabacloud.get_resource("ecs.instance", 47 | access_key_id=self.access_key_id, 48 | access_key_secret=self.access_key_secret, 49 | region_id=self.region_id) 50 | assert False 51 | except ClientException as e: 52 | self.assertEqual(e.error_message, "Parameter resource_id required.") 53 | 54 | 55 | if __name__ == '__main__': 56 | unittest.main() 57 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/urllib3/util/response.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from ..packages.six.moves import http_client as httplib 3 | 4 | from ..exceptions import HeaderParsingError 5 | 6 | 7 | def is_fp_closed(obj): 8 | """ 9 | Checks whether a given file-like object is closed. 10 | 11 | :param obj: 12 | The file-like object to check. 13 | """ 14 | 15 | try: 16 | # Check `isclosed()` first, in case Python3 doesn't set `closed`. 17 | # GH Issue #928 18 | return obj.isclosed() 19 | except AttributeError: 20 | pass 21 | 22 | try: 23 | # Check via the official file-like-object way. 24 | return obj.closed 25 | except AttributeError: 26 | pass 27 | 28 | try: 29 | # Check if the object is a container for another file-like object that 30 | # gets released on exhaustion (e.g. HTTPResponse). 31 | return obj.fp is None 32 | except AttributeError: 33 | pass 34 | 35 | raise ValueError("Unable to determine whether fp is closed.") 36 | 37 | 38 | def assert_header_parsing(headers): 39 | """ 40 | Asserts whether all headers have been successfully parsed. 41 | Extracts encountered errors from the result of parsing headers. 42 | 43 | Only works on Python 3. 44 | 45 | :param headers: Headers to verify. 46 | :type headers: `httplib.HTTPMessage`. 47 | 48 | :raises urllib3.exceptions.HeaderParsingError: 49 | If parsing errors are found. 50 | """ 51 | 52 | # This will fail silently if we pass in the wrong kind of parameter. 53 | # To make debugging easier add an explicit check. 54 | if not isinstance(headers, httplib.HTTPMessage): 55 | raise TypeError('expected httplib.Message, got {0}.'.format( 56 | type(headers))) 57 | 58 | defects = getattr(headers, 'defects', None) 59 | get_payload = getattr(headers, 'get_payload', None) 60 | 61 | unparsed_data = None 62 | if get_payload: # Platform-specific: Python 3. 63 | unparsed_data = get_payload() 64 | 65 | if defects or unparsed_data: 66 | raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) 67 | 68 | 69 | def is_response_to_head(response): 70 | """ 71 | Checks whether the request of a response has been a HEAD-request. 72 | Handles the quirks of AppEngine. 73 | 74 | :param conn: 75 | :type conn: :class:`httplib.HTTPResponse` 76 | """ 77 | # FIXME: Can we do this somehow without accessing private httplib _method? 78 | method = response._method 79 | if isinstance(method, int): # Platform-specific: Appengine 80 | return method == 3 81 | return method.upper() == 'HEAD' 82 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/urllib3/filepost.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | import codecs 3 | 4 | from uuid import uuid4 5 | from io import BytesIO 6 | 7 | from .packages import six 8 | from .packages.six import b 9 | from .fields import RequestField 10 | 11 | writer = codecs.lookup('utf-8')[3] 12 | 13 | 14 | def choose_boundary(): 15 | """ 16 | Our embarrassingly-simple replacement for mimetools.choose_boundary. 17 | """ 18 | return uuid4().hex 19 | 20 | 21 | def iter_field_objects(fields): 22 | """ 23 | Iterate over fields. 24 | 25 | Supports list of (k, v) tuples and dicts, and lists of 26 | :class:`~urllib3.fields.RequestField`. 27 | 28 | """ 29 | if isinstance(fields, dict): 30 | i = six.iteritems(fields) 31 | else: 32 | i = iter(fields) 33 | 34 | for field in i: 35 | if isinstance(field, RequestField): 36 | yield field 37 | else: 38 | yield RequestField.from_tuples(*field) 39 | 40 | 41 | def iter_fields(fields): 42 | """ 43 | .. deprecated:: 1.6 44 | 45 | Iterate over fields. 46 | 47 | The addition of :class:`~urllib3.fields.RequestField` makes this function 48 | obsolete. Instead, use :func:`iter_field_objects`, which returns 49 | :class:`~urllib3.fields.RequestField` objects. 50 | 51 | Supports list of (k, v) tuples and dicts. 52 | """ 53 | if isinstance(fields, dict): 54 | return ((k, v) for k, v in six.iteritems(fields)) 55 | 56 | return ((k, v) for k, v in fields) 57 | 58 | 59 | def encode_multipart_formdata(fields, boundary=None): 60 | """ 61 | Encode a dictionary of ``fields`` using the multipart/form-data MIME format. 62 | 63 | :param fields: 64 | Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). 65 | 66 | :param boundary: 67 | If not specified, then a random boundary will be generated using 68 | :func:`mimetools.choose_boundary`. 69 | """ 70 | body = BytesIO() 71 | if boundary is None: 72 | boundary = choose_boundary() 73 | 74 | for field in iter_field_objects(fields): 75 | body.write(b('--%s\r\n' % (boundary))) 76 | 77 | writer(body).write(field.render_headers()) 78 | data = field.data 79 | 80 | if isinstance(data, int): 81 | data = str(data) # Backwards compatibility 82 | 83 | if isinstance(data, six.text_type): 84 | writer(body).write(data) 85 | else: 86 | body.write(data) 87 | 88 | body.write(b'\r\n') 89 | 90 | body.write(b('--%s--\r\n' % (boundary))) 91 | 92 | content_type = str('multipart/form-data; boundary=%s' % boundary) 93 | 94 | return body.getvalue(), content_type 95 | -------------------------------------------------------------------------------- /alibabacloud/clients/alimt_20190107.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class AlimtClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'alimt' 29 | self.api_version = '2019-01-07' 30 | self.location_service_code = 'alimt' 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def translate_general( 34 | self, 35 | source_language=None, 36 | source_text=None, 37 | format_type=None, 38 | target_language=None, 39 | scene=None): 40 | api_request = APIRequest('TranslateGeneral', 'GET', 'http', 'RPC', 'query') 41 | api_request._params = { 42 | "SourceLanguage": source_language, 43 | "SourceText": source_text, 44 | "FormatType": format_type, 45 | "TargetLanguage": target_language, 46 | "Scene": scene} 47 | return self._handle_request(api_request).result 48 | 49 | def translate_ecommerce( 50 | self, 51 | source_language=None, 52 | source_text=None, 53 | format_type=None, 54 | target_language=None, 55 | scene=None): 56 | api_request = APIRequest('TranslateECommerce', 'GET', 'http', 'RPC', 'query') 57 | api_request._params = { 58 | "SourceLanguage": source_language, 59 | "SourceText": source_text, 60 | "FormatType": format_type, 61 | "TargetLanguage": target_language, 62 | "Scene": scene} 63 | return self._handle_request(api_request).result 64 | -------------------------------------------------------------------------------- /alibabacloud/utils/ini_helper.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import os 16 | 17 | from alibabacloud.exceptions import ClientException, ConfigNotFoundException 18 | from alibabacloud.vendored import six 19 | 20 | 21 | # parse ini file 22 | def _parse_nested(config_value): 23 | parsed = {} 24 | for line in config_value.splitlines(): 25 | line = line.strip() 26 | if not line: 27 | continue 28 | key, value = line.split('=', 1) 29 | parsed[key.strip()] = value.strip() 30 | return parsed 31 | 32 | 33 | def raw_config_parse(config_filename, parse_subsections=True): 34 | config = {} 35 | path = config_filename 36 | if path is not None: 37 | path = os.path.expandvars(path) 38 | path = os.path.expanduser(path) 39 | if not os.path.isfile(path): 40 | raise ConfigNotFoundException(path=path) 41 | cp = six.moves.configparser.RawConfigParser() 42 | try: 43 | cp.read([path]) 44 | except six.moves.configparser.ParsingError: 45 | raise ClientException( 46 | msg='Credentials file (%s) format is incorrect.' % path 47 | ) 48 | except six.moves.configparser.Error: 49 | raise ClientException( 50 | msg='Cannot read credentials from (%s).' % path 51 | ) 52 | else: 53 | for section in cp.sections(): 54 | config[section] = {} 55 | for option in cp.options(section): 56 | 57 | config_value = cp.get(section, option) 58 | 59 | if parse_subsections and config_value.startswith('\n'): 60 | try: 61 | config_value = _parse_nested(config_value) 62 | except ValueError: 63 | raise ClientException( 64 | msg='Unable to parse ini file: %s.' % path 65 | ) 66 | config[section][option] = config_value 67 | return config 68 | 69 | 70 | def load_config(config_filename): 71 | parsed = raw_config_parse(config_filename) 72 | return parsed 73 | -------------------------------------------------------------------------------- /alibabacloud/endpoint/chained_endpoint_resolver.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with self work for additional information 4 | # regarding copyright ownership. The ASF licenses self file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use self file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | from alibabacloud.endpoint import EndpointResolver 19 | from alibabacloud.exceptions import InvalidProductCodeException, \ 20 | InvalidRegionIDException, NoSuchEndpointException 21 | 22 | 23 | class ChainedEndpointResolver(EndpointResolver): 24 | 25 | def __init__(self, resolver_chain): 26 | EndpointResolver.__init__(self) 27 | self.endpoint_resolvers = resolver_chain 28 | 29 | def _check_product_code(self, request): 30 | for resolver in self.endpoint_resolvers: 31 | if resolver.is_product_code_valid(request): 32 | return 33 | raise InvalidProductCodeException(product_code=request.product_code) 34 | 35 | def _check_region_id(self, request): 36 | for resolver in self.endpoint_resolvers: 37 | if resolver.is_region_id_valid(request): 38 | return 39 | raise InvalidRegionIDException(region_id=request.region_id) 40 | 41 | def _get_available_regions_hint(self, product_code): 42 | regions = None 43 | hint = "" 44 | for resolver in self.endpoint_resolvers: 45 | regions = resolver.get_valid_region_ids_by_product(product_code) 46 | if regions is not None: 47 | hint = "\nOr you can use the other available regions:" 48 | for region in regions: 49 | hint += " " + region 50 | break 51 | return hint 52 | 53 | def resolve(self, request): 54 | for resolver in self.endpoint_resolvers: 55 | endpoint = resolver.resolve(request) 56 | if endpoint is not None: 57 | return endpoint 58 | 59 | self._check_product_code(request) 60 | self._check_region_id(request) 61 | 62 | raise NoSuchEndpointException( 63 | region_id=request.region_id, 64 | product_code=request.product_code, 65 | more=self._get_available_regions_hint(request.product_code) 66 | ) 67 | -------------------------------------------------------------------------------- /alibabacloud/clients/sts_20150401.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class StsClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'Sts' 29 | self.api_version = '2015-04-01' 30 | self.location_service_code = 'sts' 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def assume_role_with_saml( 34 | self, 35 | role_arn=None, 36 | saml_provider_arn=None, 37 | saml_assertion=None, 38 | duration_seconds=None, 39 | policy=None): 40 | api_request = APIRequest('AssumeRoleWithSAML', 'GET', 'https', 'RPC', 'query') 41 | api_request._params = { 42 | "RoleArn": role_arn, 43 | "SAMLProviderArn": saml_provider_arn, 44 | "SAMLAssertion": saml_assertion, 45 | "DurationSeconds": duration_seconds, 46 | "Policy": policy} 47 | return self._handle_request(api_request).result 48 | 49 | def get_caller_identity(self,): 50 | api_request = APIRequest('GetCallerIdentity', 'GET', 'https', 'RPC', '') 51 | 52 | return self._handle_request(api_request).result 53 | 54 | def assume_role( 55 | self, 56 | role_arn=None, 57 | role_session_name=None, 58 | duration_seconds=None, 59 | policy=None): 60 | api_request = APIRequest('AssumeRole', 'GET', 'https', 'RPC', 'query') 61 | api_request._params = { 62 | "RoleArn": role_arn, 63 | "RoleSessionName": role_session_name, 64 | "DurationSeconds": duration_seconds, 65 | "Policy": policy} 66 | return self._handle_request(api_request).result 67 | -------------------------------------------------------------------------------- /alibabacloud/clients/ubsms_20150623.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class UbsmsClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'Ubsms' 29 | self.api_version = '2015-06-23' 30 | self.location_service_code = 'ubsms' 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def describe_business_status(self, password=None, caller_bid=None): 34 | api_request = APIRequest('DescribeBusinessStatus', 'GET', 'http', 'RPC', 'query') 35 | api_request._params = {"Password": password, "callerBid": caller_bid} 36 | return self._handle_request(api_request).result 37 | 38 | def notify_user_business_command( 39 | self, 40 | uid=None, 41 | password=None, 42 | instance_id=None, 43 | service_code=None, 44 | client_token=None, 45 | cmd=None, 46 | region=None): 47 | api_request = APIRequest('NotifyUserBusinessCommand', 'GET', 'http', 'RPC', 'query') 48 | api_request._params = { 49 | "Uid": uid, 50 | "Password": password, 51 | "InstanceId": instance_id, 52 | "ServiceCode": service_code, 53 | "ClientToken": client_token, 54 | "Cmd": cmd, 55 | "Region": region} 56 | return self._handle_request(api_request).result 57 | 58 | def set_user_business_status(self, uid=None, status_value=None, service=None, status_key=None): 59 | api_request = APIRequest('SetUserBusinessStatus', 'GET', 'http', 'RPC', 'query') 60 | api_request._params = { 61 | "Uid": uid, 62 | "StatusValue": status_value, 63 | "Service": service, 64 | "StatusKey": status_key} 65 | return self._handle_request(api_request).result 66 | -------------------------------------------------------------------------------- /alibabacloud/handlers/timeout_config_reader.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import jmespath 16 | 17 | from alibabacloud.exceptions import ClientException, ParamTypeInvalidException 18 | from alibabacloud.handlers import RequestHandler 19 | from alibabacloud.utils import load_json_from_data_dir 20 | 21 | DEFAULT_READ_TIMEOUT = 10 22 | DEFAULT_CONNECTION_TIMEOUT = 5 23 | _api_timeout_config_data = load_json_from_data_dir._load_json_from_data_dir("timeout_config.json") 24 | 25 | 26 | class TimeoutConfigReader(RequestHandler): 27 | def handle_request(self, context): 28 | context.http_request.timeout = (self._connection_timeout(context.config.connection_timeout), 29 | self._read_timeout(context)) 30 | 31 | @staticmethod 32 | def _valid_timeout_value(timeout, name): 33 | if isinstance(timeout, int) or isinstance(timeout, float): 34 | if timeout > 0: 35 | return timeout 36 | raise ParamTypeInvalidException(param=name, param_type='positive integer') 37 | elif isinstance(timeout, str) and timeout.isdigit(): 38 | if float(timeout) > 0: 39 | return float(timeout) 40 | raise ParamTypeInvalidException(param=name, param_type='positive integer') 41 | raise ParamTypeInvalidException(param=name, param_type='float or int or str') 42 | 43 | def _connection_timeout(self, connection_timeout): 44 | connection_timeout = self._valid_timeout_value(connection_timeout, 'connection_timeout') \ 45 | if connection_timeout else None 46 | 47 | return connection_timeout or DEFAULT_CONNECTION_TIMEOUT 48 | 49 | def _read_timeout(self, context): 50 | read_timeout = self._valid_timeout_value(context.config.read_timeout, 'read_timeout') \ 51 | if context.config.read_timeout else None 52 | file_read_timeout = None 53 | product_code = context.client.product_code 54 | api_version = context.client.api_version 55 | action_name = context.api_request.action_name 56 | if product_code is not None and api_version is not None \ 57 | and action_name is not None: 58 | path = '"{0}"."{1}"."{2}"'.format(product_code.lower(), api_version, 59 | action_name) 60 | file_read_timeout = jmespath.search(path, _api_timeout_config_data) 61 | return read_timeout or file_read_timeout or DEFAULT_READ_TIMEOUT 62 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/cli/chardetect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Script which takes one or more file paths and reports on their detected 4 | encodings 5 | 6 | Example:: 7 | 8 | % chardetect somefile someotherfile 9 | somefile: windows-1252 with confidence 0.5 10 | someotherfile: ascii with confidence 1.0 11 | 12 | If no paths are provided, it takes its input from stdin. 13 | 14 | """ 15 | 16 | from __future__ import absolute_import, print_function, unicode_literals 17 | 18 | import argparse 19 | import sys 20 | 21 | from chardet import __version__ 22 | from chardet.compat import PY2 23 | from chardet.universaldetector import UniversalDetector 24 | 25 | 26 | def description_of(lines, name='stdin'): 27 | """ 28 | Return a string describing the probable encoding of a file or 29 | list of strings. 30 | 31 | :param lines: The lines to get the encoding of. 32 | :type lines: Iterable of bytes 33 | :param name: Name of file or collection of lines 34 | :type name: str 35 | """ 36 | u = UniversalDetector() 37 | for line in lines: 38 | line = bytearray(line) 39 | u.feed(line) 40 | # shortcut out of the loop to save reading further - particularly useful if we read a BOM. 41 | if u.done: 42 | break 43 | u.close() 44 | result = u.result 45 | if PY2: 46 | name = name.decode(sys.getfilesystemencoding(), 'ignore') 47 | if result['encoding']: 48 | return '{0}: {1} with confidence {2}'.format(name, result['encoding'], 49 | result['confidence']) 50 | else: 51 | return '{0}: no result'.format(name) 52 | 53 | 54 | def main(argv=None): 55 | """ 56 | Handles command line arguments and gets things started. 57 | 58 | :param argv: List of arguments, as if specified on the command-line. 59 | If None, ``sys.argv[1:]`` is used instead. 60 | :type argv: list of str 61 | """ 62 | # Get command line arguments 63 | parser = argparse.ArgumentParser( 64 | description="Takes one or more file paths and reports their detected \ 65 | encodings") 66 | parser.add_argument('input', 67 | help='File whose encoding we would like to determine. \ 68 | (default: stdin)', 69 | type=argparse.FileType('rb'), nargs='*', 70 | default=[sys.stdin if PY2 else sys.stdin.buffer]) 71 | parser.add_argument('--version', action='version', 72 | version='%(prog)s {0}'.format(__version__)) 73 | args = parser.parse_args(argv) 74 | 75 | for f in args.input: 76 | if f.isatty(): 77 | print("You are running chardetect interactively. Press " + 78 | "CTRL-D twice at the start of a blank line to signal the " + 79 | "end of your input. If you want help, run chardetect " + 80 | "--help\n", file=sys.stderr) 81 | print(description_of(f, f.name)) 82 | 83 | 84 | if __name__ == '__main__': 85 | main() 86 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/chardet/utf8prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .charsetprober import CharSetProber 29 | from .enums import ProbingState, MachineState 30 | from .codingstatemachine import CodingStateMachine 31 | from .mbcssm import UTF8_SM_MODEL 32 | 33 | 34 | 35 | class UTF8Prober(CharSetProber): 36 | ONE_CHAR_PROB = 0.5 37 | 38 | def __init__(self): 39 | super(UTF8Prober, self).__init__() 40 | self.coding_sm = CodingStateMachine(UTF8_SM_MODEL) 41 | self._num_mb_chars = None 42 | self.reset() 43 | 44 | def reset(self): 45 | super(UTF8Prober, self).reset() 46 | self.coding_sm.reset() 47 | self._num_mb_chars = 0 48 | 49 | @property 50 | def charset_name(self): 51 | return "utf-8" 52 | 53 | @property 54 | def language(self): 55 | return "" 56 | 57 | def feed(self, byte_str): 58 | for c in byte_str: 59 | coding_state = self.coding_sm.next_state(c) 60 | if coding_state == MachineState.ERROR: 61 | self._state = ProbingState.NOT_ME 62 | break 63 | elif coding_state == MachineState.ITS_ME: 64 | self._state = ProbingState.FOUND_IT 65 | break 66 | elif coding_state == MachineState.START: 67 | if self.coding_sm.get_current_charlen() >= 2: 68 | self._num_mb_chars += 1 69 | 70 | if self.state == ProbingState.DETECTING: 71 | if self.get_confidence() > self.SHORTCUT_THRESHOLD: 72 | self._state = ProbingState.FOUND_IT 73 | 74 | return self.state 75 | 76 | def get_confidence(self): 77 | unlike = 0.99 78 | if self._num_mb_chars < 6: 79 | unlike *= self.ONE_CHAR_PROB ** self._num_mb_chars 80 | return 1.0 - unlike 81 | else: 82 | return unlike 83 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/packages/urllib3/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | urllib3 - Thread-safe connection pooling and re-using. 3 | """ 4 | 5 | from __future__ import absolute_import 6 | import warnings 7 | 8 | from .connectionpool import ( 9 | HTTPConnectionPool, 10 | HTTPSConnectionPool, 11 | connection_from_url 12 | ) 13 | 14 | from . import exceptions 15 | from .filepost import encode_multipart_formdata 16 | from .poolmanager import PoolManager, ProxyManager, proxy_from_url 17 | from .response import HTTPResponse 18 | from .util.request import make_headers 19 | from .util.url import get_host 20 | from .util.timeout import Timeout 21 | from .util.retry import Retry 22 | 23 | 24 | # Set default logging handler to avoid "No handler found" warnings. 25 | import logging 26 | try: # Python 2.7+ 27 | from logging import NullHandler 28 | except ImportError: 29 | class NullHandler(logging.Handler): 30 | def emit(self, record): 31 | pass 32 | 33 | __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)' 34 | __license__ = 'MIT' 35 | __version__ = '1.21.1' 36 | 37 | __all__ = ( 38 | 'HTTPConnectionPool', 39 | 'HTTPSConnectionPool', 40 | 'PoolManager', 41 | 'ProxyManager', 42 | 'HTTPResponse', 43 | 'Retry', 44 | 'Timeout', 45 | 'add_stderr_logger', 46 | 'connection_from_url', 47 | 'disable_warnings', 48 | 'encode_multipart_formdata', 49 | 'get_host', 50 | 'make_headers', 51 | 'proxy_from_url', 52 | ) 53 | 54 | logging.getLogger(__name__).addHandler(NullHandler()) 55 | 56 | 57 | def add_stderr_logger(level=logging.DEBUG): 58 | """ 59 | Helper for quickly adding a StreamHandler to the logger. Useful for 60 | debugging. 61 | 62 | Returns the handler after adding it. 63 | """ 64 | # This method needs to be in this __init__.py to get the __name__ correct 65 | # even if urllib3 is vendored within another package. 66 | logger = logging.getLogger(__name__) 67 | handler = logging.StreamHandler() 68 | handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) 69 | logger.addHandler(handler) 70 | logger.setLevel(level) 71 | logger.debug('Added a stderr logging handler to logger: %s', __name__) 72 | return handler 73 | 74 | 75 | # ... Clean up. 76 | del NullHandler 77 | 78 | 79 | # All warning filters *must* be appended unless you're really certain that they 80 | # shouldn't be: otherwise, it's very hard for users to use most Python 81 | # mechanisms to silence them. 82 | # SecurityWarning's always go off by default. 83 | warnings.simplefilter('always', exceptions.SecurityWarning, append=True) 84 | # SubjectAltNameWarning's should go off once per host 85 | warnings.simplefilter('default', exceptions.SubjectAltNameWarning, append=True) 86 | # InsecurePlatformWarning's don't vary between requests, so we keep it default. 87 | warnings.simplefilter('default', exceptions.InsecurePlatformWarning, 88 | append=True) 89 | # SNIMissingWarnings should go off only once. 90 | warnings.simplefilter('default', exceptions.SNIMissingWarning, append=True) 91 | 92 | 93 | def disable_warnings(category=exceptions.HTTPWarning): 94 | """ 95 | Helper for quickly disabling all urllib3 warnings. 96 | """ 97 | warnings.simplefilter('ignore', category) 98 | -------------------------------------------------------------------------------- /alibabacloud/clients/oms_20150212.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class OmsClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'Oms' 29 | self.api_version = '2015-02-12' 30 | self.location_service_code = 'oms' 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def get_data_open_config( 34 | self, 35 | data_type=None, 36 | product_name=None, 37 | table_name=None, 38 | site_bid=None): 39 | api_request = APIRequest('GetDataOpenConfig', 'GET', 'http', 'RPC', 'query') 40 | api_request._params = { 41 | "DataType": data_type, 42 | "ProductName": product_name, 43 | "TableName": table_name, 44 | "SiteBid": site_bid} 45 | return self._handle_request(api_request).result 46 | 47 | def get_product_define(self, data_type=None, product_name=None, site_bid=None): 48 | api_request = APIRequest('GetProductDefine', 'GET', 'http', 'RPC', 'query') 49 | api_request._params = { 50 | "DataType": data_type, 51 | "ProductName": product_name, 52 | "siteBid": site_bid} 53 | return self._handle_request(api_request).result 54 | 55 | def get_user_data( 56 | self, 57 | data_type=None, 58 | next_token=None, 59 | owner_account=None, 60 | product_name=None, 61 | end_time=None, 62 | start_time=None, 63 | owner_id=None, 64 | table_name=None, 65 | max_result=None): 66 | api_request = APIRequest('GetUserData', 'GET', 'http', 'RPC', 'query') 67 | api_request._params = { 68 | "DataType": data_type, 69 | "NextToken": next_token, 70 | "OwnerAccount": owner_account, 71 | "ProductName": product_name, 72 | "EndTime": end_time, 73 | "StartTime": start_time, 74 | "OwnerId": owner_id, 75 | "TableName": table_name, 76 | "MaxResult": max_result} 77 | return self._handle_request(api_request).result 78 | -------------------------------------------------------------------------------- /tests/base.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import json 16 | import os 17 | import re 18 | import sys 19 | import alibabacloud 20 | import alibabacloud.utils 21 | 22 | 23 | # The unittest module got a significant overhaul 24 | # in 2.7, so if we're in 2.6 we can use the backported 25 | # version unittest2. 26 | if sys.version_info[:2] == (2, 6): 27 | from unittest2 import TestCase 28 | else: 29 | from unittest import TestCase 30 | 31 | 32 | class SDKTestBase(TestCase): 33 | 34 | def __init__(self, *args, **kwargs): 35 | TestCase.__init__(self, *args, **kwargs) 36 | alibabacloud.utils._test_flag = True 37 | if sys.version_info[0] == 2: 38 | self.assertRegex = self.assertRegexpMatches 39 | 40 | self._sdk_config = self._init_sdk_config() 41 | self.access_key_id = self._read_key_from_env_or_config("ACCESS_KEY_ID") 42 | self.access_key_secret = self._read_key_from_env_or_config("ACCESS_KEY_SECRET") 43 | self.region_id = self._read_key_from_env_or_config("REGION_ID") 44 | self.ecs = self._get_ecs_resource() 45 | 46 | def _convert_camel_to_snake(self, name): 47 | # covert name from camel case to snake case 48 | # e.g: InstanceName -> instance_name 49 | s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) 50 | return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() 51 | 52 | def _init_sdk_config(self): 53 | sdk_config_path = os.path.join(os.path.expanduser("~"), "aliyun_sdk_config.json") 54 | if os.path.isfile(sdk_config_path): 55 | with open(sdk_config_path) as fp: 56 | return json.loads(fp.read()) 57 | 58 | def _read_key_from_env_or_config(self, key_name): 59 | if key_name.upper() in os.environ: 60 | return os.environ.get(key_name.upper()) 61 | if self._sdk_config is not None and key_name.lower() in self._sdk_config: 62 | return self._sdk_config[key_name.lower()] 63 | 64 | raise Exception("Failed to find sdk config: " + key_name) 65 | 66 | def _get_resource(self, *args, **kwargs): 67 | ecs_resource = alibabacloud.get_resource(*args, access_key_id=self.access_key_id, 68 | access_key_secret=self.access_key_secret, 69 | region_id=self.region_id, **kwargs) 70 | return ecs_resource 71 | 72 | def _get_ecs_resource(self, **kwargs): 73 | return self._get_resource("ecs", **kwargs) 74 | 75 | def create_simple_instance(self): 76 | instance = self.ecs.create_instance( 77 | ImageId="coreos_1745_7_0_64_30G_alibase_20180705.vhd", 78 | InstanceType="ecs.n2.small", 79 | ) 80 | 81 | return instance 82 | -------------------------------------------------------------------------------- /alibabacloud/request.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | 17 | class APIRequest: 18 | """ 19 | `Alibaba Cloud Python` SDK 的请求基类 20 | """ 21 | 22 | def __init__(self, action_name, method, scheme, style, param_position="query"): 23 | self.action_name = action_name 24 | self.scheme = scheme # http|https 25 | self.method = method 26 | self.style = style 27 | self._param_position = param_position 28 | self._params = {} 29 | self.uri_pattern = '' 30 | self.path_params = {} 31 | 32 | self._headers = {} 33 | self._body_params = {} 34 | self._query_params = {} 35 | self._content = None 36 | 37 | def _load_from_legacy_request(self, request): 38 | # request:acsrequest 39 | 40 | # FIXME content 41 | self._content = request._content 42 | 43 | self._body_params = request._body_params 44 | self._query_params = request._params 45 | 46 | if self.style == 'ROA': 47 | self.uri_pattern = request._uri_pattern 48 | self.path_params = request._path_params 49 | return self 50 | 51 | @property 52 | def params(self): 53 | return self._params 54 | 55 | 56 | class APIResponse: 57 | pass 58 | 59 | 60 | class HTTPRequest: 61 | 62 | def __init__(self, accept_format=None, method=None, scheme=None, proxy=None, 63 | signature=None, port=None, 64 | headers=None, url=None, endpoint=None, timeout=None, 65 | body="", retries=0, credentials=None, verify=None): 66 | self.accept_format = accept_format 67 | self.body = body 68 | self.method = method 69 | self.scheme = scheme 70 | self.proxy = proxy 71 | self.port = port 72 | self.headers = headers 73 | self.url = url 74 | self.timeout = timeout 75 | self.signature = signature 76 | self.endpoint = endpoint 77 | self.retries = retries 78 | self.credentials = credentials 79 | self.verify = verify 80 | 81 | 82 | class HTTPResponse: 83 | 84 | def __init__(self, url, status_code, headers, raw): 85 | self.url = url 86 | self.status_code = status_code 87 | self.headers = headers 88 | self.raw = raw 89 | 90 | self._content = None 91 | 92 | @property 93 | def content(self): 94 | if self._content is None: 95 | self._content = bytes(self.raw, encoding='utf-8') if self.raw else bytes() 96 | return self._content 97 | 98 | @property 99 | def text(self): 100 | return self.content.decode('utf-8') 101 | -------------------------------------------------------------------------------- /alibabacloud/clients/yundun_20150227.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class YundunClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'Yundun' 29 | self.api_version = '2015-02-27' 30 | self.location_service_code = 'yundun' 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def web_attack_num(self,): 34 | api_request = APIRequest('WebAttackNum', 'GET', 'http', 'RPC', '') 35 | 36 | return self._handle_request(api_request).result 37 | 38 | def todayqps_by_region(self,): 39 | api_request = APIRequest('TodayqpsByRegion', 'GET', 'http', 'RPC', '') 40 | 41 | return self._handle_request(api_request).result 42 | 43 | def today_malware_num(self,): 44 | api_request = APIRequest('TodayMalwareNum', 'GET', 'http', 'RPC', '') 45 | 46 | return self._handle_request(api_request).result 47 | 48 | def today_crack_intercept(self,): 49 | api_request = APIRequest('TodayCrackIntercept', 'GET', 'http', 'RPC', '') 50 | 51 | return self._handle_request(api_request).result 52 | 53 | def today_backdoor(self,): 54 | api_request = APIRequest('TodayBackdoor', 'GET', 'http', 'RPC', '') 55 | 56 | return self._handle_request(api_request).result 57 | 58 | def today_allpps(self,): 59 | api_request = APIRequest('TodayAllpps', 'GET', 'http', 'RPC', '') 60 | 61 | return self._handle_request(api_request).result 62 | 63 | def today_allkbps(self,): 64 | api_request = APIRequest('TodayAllkbps', 'GET', 'http', 'RPC', '') 65 | 66 | return self._handle_request(api_request).result 67 | 68 | def today_aegis_online_rate(self,): 69 | api_request = APIRequest('TodayAegisOnlineRate', 'GET', 'http', 'RPC', '') 70 | 71 | return self._handle_request(api_request).result 72 | 73 | def current_ddos_attack_num(self,): 74 | api_request = APIRequest('CurrentDdosAttackNum', 'GET', 'http', 'RPC', '') 75 | 76 | return self._handle_request(api_request).result 77 | 78 | def all_malware_num(self,): 79 | api_request = APIRequest('AllMalwareNum', 'GET', 'http', 'RPC', '') 80 | 81 | return self._handle_request(api_request).result 82 | -------------------------------------------------------------------------------- /alibabacloud/handlers/retry_handler.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import alibabacloud.utils.parameter_helper 16 | from alibabacloud.handlers import RequestHandler 17 | from alibabacloud.retry.retry_condition import RetryCondition 18 | from alibabacloud.retry.retry_policy_context import RetryPolicyContext 19 | 20 | 21 | class RetryHandler(RequestHandler): 22 | 23 | def handle_request(self, context): 24 | 25 | client = context.client 26 | product_code = client.product_code.lower() if client.product_code else None 27 | 28 | if context.http_request.retries == 0: 29 | retry_policy_context = RetryPolicyContext(context.api_request, None, 0, None, 30 | product_code, client.api_version, 31 | context.client.logger) 32 | if context.client.retry_policy.should_retry(retry_policy_context) & \ 33 | RetryCondition.SHOULD_RETRY_WITH_CLIENT_TOKEN: 34 | self._add_request_client_token(context.api_request) 35 | 36 | def handle_response(self, context): 37 | client = context.client 38 | api_request = context.api_request 39 | product_code = client.product_code.lower() if client.product_code else None 40 | 41 | retry_policy_context = RetryPolicyContext(api_request, context.exception, 42 | context.http_request.retries, 43 | context.http_response.status_code, 44 | product_code, client.api_version, 45 | context.client.logger) 46 | 47 | should_retry = context.client.retry_policy.should_retry(retry_policy_context) 48 | if should_retry & RetryCondition.NO_RETRY: 49 | context.retry_flag = False 50 | else: 51 | 52 | retry_policy_context.retryable = should_retry 53 | context.http_request.retries += 1 54 | context.retry_flag = True 55 | context.retry_backoff = context.client.retry_policy.compute_delay_before_next_retry( 56 | retry_policy_context 57 | ) 58 | context.client.logger.debug("Retry needed. Request:%s Retries :%d", 59 | api_request.action_name, context.http_request.retries) 60 | 61 | @staticmethod 62 | def _add_request_client_token(request): 63 | # TODO implement: add a ClientToken parameter on api_request 64 | client_token = request.params.get('ClientToken') 65 | if not client_token: 66 | # ClientToken has not been set 67 | client_token = alibabacloud.utils.parameter_helper.get_uuid() # up to 60 chars 68 | request._params['ClientToken'] = client_token 69 | -------------------------------------------------------------------------------- /python-function-test/alibabacloud_edas_test.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from alibabacloud.clients.edas_20170801 import EdasClient 15 | from alibabacloud.exceptions import ServerException 16 | from base import SDKTestBase 17 | 18 | 19 | class AlibabaCloudEdasTest(SDKTestBase): 20 | 21 | def test_api_request_post(self): 22 | config = self.client_config 23 | config.endpoint = 'edas.cn-hangzhou.aliyuncs.com' 24 | client = EdasClient(config, self.init_credentials_provider()) 25 | try: 26 | response = client.list_application() 27 | self.assertEqual(response.get("Message"), "success") 28 | self.assertIsInstance(response.get("ApplicationList"), dict) 29 | self.assertEqual(response.get("Code"), 200) 30 | except ServerException as e: 31 | self.assertEqual(e.http_status, 503) 32 | self.assertEqual(e.error_code, "ServiceUnavailable") 33 | self.assertEqual(e.error_message, 34 | "The request has failed due to a temporary failure of the server.") 35 | 36 | def test_api_request_get(self): 37 | config = self.client_config 38 | config.endpoint = 'edas.cn-hangzhou.aliyuncs.com' 39 | client = EdasClient(config, self.init_credentials_provider()) 40 | try: 41 | response = client.list_slb() 42 | self.assertEqual(response.get("Message"), "success") 43 | self.assertEqual(response.get("Code"), 200) 44 | self.assertIsInstance(response.get("SlbList"), dict) 45 | except ServerException as e: 46 | self.assertEqual(e.http_status, 503) 47 | self.assertEqual(e.error_code, "ServiceUnavailable") 48 | self.assertEqual(e.error_message, 49 | "The request has failed due to a temporary failure of the server.") 50 | 51 | def test_api_request_put(self): 52 | config = self.client_config 53 | config.endpoint = 'edas.cn-hangzhou.aliyuncs.com' 54 | client = EdasClient(config, self.init_credentials_provider()) 55 | 56 | response = client.disable_degrade_control(app_id='123', rule_id='456') 57 | self.assertEqual(response.get("Message"), "No permissions") 58 | self.assertTrue(response.get("Code") == 401 or response.get("Code") == 500) 59 | 60 | def test_api_request_delete(self): 61 | config = self.client_config 62 | config.endpoint = 'edas.cn-hangzhou.aliyuncs.com' 63 | client = EdasClient(config, self.init_credentials_provider()) 64 | 65 | response = client.delete_cluster(cluster_id='123') 66 | self.assertTrue(response.get("Code") == 401 or response.get("Code") == "601") 67 | self.assertTrue(response.get("Message") == "Edas.errorcode.User.Invalid.message" 68 | or response.get("Message") == "Cluster(123) does not exist") 69 | -------------------------------------------------------------------------------- /python-function-test/alibabacloud_verify_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import shutil 3 | import tempfile 4 | 5 | from alibabacloud import get_client, ClientConfig 6 | from base import SDKTestBase 7 | 8 | 9 | class VerifyTest(SDKTestBase): 10 | 11 | def test_response_set_path(self): 12 | client_config = self.client_config 13 | self.assertEqual(client_config.verify, True) 14 | 15 | def write_config(self, credential): 16 | with open(self.credentials_file, 'w') as f: 17 | f.write(credential) 18 | 19 | def test_file_ca(self): 20 | self.tempdir = tempfile.mkdtemp() 21 | self.credentials_file = os.path.join(self.tempdir, 'config') 22 | os.environ['ALIBABA_CLOUD_CONFIG_FILE'] = self.credentials_file 23 | 24 | config_file = ( 25 | '[default]\n' 26 | 'region_id = us-west-1\n' 27 | 'endpoint = somewhere.you.will.never.get\n' 28 | 'verify = /path/cacerts.pem\n' 29 | ) 30 | self.write_config(config_file) 31 | client = get_client('ecs', access_key_id=self.access_key_id, 32 | access_key_secret=self.access_key_secret, 33 | region_id='hangzhou', endpoint='123') 34 | self.assertEqual(client.config.verify, "/path/cacerts.pem") 35 | 36 | shutil.rmtree(self.tempdir) 37 | os.environ.pop('ALIBABA_CLOUD_CONFIG_FILE') 38 | 39 | def test_file_env_ca(self): 40 | self.tempdir = tempfile.mkdtemp() 41 | self.credentials_file = os.path.join(self.tempdir, 'config') 42 | os.environ['ALIBABA_CLOUD_CONFIG_FILE'] = self.credentials_file 43 | os.environ['ALIBABA_CLOUD_CA_BUNDLE'] = "/path/cacerts.pem" 44 | 45 | config_file = ( 46 | '[default]\n' 47 | 'region_id = us-west-1\n' 48 | 'endpoint = somewhere.you.will.never.get\n' 49 | 'verify = 11111111111\n' 50 | ) 51 | self.write_config(config_file) 52 | client = get_client('ecs', access_key_id=self.access_key_id, 53 | access_key_secret=self.access_key_secret, 54 | region_id='hangzhou', endpoint='123') 55 | self.assertEqual(client.config.verify, "/path/cacerts.pem") 56 | 57 | shutil.rmtree(self.tempdir) 58 | os.environ.pop('ALIBABA_CLOUD_CONFIG_FILE') 59 | os.environ.pop('ALIBABA_CLOUD_CA_BUNDLE') 60 | 61 | def test_client_file_env_ca(self): 62 | self.tempdir = tempfile.mkdtemp() 63 | self.credentials_file = os.path.join(self.tempdir, 'config') 64 | os.environ['ALIBABA_CLOUD_CONFIG_FILE'] = self.credentials_file 65 | os.environ['ALIBABA_CLOUD_CA_BUNDLE'] = "/path/cacerts.pem" 66 | 67 | config_file = ( 68 | '[default]\n' 69 | 'region_id = us-west-1\n' 70 | 'endpoint = somewhere.you.will.never.get\n' 71 | 'verify = 11111111111\n' 72 | ) 73 | self.write_config(config_file, ) 74 | config = ClientConfig(region_id='hangzhou', endpoint='123', verify="client/config.pem") 75 | client = get_client('ecs', access_key_id=self.access_key_id, 76 | access_key_secret=self.access_key_secret, 77 | config=config) 78 | self.assertEqual(client.config.verify, "client/config.pem") 79 | 80 | shutil.rmtree(self.tempdir) 81 | os.environ.pop('ALIBABA_CLOUD_CONFIG_FILE') 82 | os.environ.pop('ALIBABA_CLOUD_CA_BUNDLE') 83 | -------------------------------------------------------------------------------- /alibabacloud/clients/tesladam_20180118.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Alibaba Cloud Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from alibabacloud.client import AlibabaCloudClient 16 | from alibabacloud.request import APIRequest 17 | from alibabacloud.utils.parameter_validation import verify_params 18 | 19 | 20 | class TeslaDamClient(AlibabaCloudClient): 21 | 22 | def __init__(self, client_config, credentials_provider=None, retry_policy=None, 23 | endpoint_resolver=None): 24 | AlibabaCloudClient.__init__(self, client_config, 25 | credentials_provider=credentials_provider, 26 | retry_policy=retry_policy, 27 | endpoint_resolver=endpoint_resolver) 28 | self.product_code = 'TeslaDam' 29 | self.api_version = '2018-01-18' 30 | self.location_service_code = 'tesladam' 31 | self.location_endpoint_type = 'openAPI' 32 | 33 | def action(self, order_id=None, step_code=None): 34 | api_request = APIRequest('Action', 'GET', 'http', 'RPC', 'query') 35 | api_request._params = {"OrderId": order_id, "StepCode": step_code} 36 | return self._handle_request(api_request).result 37 | 38 | def action_disk_rma( 39 | self, 40 | disk_name=None, 41 | execution_id=None, 42 | disk_slot=None, 43 | hostname=None, 44 | disk_mount=None, 45 | disk_reason=None, 46 | disk_sn=None): 47 | api_request = APIRequest('ActionDiskRma', 'GET', 'http', 'RPC', 'query') 48 | api_request._params = { 49 | "DiskName": disk_name, 50 | "ExecutionId": execution_id, 51 | "DiskSlot": disk_slot, 52 | "Hostname": hostname, 53 | "DiskMount": disk_mount, 54 | "DiskReason": disk_reason, 55 | "DiskSn": disk_sn} 56 | return self._handle_request(api_request).result 57 | 58 | def host_gets(self, query=None, end_time=None, start_time=None, query_type=None): 59 | api_request = APIRequest('HostGets', 'GET', 'http', 'RPC', 'query') 60 | api_request._params = { 61 | "Query": query, 62 | "EndTime": end_time, 63 | "StartTime": start_time, 64 | "QueryType": query_type} 65 | return self._handle_request(api_request).result 66 | 67 | def action_disk_mask(self, op=None, disk_mount=None, ip=None): 68 | api_request = APIRequest('ActionDiskMask', 'GET', 'http', 'RPC', 'query') 69 | api_request._params = {"Op": op, "DiskMount": disk_mount, "Ip": ip} 70 | return self._handle_request(api_request).result 71 | 72 | def action_disk_check(self, disk_mount=None, ip=None): 73 | api_request = APIRequest('ActionDiskCheck', 'GET', 'http', 'RPC', 'query') 74 | api_request._params = {"DiskMount": disk_mount, "Ip": ip} 75 | return self._handle_request(api_request).result 76 | -------------------------------------------------------------------------------- /docs/source/higher/04_client.rst: -------------------------------------------------------------------------------- 1 | .. _handle-client: 2 | 3 | 管理客户端配置 4 | =============== 5 | 6 | ``Alibaba Cloud Python SDK`` 提供多种方式管理您发送请求时候的 ``Config`` 7 | ,一般,我们遵循这样的方法:\ **尝试各种位置,直到找到值**\ 。 8 | ``Alibaba Cloud Python SDK`` 使用以下方式查找您的配置: 9 | 10 | - 创建客户端时显式传递为参数 11 | 12 | - 环境变量 13 | 14 | - 文件 15 | 16 | - 默认配置 17 | 18 | 19 | 创建客户端时显式传递参数 20 | ------------------------------- 21 | 22 | 23 | 方式一:get_client接口显式传递 24 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 25 | 26 | ``get_client`` 接口递仅仅支持 ``region_id`` 以及 ``endpoint`` 27 | 显式传递。此处指定的 ``region_id`` 和 ``endpoint`` 28 | 优先级高于任何其他的链式 ``Config`` 指定。 29 | 30 | **endpoint:** 31 | Endpoint是阿里云服务的API服务端地址。针对不同的地域,单个服务可能有不同的Endpoint。例如,云服务器(ECS)在华东1(杭州)地域的Endpoint是 32 | ecs-cn-hangzhou.aliyuncs.com, 33 | 而在日本(东京)地域的Endpoint是ecs.ap-northeast-1.aliyuncs.com。 34 | 如果您不显式指定endpoint,阿里云SDK内置了 35 | Endpoint寻址模块,当您调用SDK对一个服务发起请求时,SDK会自动根据您在创建SDK 36 | Client时指定的地域ID(Region ID)和产品ID来找到Endpoint。 37 | 38 | .. code:: python 39 | 40 | from alibabacloud import get_client 41 | 42 | ecs_client = get_client('ecs', access_key_id=access_key_id, 43 | access_key_secret=access_key_secret, 44 | region_id='cn-hangzhou', endpoint='ecs-cn-hangzhou.aliyuncs.com') 45 | response = ecs_client.describe_tags(page_size=100) 46 | ret = response.get('Tags') 47 | print(ret) 48 | 49 | 50 | 方式二:get_client接口通过config传递 51 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 52 | 53 | ``get_client`` 接口 支持用户显式传递 ``ClientConfig`` 对象。 54 | 55 | .. code:: python 56 | 57 | from alibabacloud import get_client, ClientConfig 58 | 59 | client_config = ClientConfig(region_id='cn-hangzhou', endpoint='ecs-cn-hangzhou.aliyuncs.com') 60 | 61 | ecs_client = get_client('ecs', access_key_id=access_key_id, 62 | access_key_secret=access_key_secret, 63 | config=client_config) 64 | response = ecs_client.describe_tags(page_size=100) 65 | ret = response.get('Tags') 66 | print(ret) 67 | 68 | 69 | 环境变量配置 70 | ------------------------------- 71 | 72 | ``Alibaba Cloud Python SDK`` 支持从环境变量读取部分 ``config`` 相关配置 73 | 74 | **HTTPS_PROXY**:HTTPS代理 75 | 76 | **HTTP_PROXY**:HTTP代理 77 | 78 | 79 | 文件 80 | ------------------------------- 81 | 82 | 在查找配置值时,\ ``Alibaba Cloud Python SDK``\ 还将搜索\ ``~/.alibabacloud/config``\ 文件。您可以设置环境变量\ ``ALIBABA_CLOUD_CONFIG_FILE``\ 值来更改此文件的位置。 83 | 此文件是INI格式文件,我们支持多个section配置,但是目前,我们默认只读取default 84 | 85 | 以下是\ ``~/.alibabacloud/config``\ 支持的所有的配置变量: 86 | 87 | - region_id:要使用的默认地域,参考 `地域与可用区 `__ 88 | 89 | - endpoint:默认的endpoint,即服务请求地址 90 | 91 | - max_retry_times:单个请求的最大重试次数 92 | 93 | - http_port:HTTP代理服务器 94 | 95 | - https_port:HTTPS代理服务器 96 | 97 | - connection_timeout:尝试建立连接时,抛出超时异常的时间,单位为秒。默认5秒 98 | 99 | - read_timeout:尝试从连接读取时抛出超时异常的时间,单位为秒。默认10秒 100 | 101 | - http_proxy:http代理 102 | 103 | - https_proxy:HTTPS代理 104 | 105 | - user_agent:用户自定义的user_gent 106 | 107 | **注意:** 108 | 目前文件暂不支持开关类接口配置。开关类接口在文件中一经配置,默认为开启 109 | 110 | - enable_retry:是否使用使用重试 111 | 112 | - enable_https:使用HTTPS 113 | 114 | 115 | 默认配置 116 | ------------------------------- 117 | 118 | ``Alibaba Cloud Python SDK`` 119 | 提供一些默认的配置,保障API请求或者服务的通路。您可以通过上边的方式进行修改。 120 | 121 | **max_retry_times**:最大重试次数,默认3次 122 | 123 | **enable_retry**:是否重试,默认True 124 | 125 | **enable_https**:是否使用ssl,默认True 126 | 127 | **http_port**:HTTP请求 端口,默认80 128 | 129 | **https_port**:HTTPS请求端口,默认443 130 | -------------------------------------------------------------------------------- /alibabacloud/vendored/requests/structures.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.structures 5 | ~~~~~~~~~~~~~~~~~~~ 6 | 7 | Data structures that power Requests. 8 | """ 9 | 10 | from .compat import OrderedDict, Mapping, MutableMapping 11 | 12 | from .compat import OrderedDict 13 | 14 | 15 | class CaseInsensitiveDict(MutableMapping): 16 | """A case-insensitive ``dict``-like object. 17 | 18 | Implements all methods and operations of 19 | ``MutableMapping`` as well as dict's ``copy``. Also 20 | provides ``lower_items``. 21 | 22 | All keys are expected to be strings. The structure remembers the 23 | case of the last key to be set, and ``iter(instance)``, 24 | ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` 25 | will contain case-sensitive keys. However, querying and contains 26 | testing is case insensitive:: 27 | 28 | cid = CaseInsensitiveDict() 29 | cid['Accept'] = 'application/json' 30 | cid['aCCEPT'] == 'application/json' # True 31 | list(cid) == ['Accept'] # True 32 | 33 | For example, ``headers['content-encoding']`` will return the 34 | value of a ``'Content-Encoding'`` response header, regardless 35 | of how the header name was originally stored. 36 | 37 | If the constructor, ``.update``, or equality comparison 38 | operations are given keys that have equal ``.lower()``s, the 39 | behavior is undefined. 40 | """ 41 | 42 | def __init__(self, data=None, **kwargs): 43 | self._store = OrderedDict() 44 | if data is None: 45 | data = {} 46 | self.update(data, **kwargs) 47 | 48 | def __setitem__(self, key, value): 49 | # Use the lowercased key for lookups, but store the actual 50 | # key alongside the value. 51 | self._store[key.lower()] = (key, value) 52 | 53 | def __getitem__(self, key): 54 | return self._store[key.lower()][1] 55 | 56 | def __delitem__(self, key): 57 | del self._store[key.lower()] 58 | 59 | def __iter__(self): 60 | return (casedkey for casedkey, mappedvalue in self._store.values()) 61 | 62 | def __len__(self): 63 | return len(self._store) 64 | 65 | def lower_items(self): 66 | """Like iteritems(), but with all lowercase keys.""" 67 | return ( 68 | (lowerkey, keyval[1]) 69 | for (lowerkey, keyval) 70 | in self._store.items() 71 | ) 72 | 73 | def __eq__(self, other): 74 | if isinstance(other, Mapping): 75 | other = CaseInsensitiveDict(other) 76 | else: 77 | return NotImplemented 78 | # Compare insensitively 79 | return dict(self.lower_items()) == dict(other.lower_items()) 80 | 81 | # Copy is required 82 | def copy(self): 83 | return CaseInsensitiveDict(self._store.values()) 84 | 85 | def __repr__(self): 86 | return str(dict(self.items())) 87 | 88 | 89 | class LookupDict(dict): 90 | """Dictionary lookup object.""" 91 | 92 | def __init__(self, name=None): 93 | self.name = name 94 | super(LookupDict, self).__init__() 95 | 96 | def __repr__(self): 97 | return '' % (self.name) 98 | 99 | def __getitem__(self, key): 100 | # We allow fall-through here, so values default to None 101 | 102 | return self.__dict__.get(key, None) 103 | 104 | def get(self, key, default=None): 105 | return self.__dict__.get(key, default) 106 | --------------------------------------------------------------------------------