Commit 5dc8cb75 authored by 张允禹's avatar 张允禹

t push -u origin master

parents
recursive-include aliyunsdkcore *.xml
\ No newline at end of file
======================
aliyun-python-sdk-core
======================
This is the core module of Aliyun Python SDK.
Aliyun Python SDK is the official software development kit. It makes things easy to integrate your Python application,
library, or script with Aliyun services.
This module works on Python versions:
* 2.6.5 and greater
Documentation:
Please visit http://develop.aliyun.com/sdk/python
\ No newline at end of file
__author__ = 'alex jiang'
__version__ = '2.3.2'
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
"""
Acs ERROR CODE module.
Created on 6/15/2015
@author: alex jiang
"""
SDK_INVALID_REGION_ID = 'SDK.InvalidRegionId'
SDK_SERVER_UNREACHABLE = 'SDK.ServerUnreachable'
SDK_INVALID_REQUEST = 'SDK.InvalidRequest'
SDK_MISSING_ENDPOINTS_FILER = 'SDK.MissingEndpointsFiler'
SDK_UNKNOWN_SERVER_ERROR = 'SDK.UnknownServerError'
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
"""
Acs error message module.
Created on 6/15/2015
@author: alex jiang
"""
__dict = dict(
SDK_INVALID_REGION_ID='Can not find endpoint to access.',
SDK_SERVER_UNREACHABLE='Unable to connect server',
SDK_INVALID_REQUEST='The request is not a valid AcsRequest.',
SDK_MISSING_ENDPOINTS_FILER='Internal endpoints info is missing.',
SDK_UNKNOWN_SERVER_ERROR="Can not parse error message from server response.")
def get_msg(code):
return __dict.get(code)
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
"""
SDK exception error type module.
Created on 6/15/2015
@author: alex
"""
ERROR_TYPE_CLIENT = 'Client'
ERROR_TYPE_SERVER = 'Server'
ERROR_TYPE_THROTTLING = 'Throttling'
ERROR_TYPE_UNKNOWN = 'Unknown'
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
"""
SDK exception module.
Created on 6/15/2015
@author: alex jiang
"""
import error_type
class ClientException(Exception):
"""client exception"""
def __init__(self, code, msg):
"""
:param code: error code
:param message: error message
:return:
"""
Exception.__init__(self)
self.__error_type = error_type.ERROR_TYPE_CLIENT
self.message = msg
self.error_code = code
def __str__(self):
return "%s %s" % (
self.error_code,
self.message,
)
def set_error_code(self, code):
self.error_code = code
def set_error_msg(self, msg):
self.message = msg
def get_error_type(self):
return self.__error_type
def get_error_code(self):
return self.error_code
def get_error_msg(self):
return self.message
class ServerException(Exception):
"""
server exception
"""
def __init__(self, code, msg, http_status=None, request_id=None):
Exception.__init__(self)
self.error_code = code
self.message = msg
self.__error_type = error_type.ERROR_TYPE_SERVER
self.http_status = http_status
self.request_id = request_id
def __str__(self):
return "HTTP Status: %s Error:%s %s RequestID: %s" % (
str(self.http_status),
self.error_code,
self.message,
self.request_id
)
def set_error_code(self, code):
self.error_code = code
def set_error_msg(self, msg):
self.message = msg
def get_error_type(self):
return self.__error_type
def get_error_code(self):
return self.error_code
def get_error_msg(self):
return self.message
def get_http_status(self):
return self.http_status
def get_request_id(self):
return self.request_id
__author__ = 'alex jiang'
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
"""
MD5 tools module.
Created on 9/28/2015
@author: alex jiang
"""
import hashlib
import base64
def _get_md5(content):
m = hashlib.md5()
m.update(buffer(content))
return m.digest()
def get_md5_base64_str(content):
return base64.encodestring(_get_md5(content)).strip()
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
__author__ = 'alex jiang'
import os
import sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parentdir)
import roa_signature_composer
import sha_hmac1 as mac1
from ..utils import parameter_helper as helper
import urllib
ACCEPT = "Accept"
CONTENT_MD5 = "Content-MD5"
CONTENT_TYPE = "Content-Type"
DATE = "Date"
QUERY_SEPARATOR = "&"
HEADER_SEPARATOR = "\n"
def __init__():
pass
def refresh_sign_parameters(
parameters,
access_key_id,
format="JSON",
signer=mac1):
parameters["Date"] = helper.get_rfc_2616_date()
return parameters
def __build_query_string(uri, queries):
sorted_map = sorted(queries.items(), key=lambda queries: queries[0])
if len(sorted_map) > 0:
uri += "?"
for (k, v) in sorted_map:
uri += k
if v is not None:
uri += "="
uri += v
uri += roa_signature_composer.QUERY_SEPARATOR
if uri.find(roa_signature_composer.QUERY_SEPARATOR) >= 0:
uri = uri[0:(len(uri) - 1)]
return uri
def compose_string_to_sign(
method,
queries,
uri_pattern=None,
headers=None,
paths=None,
signer=mac1):
sign_to_string = ""
sign_to_string += method
sign_to_string += HEADER_SEPARATOR
if CONTENT_MD5 in headers and headers[CONTENT_MD5] is not None:
sign_to_string += headers[CONTENT_MD5]
sign_to_string += HEADER_SEPARATOR
if CONTENT_TYPE in headers and headers[CONTENT_TYPE] is not None:
sign_to_string += headers[CONTENT_TYPE]
sign_to_string += HEADER_SEPARATOR
if DATE in headers and headers[DATE] is not None:
sign_to_string += headers[DATE]
sign_to_string += HEADER_SEPARATOR
sign_to_string += roa_signature_composer.build_canonical_headers(
headers, "x-oss-")
sign_to_string += __build_query_string(uri_pattern, queries)
return sign_to_string
def get_signature(
queries,
access_key,
secret,
format,
headers,
uri_pattern,
paths,
method,
signer=mac1,
bucket_name=None):
headers = refresh_sign_parameters(
parameters=headers,
access_key_id=access_key,
format=format)
uri = uri_pattern
if bucket_name is not None:
uri = "/" + bucket_name + uri
sign_to_string = compose_string_to_sign(
method=method,
queries=queries,
headers=headers,
uri_pattern=uri,
paths=paths)
signature = signer.get_sign_string(sign_to_string, secret=secret)
return signature
def get_signature_headers(
queries,
access_key,
secret,
format,
headers,
uri_pattern,
paths,
method,
bucket_name,
signer=mac1):
signature = get_signature(
queries,
access_key,
secret,
format,
headers,
uri_pattern,
paths,
method,
signer,
bucket_name)
headers["Authorization"] = "OSS " + access_key + ":" + signature
return headers
def get_url(queries, uri_pattern, path_parameters):
url = ""
url += roa_signature_composer.replace_occupied_parameters(
uri_pattern, path_parameters)
if not url.endswith("?"):
url += "?"
url += urllib.urlencode(queries)
if url.endswith("?"):
url = url[0:(len(url) - 1)]
return url
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
__author__ = 'alex jiang'
import os
import sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parentdir)
import sha_hmac1 as mac1
from ..utils import parameter_helper as helper
from ..http import format_type as FormatType
import urllib
ACCEPT = "Accept"
CONTENT_MD5 = "Content-MD5"
CONTENT_TYPE = "Content-Type"
DATE = "Date"
QUERY_SEPARATOR = "&"
HEADER_SEPARATOR = "\n"
def __init__():
pass
# this function will append the necessary parameters for signer process.
# parameters: the orignal parameters
# signer: sha_hmac1 or sha_hmac256
# accessKeyId: this is aliyun_access_key_id
# format: XML or JSON
# input parameters is headers
def refresh_sign_parameters(parameters, access_key_id, format, signer=mac1):
if parameters is None or not isinstance(parameters, dict):
parameters = dict()
if format is None:
format = FormatType.RAW
parameters["Date"] = helper.get_rfc_2616_date()
parameters["Accept"] = FormatType.map_format_to_accept(format)
parameters["x-acs-signature-method"] = signer.get_signer_name()
parameters["x-acs-signature-version"] = signer.get_singer_version()
return parameters
def compose_string_to_sign(
method,
queries,
uri_pattern=None,
headers=None,
paths=None,
signer=mac1):
sign_to_string = ""
sign_to_string += method
sign_to_string += HEADER_SEPARATOR
if ACCEPT in headers and headers[ACCEPT] is not None:
sign_to_string += headers[ACCEPT]
sign_to_string += HEADER_SEPARATOR
if CONTENT_MD5 in headers and headers[CONTENT_MD5] is not None:
sign_to_string += headers[CONTENT_MD5]
sign_to_string += HEADER_SEPARATOR
if CONTENT_TYPE in headers and headers[CONTENT_TYPE] is not None:
sign_to_string += headers[CONTENT_TYPE]
sign_to_string += HEADER_SEPARATOR
if DATE in headers and headers[DATE] is not None:
sign_to_string += headers[DATE]
sign_to_string += HEADER_SEPARATOR
uri = replace_occupied_parameters(uri_pattern, paths)
sign_to_string += build_canonical_headers(headers, "x-acs-")
sign_to_string += __build_query_string(uri, queries)
return sign_to_string
def replace_occupied_parameters(uri_pattern, paths):
result = uri_pattern
if paths is not None:
for (key, value) in paths.items():
target = "[" + key + "]"
result = result.replace(target, value)
return result
# change the give headerBegin to the lower() which in the headers
# and change it to key.lower():value
def build_canonical_headers(headers, header_begin):
result = ""
unsort_map = dict()
for (key, value) in headers.iteritems():
if key.lower().find(header_begin) >= 0:
unsort_map[key.lower()] = value
sort_map = sorted(unsort_map.iteritems(), key=lambda d: d[0])
for (key, value) in sort_map:
result += key + ":" + value
result += HEADER_SEPARATOR
return result
def split_sub_resource(uri):
return uri.split("?")
def __build_query_string(uri, queries):
uri_parts = split_sub_resource(uri)
if len(uri_parts) > 1 and uri_parts[1] is not None:
queries[uri_parts[1]] = None
query_builder = uri_parts[0]
sorted_map = sorted(queries.items(), key=lambda queries: queries[0])
if len(sorted_map) > 0:
query_builder += "?"
for (k, v) in sorted_map:
query_builder += k
if v is not None:
query_builder += "="
query_builder += str(v)
query_builder += QUERY_SEPARATOR
if query_builder.endswith(QUERY_SEPARATOR):
query_builder = query_builder[0:(len(query_builder) - 1)]
return query_builder
def get_signature(
queries,
access_key,
secret,
format,
headers,
uri_pattern,
paths,
method,
signer=mac1):
headers = refresh_sign_parameters(
parameters=headers,
access_key_id=access_key,
format=format)
sign_to_string = compose_string_to_sign(
method=method,
queries=queries,
headers=headers,
uri_pattern=uri_pattern,
paths=paths)
signature = signer.get_sign_string(sign_to_string, secret=secret)
return signature
def get_signature_headers(
queries,
access_key,
secret,
format,
headers,
uri_pattern,
paths,
method,
signer=mac1):
signature = get_signature(
queries,
access_key,
secret,
format,
headers,
uri_pattern,
paths,
method,
signer)
headers["Authorization"] = "acs " + access_key + ":" + signature
return headers
def get_url(uri_pattern, queries, path_parameters):
url = ""
url += replace_occupied_parameters(uri_pattern, path_parameters)
if not url.endswith("?"):
url += "?"
url += urllib.urlencode(queries)
if url.endswith("?"):
url = url[0:(len(url) - 1)]
return url
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
__author__ = 'alex jiang'
import os
import sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parentdir)
import sha_hmac1 as mac1
import urllib
from ..utils import parameter_helper as helper
def __init__():
pass
# this function will append the necessary parameters for signer process.
# parameters: the orignal parameters
# signer: sha_hmac1 or sha_hmac256
# accessKeyId: this is aliyun_access_key_id
# format: XML or JSON
def __refresh_sign_parameters(
parameters,
access_key_id,
accept_format="JSON",
signer=mac1):
if parameters is None or not isinstance(parameters, dict):
parameters = dict()
parameters["Timestamp"] = helper.get_iso_8061_date()
parameters["SignatureMethod"] = signer.get_signer_name()
parameters["SignatureVersion"] = signer.get_singer_version()
parameters["SignatureNonce"] = helper.get_uuid()
parameters["AccessKeyId"] = access_key_id
if accept_format is not None:
parameters["Format"] = accept_format
return parameters
def __pop_standard_urlencode(query):
ret = urllib.urlencode(query)
ret = ret.replace('+', '%20')
ret = ret.replace('*', '%2A')
ret = ret.replace('%7E', '~')
return ret
def __compose_string_to_sign(method, queries):
canonicalized_query_string = ""
sorted_parameters = sorted(queries.items(), key=lambda queries: queries[0])
string_to_sign = method + "&%2F&" + \
urllib.pathname2url(__pop_standard_urlencode(sorted_parameters))
return string_to_sign
def __get_signature(string_to_sign, secret, signer=mac1):
return signer.get_sign_string(string_to_sign, secret + '&')
def get_signed_url(params, ak, secret, accept_format, method, signer=mac1):
sign_params = __refresh_sign_parameters(params, ak, accept_format, signer)
string_to_sign = __compose_string_to_sign(method, sign_params)
signature = __get_signature(string_to_sign, secret, signer)
sign_params['Signature'] = signature
url = '/?' + __pop_standard_urlencode(sign_params)
return url
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
__author__ = 'alex jiang'
import hashlib
import hmac
import base64
def get_sign_string(source, secret):
h = hmac.new(secret, source, hashlib.sha1)
signature = base64.encodestring(h.digest()).strip()
return signature
def get_signer_name():
return "HMAC-SHA1"
def get_singer_version():
return "1.0"
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
__author__ = 'alex jiang'
import hmac
import hashlib
import base64
class ShaHmac256:
def __init__(self):
pass
def get_sign_string(self, source, accessSecret):
h = hmac.new(accessSecret, source, hashlib.sha256)
signature = base64.encodestring(h.digest()).strip()
return signature
def get_signer_name(self):
return "HMAC-SHA256"
def get_singer_version(self):
return "1.0"
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
import urllib
import sys
"""
Acs url encoder module.
Created on 6/16/2015
@author: alex
"""
def get_encode_str(params):
"""
transforms parameters to encoded string
:param params: dict parameters
:return: string
"""
list_params = sorted(params.iteritems(), key=lambda d: d[0])
encode_str = urllib.urlencode(list_params)
if sys.stdin.encoding is None:
res = urllib.quote(encode_str.decode('cp936').encode('utf8'), '')
else:
res = urllib.quote(
encode_str.decode(
sys.stdin.encoding).encode('utf8'), '')
res = res.replace("+", "%20")
res = res.replace("*", "%2A")
res = res.replace("%7E", "~")
return res
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
import os
import sys
import httplib
import warnings
warnings.filterwarnings("once", category=DeprecationWarning)
try:
import json
except ImportError:
import simplejson as json
from .profile import region_provider
from .profile.location_service import LocationService
from .acs_exception.exceptions import ClientException
from .acs_exception.exceptions import ServerException
from .acs_exception import error_code, error_msg
from .http.http_response import HttpResponse
from .request import AcsRequest
"""
Acs default client module.
Created on 6/15/2015
@author: alex jiang
"""
class AcsClient:
def __init__(
self,
ak,
secret,
region_id,
auto_retry=True,
max_retry_time=3,
user_agent=None,
port=80):
"""
constructor for AcsClient
:param ak: String, access key id
:param secret: String, access key secret
:param region_id: String, region id
:param auto_retry: Boolean
:param max_retry_time: Number
:return:
"""
self.__max_retry_num = max_retry_time
self.__auto_retry = auto_retry
self.__ak = ak
self.__secret = secret
self.__region_id = region_id
self.__user_agent = user_agent
self._port = port
self._location_service = LocationService(self)
# if true, do_action() will throw a ClientException that contains URL
self._url_test_flag = False
def get_region_id(self):
"""
:return: String
"""
return self.__region_id
def get_access_key(self):
"""
:return: String
"""
return self.__ak
def get_access_secret(self):
"""
:return: String
"""
return self.__secret
def is_auto_retry(self):
"""
:return:Boolean
"""
return self.__auto_retry
def get_max_retry_num(self):
"""
:return: Number
"""
return self.__max_retry_num
def get_user_agent(self):
return self.__user_agent
def set_region_id(self, region):
self.__region_id = region
def set_access_key(self, ak):
self.__ak = ak
def set_access_secret(self, secret):
self.__secret = secret
def set_max_retry_num(self, num):
"""
set auto retry number
:param num: Numbers
:return: None
"""
self.__max_retry_num = num
def set_auto_retry(self, flag):
"""
set whether or not the client perform auto-retry
:param flag: Booleans
:return: None
"""
self.__auto_retry = flag
def set_user_agent(self, agent):
"""
User agent set to client will overwrite the request setting.
:param agent:
:return:
"""
self.__user_agent = agent
def get_location_service(self):
return self._location_service
def get_port(self):
return self._port
def _resolve_endpoint(self, request):
endpoint = None
if request.get_location_service_code() is not None:
endpoint = self._location_service.find_product_domain(
self.get_region_id(), request.get_location_service_code())
if endpoint is None:
endpoint = region_provider.find_product_domain(
self.get_region_id(), request.get_product())
if endpoint is None:
raise ClientException(
error_code.SDK_INVALID_REGION_ID,
error_msg.get_msg('SDK_INVALID_REGION_ID'))
if not isinstance(request, AcsRequest):
raise ClientException(
error_code.SDK_INVALID_REQUEST,
error_msg.get_msg('SDK_INVALID_REQUEST'))
return endpoint
def _make_http_response(self, endpoint, request):
content = request.get_content()
method = request.get_method()
header = request.get_signed_header(
self.get_region_id(),
self.get_access_key(),
self.get_access_secret())
if self.get_user_agent() is not None:
header['User-Agent'] = self.get_user_agent()
header['x-sdk-client'] = 'python/2.0.0'
if header is None:
header = {}
protocol = request.get_protocol_type()
url = request.get_url(
self.get_region_id(),
self.get_access_key(),
self.get_access_secret())
response = HttpResponse(
endpoint,
url,
method,
header,
protocol,
content,
self._port)
return response
def _implementation_of_do_action(self, request):
endpoint = self._resolve_endpoint(request)
http_response = self._make_http_response(endpoint, request)
if self._url_test_flag:
raise ClientException("URLTestFlagIsSet", http_response.get_url())
# Do the actual network thing
try:
status, headers, body = http_response.get_response_object()
return status, headers, body
except IOError as e:
raise ClientException(
error_code.SDK_SERVER_UNREACHABLE,
error_msg.get_msg('SDK_SERVER_UNREACHABLE') + ': ' + str(e))
except AttributeError:
raise ClientException(
error_code.SDK_INVALID_REQUEST,
error_msg.get_msg('SDK_INVALID_REQUEST'))
def _parse_error_info_from_response_body(self, response_body):
try:
body_obj = json.loads(response_body)
if 'Code' in body_obj and 'Message' in body_obj:
return (body_obj['Code'], body_obj['Message'])
else:
return (
error_code.SDK_UNKNOWN_SERVER_ERROR,
error_msg.get_msg('SDK_UNKNOWN_SERVER_ERROR'))
except ValueError:
# failed to parse body as json format
return (error_code.SDK_UNKNOWN_SERVER_ERROR,
error_msg.get_msg('SDK_UNKNOWN_SERVER_ERROR'))
def do_action_with_exception(self, acs_request):
# set server response format as json, because thie function will
# parse the response so which format doesn't matter
acs_request.set_accept_format('json')
status, headers, body = self._implementation_of_do_action(acs_request)
request_id = None
ret = body
try:
body_obj = json.loads(body)
request_id = body_obj.get('RequestId')
ret = body_obj
except ValueError:
# in case the response body is not a json string, return the raw
# data instead
pass
if status != httplib.OK:
server_error_code, server_error_message = self._parse_error_info_from_response_body(
body)
raise ServerException(
server_error_code,
server_error_message,
http_status=status,
request_id=request_id)
return body
def do_action(self, acs_request):
warnings.warn(
"do_action() method is deprecated, please use do_action_with_exception() instead.",
DeprecationWarning)
status, headers, body = self._implementation_of_do_action(acs_request)
return body
def get_response(self, acs_request):
warnings.warn(
"get_response() method is deprecated, please use do_action_with_exception() instead.",
DeprecationWarning)
return self._implementation_of_do_action(acs_request)
This source diff could not be displayed because it is too large. You can view the blob instead.
__author__ = 'alex jiang'
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
__author__ = 'alex jiang'
XML = 'XML'
JSON = 'JSON'
RAW = 'RAW'
APPLICATION_XML = 'application/xml'
APPLICATION_JSON = 'application/json'
APPLICATION_OCTET_STREAM = 'application/octet-stream'
TEXT_XML = 'text/xml'
def map_format_to_accept(format):
if format == XML:
return APPLICATION_XML
if format == JSON:
return APPLICATION_JSON
return APPLICATION_OCTET_STREAM
def map_accept_to_format(accept):
if accept.lower() == APPLICATION_XML or accept.lower() == TEXT_XML:
return XML
if accept.lower() == APPLICATION_JSON:
return JSON
return RAW
if __name__ == "__main__":
print map_format_to_accept(XML)
print map_format_to_accept(JSON)
print map_format_to_accept(RAW)
print map_accept_to_format("application/xml")
print map_accept_to_format("text/xml")
print map_accept_to_format("application/json")
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
__author__ = 'alex jiang'
import os
import sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parentdir)
import format_type
from ..utils import parameter_helper as helper
class HttpRequest:
content_md5 = "Content-MD5"
content_length = "Content-Length"
content_type = "Content-Type"
def __init__(self, host="", url="/", method=None, headers={}):
self.__host = host
self.__url = url
self.__method = method
self.__content_type = ""
self.__content = ""
self.__encoding = ""
self.__headers = headers
self.__body = None
def get_host(self):
return self.__host
def set_host(self, host):
self.__host = host
def get_body(self):
return self.__body
def set_body(self, body):
self.__body = body
def get_url(self):
return self.__url
def set_url(self, url):
self.__url = url
def get_encoding(self):
return self.__encoding
def set_encoding(self, encoding):
self.__encoding = encoding
def get_content_type(self):
return self.__content_type
def set_content_type(self, content_type):
self.__content_type = content_type
def get_method(self):
return self.__method
def set_method(self, method):
self.__method = method
def get_content(self):
return self.__content
def get_header_value(self, name):
return self.__headers[name]
def put_header_parameter(self, key, value):
if key is not None and value is not None:
self.__headers[key] = value
def md5_sum(self, content):
return helper.md5_sum(content)
def set_content(self, content, encoding, format):
tmp = dict()
if content is None:
self.__headers.pop(self.content_md5)
self.__headers.pop(self.content_length)
self.__headers.pop(self.content_type)
self.__content_type = None
self.__content = None
self.__encoding = None
return
str_md5 = self.md5_sum(content)
content_length = len(content)
content_type = format_type.RAW
if format is None:
content_type = format
self.__headers[self.content_md5] = str_md5
self.__headers[self.content_length] = content_length
self.__headers[self.content_type] = content_type
self.__content = content
self.__encoding = encoding
def get_headers(self):
return self.__headers
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
__author__ = 'alex jiang'
import httplib
from http_request import HttpRequest
import protocol_type as PT
class HttpResponse(HttpRequest):
def __init__(
self,
host="",
url="/",
method="GET",
headers={},
protocol=PT.HTTP,
content=None,
port=None,
key_file=None,
cert_file=None):
HttpRequest.__init__(
self,
host=host,
url=url,
method=method,
headers=headers)
self.__ssl_enable = False
if protocol is PT.HTTPS:
self.__ssl_enable = True
self.__key_file = key_file
self.__cert_file = cert_file
self.__port = port
self.__connection = None
self.set_body(content)
def set_ssl_enable(self, enable):
self.__ssl_enable = enable
def get_ssl_enabled(self):
return self.__ssl_enable
def get_response(self):
if self.get_ssl_enabled():
return self.get_https_response()
else:
return self.get_http_response()
def get_response_object(self):
if self.get_ssl_enabled():
return self.get_https_response_object()
else:
return self.get_http_response_object()
def get_http_response(self):
if self.__port is None or self.__port == "":
self.__port = 80
try:
self.__connection = httplib.HTTPConnection(
self.get_host(), self.__port)
self.__connection.connect()
self.__connection.request(
method=self.get_method(),
url=self.get_url(),
body=self.get_body(),
headers=self.get_headers())
response = self.__connection.getresponse()
return response.getheaders(), response.read()
finally:
self.__close_connection()
def get_http_response_object(self):
if self.__port is None or self.__port == "":
self.__port = 80
try:
self.__connection = httplib.HTTPConnection(
self.get_host(), self.__port)
self.__connection.connect()
self.__connection.request(
method=self.get_method(),
url=self.get_url(),
body=self.get_body(),
headers=self.get_headers())
response = self.__connection.getresponse()
return response.status, response.getheaders(), response.read()
finally:
self.__close_connection()
def get_https_response(self):
if self.__port is None or self.__port == "":
self.__port = 443
try:
self.__port = 443
self.__connection = httplib.HTTPSConnection(
self.get_host(),
self.__port,
cert_file=self.__cert_file,
key_file=self.__key_file)
self.__connection.connect()
self.__connection.request(
method=self.get_method(),
url=self.get_url(),
body=self.get_body(),
headers=self.get_headers())
response = self.__connection.getresponse()
return response.getheaders(), response.read()
finally:
self.__close_connection()
def get_https_response_object(self):
if self.__port is None or self.__port == "":
self.__port = 443
try:
self.__port = 443
self.__connection = httplib.HTTPSConnection(
self.get_host(),
self.__port,
cert_file=self.__cert_file,
key_file=self.__key_file)
self.__connection.connect()
self.__connection.request(
method=self.get_method(),
url=self.get_url(),
body=self.get_body(),
headers=self.get_headers())
response = self.__connection.getresponse()
return response.status, response.getheaders(), response.read()
finally:
self.__close_connection()
def __close_connection(self):
if self.__connection is not None:
self.__connection.close()
self.__connection = None
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
__author__ = 'alex jiang'
GET = "GET"
PUT = "PUT"
POST = "POST"
DELETE = "DELETE"
HEAD = "HEAD"
OPTIONS = "OPTIONS"
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
__author__ = 'alex jiang'
HTTP = "http"
HTTPS = "https"
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
import os
import sys
import json
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)
from ..request import RpcRequest
from ..http.http_response import HttpResponse
from ..acs_exception import exceptions as exs
from ..acs_exception import error_code, error_msg
LOCATION_SERVICE_PRODUCT_NAME = "Location"
LOCATION_SERVICE_DOMAIN = "location.aliyuncs.com"
LOCATION_SERVICE_VERSION = "2015-06-12"
LOCATION_SERVICE_DESCRIBE_ENDPOINT_ACTION = "DescribeEndpoint"
LOCATION_SERVICE_REGION = "cn-hangzhou"
class DescribeEndpointRequest(RpcRequest):
def __init__(
self,
product_name,
version,
action_name,
region_id,
service_code):
RpcRequest.__init__(self, product_name, version, action_name, 'hhh')
self.add_query_param("Id", region_id)
self.add_query_param("ServiceCode", service_code)
self.set_accept_format("JSON")
class LocationService:
def __init__(self, client):
self.__clinetRef = client
self.__cache = {}
self.__service_product_name = LOCATION_SERVICE_PRODUCT_NAME
self.__service_domain = LOCATION_SERVICE_DOMAIN
self.__service_version = LOCATION_SERVICE_VERSION
self.__service_region = LOCATION_SERVICE_REGION
self.__service_action = LOCATION_SERVICE_DESCRIBE_ENDPOINT_ACTION
def set_location_service_attr(
self,
region=None,
product_name=None,
domain=None):
if region is not None:
self.__service_region = region
if product_name is not None:
self.__service_product_name = product_name
if domain is not None:
self.__service_domain = domain
def find_product_domain(self, region_id, service_code):
key = "%s_&_%s" % (region_id, service_code)
domain = self.__cache.get(key)
if domain is None:
domain = self.find_product_domain_from_location_service(
region_id, service_code)
if domain is not None:
self.__cache[key] = domain
return domain
def find_product_domain_from_location_service(
self, region_id, service_code):
request = DescribeEndpointRequest(self.__service_product_name,
self.__service_version,
self.__service_action,
region_id,
service_code)
try:
content = request.get_content()
method = request.get_method()
header = request.get_signed_header(
self.__service_region,
self.__clinetRef.get_access_key(),
self.__clinetRef.get_access_secret())
if self.__clinetRef.get_user_agent() is not None:
header['User-Agent'] = self.__clinetRef.get_user_agent()
header['x-sdk-client'] = 'python/2.0.0'
protocol = request.get_protocol_type()
url = request.get_url(
self.__service_region,
self.__clinetRef.get_access_key(),
self.__clinetRef.get_access_secret())
response = HttpResponse(
self.__service_domain,
url,
method,
{} if header is None else header,
protocol,
content,
self.__clinetRef.get_port())
status, header, body = response.get_response_object()
result = json.loads(body)
if status == 200:
return result.get('Endpoint')
elif status >= 400 and status < 500:
# print "serviceCode=" + service_code + " get location error!
# code=" + result.get('Code') +", message =" +
# result.get('Message')
return None
elif status >= 500:
raise exs.ServerException(
result.get('Code'), result.get('Message'))
else:
raise exs.ClientException(
result.get('Code'), result.get('Message'))
except IOError:
raise exs.ClientException(
error_code.SDK_SERVER_UNREACHABLE,
error_msg.get_msg('SDK_SERVER_UNREACHABLE'))
except AttributeError:
raise exs.ClientException(
error_code.SDK_INVALID_REQUEST,
error_msg.get_msg('SDK_INVALID_REQUEST'))
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
import os
import sys
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)
from acs_exception import error_code, error_msg
from acs_exception.exceptions import ClientException
from xml.dom.minidom import parse
"""
Region&Endpoint provider module.
Created on 6/12/2015
@author: alex
"""
# endpoint list
__endpoints = dict()
# load endpoints info from endpoints.xml file and parse to dict.
__endpoints_file = os.path.join(parent_dir, 'endpoints.xml')
try:
DOMTree = parse(__endpoints_file)
root = DOMTree.documentElement
eps = root.getElementsByTagName('Endpoint')
for endpoint in eps:
region_list = []
product_list = []
regions = endpoint.getElementsByTagName('RegionId')
products = endpoint.getElementsByTagName('Product')
for region in regions:
region_list.append(region.childNodes[0].nodeValue)
for product in products:
name_node = product.getElementsByTagName('ProductName')[0]
name = name_node.childNodes[0].nodeValue
domain_node = product.getElementsByTagName('DomainName')[0]
domain = domain_node.childNodes[0].nodeValue
product_list.append({name: domain})
__endpoints[endpoint.getAttribute('name')] = dict(
regions=region_list, products=product_list)
except Exception as ex:
raise ClientException(
error_code.SDK_MISSING_ENDPOINTS_FILER,
error_msg.get_msg('SDK_MISSING_ENDPOINTS_FILER'))
def find_product_domain(regionid, prod_name):
"""
Fetch endpoint url with given region id, product name and endpoint list
:param regionid: region id
:param product: product name
:param endpoints: product list
:return: endpoint url
"""
if regionid is not None and product is not None:
for point in __endpoints:
point_info = __endpoints.get(point)
if regionid in point_info.get('regions'):
prod_info = point_info.get('products')
for prod in prod_info:
if prod_name in prod:
return prod.get(prod_name)
return None
def modify_point(product_name, region_id, end_point):
for point in __endpoints:
point_info = __endpoints.get(point)
region_list = point_info.get('regions')
products = point_info.get('products')
if region_id is not None and region_id not in region_list:
region_list.append(region_id)
if end_point is not None:
product_exit = 0
for prod in products:
if product_name in prod:
prod[product_name] = end_point
product_exit = 1
if product_exit == 0:
item = dict()
item[product_name] = end_point
products.append(item)
__mdict = dict()
__mdict['regions'] = region_list
__mdict['products'] = products
__endpoints[point] = __mdict
convert_dict_to_endpointsxml(__endpoints)
def convert_dict_to_endpointsxml(mdict):
regions = list()
products = list()
for point in mdict:
point_info = mdict.get(point)
regions = point_info.get('regions')
products = point_info.get('products')
content = ''
prefix = '<?xml version="1.0" encoding="UTF-8"?>\n<Endpoints>\n<Endpoint name="cn-hangzhou">\n'
endfix = '</Endpoint>\n</Endpoints>\n'
content += prefix
content += '<RegionIds>\n'
for item in regions:
content += '<RegionId>' + item + '</RegionId>\n'
content += '</RegionIds>\n' + '<Products>\n'
for item in products:
content += '<Product>\n'
content += '<ProductName>' + item.keys()[0] + '</ProductName>\n'
content += '<DomainName>' + item[item.keys()[0]] + '</DomainName>\n'
content += '</Product>\n'
content += '</Products>'
content += endfix
# print content
if not os.path.isfile(__endpoints_file):
_createFile(__endpoints_file)
f = open(__endpoints_file, 'w')
try:
f.write(''.join(content))
except Exception as e:
print e
print "Please confirm you has use sudo + cmd"
finally:
f.close()
def _createFile(filename):
namePath = os.path.split(filename)[0]
if not os.path.isdir(namePath):
os.makedirs(namePath)
with os.fdopen(os.open(filename,
os.O_WRONLY | os.O_CREAT, 0o600), 'w'):
pass
if __name__ == '__main__':
print find_product_domain('cn-hangzhou', 'Rds')
modify_point('ecs', 'cn-beijing-2', 'ecs.aliyuncs.com')
This diff is collapsed.
__author__ = 'alex jiang'
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
__author__ = 'alex jiang'
import hashlib
import base64
import uuid
import time
import urllib
import sys
TIME_ZONE = "GMT"
FORMAT_ISO_8601 = "%Y-%m-%dT%H:%M:%SZ"
FORMAT_RFC_2616 = "%a, %d %b %Y %X GMT"
def get_uuid():
return str(uuid.uuid4())
def get_iso_8061_date():
return time.strftime(FORMAT_ISO_8601, time.gmtime())
def get_rfc_2616_date():
return time.strftime(FORMAT_RFC_2616, time.gmtime())
def md5_sum(content):
return base64.standard_b64encode(hashlib.md5(content).digest())
def percent_encode(encodeStr):
encodeStr = str(encodeStr)
if sys.stdin.encoding is None:
res = urllib.quote(encodeStr.decode('cp936').encode('utf8'), '')
else:
res = urllib.quote(
encodeStr.decode(
sys.stdin.encoding).encode('utf8'), '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
if __name__ == "__main__":
print get_uuid()
print get_iso_8061_date()
print get_rfc_2616_date()
#!/usr/bin/python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
'''
from setuptools import setup, find_packages
import os
"""
setup module for core.
Created on 6/24/2015
@author: alex
"""
PACKAGE = "aliyunsdkcore"
NAME = "aliyun-python-sdk-core"
DESCRIPTION = "The core module of Aliyun Python SDK."
AUTHOR = "Aliyun"
AUTHOR_EMAIL = "aliyun-developers-efficiency@list.alibaba-inc.com"
URL = "http://develop.aliyun.com/sdk/python"
TOPDIR = os.path.dirname(__file__) or "."
VERSION = __import__(PACKAGE).__version__
desc_file = open("README.rst")
try:
LONG_DESCRIPTION = desc_file.read()
finally:
desc_file.close()
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
license="Apache",
url=URL,
keywords=["aliyun", "sdk", "core"],
packages=find_packages(exclude=["tests*"]),
include_package_data=True,
platforms='any',
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development',
)
)
__author__ = 'alex'
from __future__ import absolute_import
__author__ = 'alex'
# import os
# import sys
# parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.insert(0,parentdir)
# from aliyun-python-sdk-core import client
import pytest
# ak = 'test-ak'
# secret = 'test-secret'
# region = 'test-region'
# agent = 'aliyuncli'
# max_retry_num = 3
# class TestClient:
#
# @pytest.mark.smoke
# def test_client_init(self):
# self#initiate client
# acs_client = client.AcsClient(ak, secret, region)
# assert acs_client
# #set up attributes
# acs_client.set_user_agent(agent)
# acs_client.set_auto_retry(True)
# acs_client.set_max_retry_num(max_retry_num)
# assert acs_client.get_user_agent() == agent
# assert acs_client.get_max_retry_num() == max_retry_num
# assert acs_client.get_access_key() == ak
# assert acs_client.get_access_secret() == secret
# assert acs_client.get_region_id() == region
# assert acs_client.is_auto_retry()
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding=utf-8
import os
import sys
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import RpcRequest
client = AcsClient('your_access_key', 'your_access_secret', 'cn-hangzhou')
location_service = client.get_location_service()
location_service.set_location_service_attr(region='cn-beijing',
product_name="Location",
domain="location.aliyuncs.com")
domain = location_service.find_product_domain(client.get_region_id(), 'oss')
print domain
domain = location_service.find_product_domain(client.get_region_id(), 'oss')
print domain
class DescribeRegionsRequest(RpcRequest):
def __init__(self, OwnerId=None, ResourceOwnerAccount=None,
ResourceOwnerId=None, OwnerAccount=None):
RpcRequest.__init__(
self,
'Ecs',
'2014-05-26',
'DescribeRegions',
'oss')
self.add_query_param('OwnerId', OwnerId)
self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount)
self.add_query_param('ResourceOwnerId', ResourceOwnerId)
self.add_query_param('OwnerAccount', OwnerAccount)
request = DescribeRegionsRequest()
status, headers, body = client.get_response(request)
print status
print body
__author__ = 'alex'
import os
import sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parentdir)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment