全部产品

Python示例

阿里云EAIS Python SDK让您不需要复杂编程即可访问阿里云弹性加速计算实例EAIS服务。本文为您介绍如何获取阿里云EAIS Python SDK并开始调用。

前提条件

调用API前,您需要先创建AccessKey。具体操作,请参见创建AccessKey

注意

 由于阿里云账号AccessKey泄露会威胁您所有资源的安全,因此禁止使用阿里云账号AccessKey。为了有效降低AccessKey泄露的风险,请您使用RAM用户进行操作。

安装EAIS Python SDK

本文中使用的Python版本为3.6。

  1. 安装SDK核心库。

    推荐使用pip命令

    pip install aliyun-python-sdk-core
  2. 安装EAIS Python SDK。

     pip install aliyun-python-sdk-eais

完整代码

以下示例通过使用SDK调用EAIS的OpenAPI,实现了一个EAIS实例从创建、绑定、解绑到释放的完整生命周期。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import time
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException

# 您的Accesskey ID
TEST_AK_ID = '<your Accesskey ID>'      
# 您的AccessKey Secret
TEST_AK_SECRET = '<your AccessKey Secret>'

class EaisClient(object):
    def __init__(self, access_key_id, access_key_secret, region_id):
        self.client = AcsClient(ak=access_key_id,
                                secret=access_key_secret,
                                region_id=region_id)
        self.region_id = region_id
    
    #用于创建EAIS实例
    def create_eai(self, eais_type, eais_name=None, client_token=None):
        from aliyunsdkeais.request.v20190624.CreateEaiRequest import CreateEaiRequest
        request = CreateEaiRequest()
        request.set_accept_format('json')
        request.set_InstanceType(eais_type)
        if eais_name:
            request.set_InstanceName(eais_name)
        if client_token:
            request.set_ClientToken(client_token)
        response = self.client.do_action_with_exception(request)
        resp_json = json.loads(response)
        return resp_json

    #用于EAIS实例绑定客户端ECS实例
    def attach_eai(self, eais_id, client_id):        
        from aliyunsdkeais.request.v20190624.AttachEaiRequest import AttachEaiRequest
        request = AttachEaiRequest()
        request.set_accept_format('json')
        request.set_ElasticAcceleratedInstanceId(eais_id)
        request.set_ClientInstanceId(client_id)
        response = self.client.do_action_with_exception(request)
        resp_json = json.loads(response)
        return resp_json

    #用于EAIS实例解绑客户端ECS实例
    def detach_eai(self, eais_id):        
        from aliyunsdkeais.request.v20190624.DetachEaiRequest import DetachEaiRequest
        request = DetachEaiRequest()
        request.set_accept_format('json')
        request.set_ElasticAcceleratedInstanceId(eais_id)
        response = self.client.do_action_with_exception(request)
        resp_json = json.loads(response)
        return resp_json

    #用于释放EAIS实例
    def delete_eai(self, eais_id, force=False):        
        from aliyunsdkeais.request.v20190624.DeleteEaiRequest import DeleteEaiRequest
        request = DeleteEaiRequest()
        request.set_accept_format('json')
        request.set_ElasticAcceleratedInstanceId(eais_id)
        request.set_Force(force)
        response = self.client.do_action_with_exception(request)
        resp_json = json.loads(response)
        return resp_json

    #用于查询EAIS实例信息
    def describe_eais(self, 
            eais_ids=None, 
            eais_name=None, 
            eais_status=None, 
            eais_type=None):
        from aliyunsdkeais.request.v20190624.DescribeEaisRequest import DescribeEaisRequest
        request = DescribeEaisRequest()
        request.set_accept_format('json')
        if eais_ids:
            request.set_ElasticAcceleratedInstanceIds(eais_ids)
        if eais_name:
            request.set_InstanceName(eais_name)
        if eais_status:
            request.set_Status(eais_status)
        if eais_type:
            request.set_InstanceType(eais_type)
        response = self.client.do_action_with_exception(request)
        resp_json = json.loads(response)
        return resp_json

    #每隔10秒检查一次实例的状态,直到实例变为就绪状态
    def wait_eais_status_ready(self, eais_id, ready_status):
        print('等待实例状态就绪......')
        for i in range(100):
            time.sleep(10)
            ret = self.describe_eais(eais_ids=json.dumps([eais_id]))
            cur_status = ret['Instances']['Instance'][0]['Status']
            print(f'检查状态是否已就绪: "{cur_status}"=="{ready_status}"?')
            if cur_status == ready_status:
                print('实例状态已就绪。')
                return

def main():
    print('SDK测试......')
    eais = EaisClient(TEST_AK_ID, TEST_AK_SECRET, 'cn-beijing')
    # 创建eais实例
    print('\n创建eais实例......')
    ret1 = eais.create_eai('eais.ei-a6.2xlarge', eais_name='test-sdk')
    print('创建结果:', ret1)
    eais_id = ret1['ElasticAcceleratedInstanceId']

    eais.wait_eais_status_ready(eais_id, 'Available') # 等待实例进入可用状态
    print('\n10秒后绑定eais实例......')
    time.sleep(10)

    # 绑定eais实例
    client_id = input('请输入要绑定的客户端ECS实例ID: ')
    ret2 = eais.attach_eai(eais_id, client_id)
    print('绑定结果:', ret2)

    eais.wait_eais_status_ready(eais_id, 'InUse') # 等待实例进入绑定状态
    print('\n10秒后查询eais实例信息......')
    time.sleep(10)

    # 查询eais实例信息
    ret3 = eais.describe_eais()
    print('查询结果:', ret3)

    print('\n10秒后解绑eais实例......')
    time.sleep(10)

    # 解绑eais实例
    ret4 = eais.detach_eai(eais_id)
    print('解绑结果:', ret4)

    eais.wait_eais_status_ready(eais_id, 'Available') # 等待实例进入可用状态
    print('\n10秒后释放eais实例......')
    time.sleep(10)

    # 释放eais实例
    ret5 = eais.delete_eai(eais_id)
    print('释放结果:', ret5)


if __name__ == '__main__':
    main()