def create_lb_jtq(self): module = 'lb' ''' action: 对应接口的接口名,请参考产品 API 文档上对应接口的接口名 ''' action = 'CreateForwardLBSeventhLayerListeners' ''' config: 云API的公共参数 ''' config = { 'Region': 'ap-beijing', 'secretId': 'AKIDTp13vccxugHgv0QjOsBJG2d2HMH0Lv79', 'secretKey': '2vfFetxqZ7UghWBfy51nZROK5f5KOIBt', } action_params = { 'Version': '2017-03-12', 'loadBalancerId': self.lb_id, #监听哪个服务的端口 这里监听80端口 'listeners.0.loadBalancerPort': '80', 'listeners.0.protocol': '1', 'listeners.0.listenerName': 'liyanliang' } # 接口参数 try: service = QcloudApi(module, config) print(service.generateUrl(action, action_params)) res = service.call(action, action_params) print(eval(res)) print('监听器创建成功') except Exception as e: print(e) import traceback print('traceback.format_exc():\n%s' % traceback.format_exc())
def cdb_qps(self): self.db.get_conn() res = self.db.query(SqlInit.cqb_sid, None) for item in res: projectname = item[0] master_sid = item[1] sidip = item[2] monitor_module = 'monitor' monitor_action = 'GetMonitorData' # metricName = ['qps','tps'] metricName = ['qps'] for metric in metricName: monitor_params = { 'namespace': 'qce/cdb', 'dimensions.0.name': 'uInstanceId', 'dimensions.0.value': master_sid, 'metricName': metric, 'startTime': self.startTime, 'endTime': self.endTime # 'period': 60/300 } nomitor_service = QcloudApi(monitor_module, self.config) monitor_total = nomitor_service.call(monitor_action, monitor_params) monitor_db_info = json.loads(monitor_total)["dataPoints"] res = (projectname, master_sid, sidip, round(max(monitor_db_info))) self.cdb_info.append(res) return self.cdb_info
def execute(self): service = QcloudApi(self.module, self.config) reslut = service.call(self.Action, self.action_param) db_info = json.loads(reslut) print reslut return db_info
def CreateSnapshot(user_region, user_secretId, user_secretKey, user_disk_id, snapshotName): module = 'snapshot' action = 'CreateSnapshot' config = { 'Region': user_region, 'secretId': user_secretId, 'secretKey': user_secretKey, 'method': 'GET', 'SignatureMethod': 'HmacSHA1' } action_params = { 'storageId': user_disk_id, 'snapshotName': snapshotName, } try: service = QcloudApi(module, config) # 生成请求的URL,不发起请求 #print(service.generateUrl(action, action_params)) # 调用接口,发起请求 service.call(action, action_params) except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc())
def get_Cdb_Volume(self): module = 'monitor' action = 'GetMonitorData' metric = ['real_capacity', 'volume_rate'] params = { 'namespace': 'qce/cdb', 'metricName': 'real_capacity', 'dimensions.0.name': 'uInstanceId', 'period': 60 } params['startTime'], params['endTime'] = generate_time() service = QcloudApi(module, self.config) self.get_Cdb_InstanceId() for m in metric: params['metricName'] = m for num, item in enumerate(self.db_items): params['dimensions.0.value'] = item['InstanceId'] service.call(action, params) result = json.loads(service.call(action, params)) if len(result['dataPoints']) != 0: if m == 'real_capacity' and result['dataPoints'][ 0] is not None: self.db_items[num][m] = round( float(result['dataPoints'][0]) / 1024, 2) else: self.db_items[num][m] = result['dataPoints'][0] else: self.db_items[num][m] = None for item in self.db_items: print "%-20s%-15s%-10s%-10s%-10s" % ( item['InstanceName'], item['Vip'], item['Volume'], item['real_capacity'], item['volume_rate'])
def get_small_classification(content): ''' 通过网络文本分类api进行查询初步的分类结果 :param contxt: 要查询的文本内容 :return: 查询的结果 dict 所属类型 ''' #提交参数 action_params = { 'content':content, } #请求 try: service = QcloudApi(module, config) # 打印生成的请求URL,不发起请求 #print(service.generateUrl(action, action_params)) # 调用接口,发起请求,并打印返回结果 rst=json.loads(str(service.call(action, action_params),'utf8')) #print(rst) #请求成功 if rst['code'] == 0: #找到最匹配分类 classification=rst['classes'][0] classification_code=classification['class_num'] print(classification) return classification_code else: return None except : return None
def cz_cvm_password(self): in_id = select_insid() module = 'cvm' ''' action: 对应接口的接口名,请参考产品 API 文档上对应接口的接口名 ''' #重置密码 action = 'ResetInstancesPassword' ''' config: 云API的公共参数 ''' config = { 'Region': 'ap-beijing', 'secretId': 'AKIDTp13vccxugHgv0QjOsBJG2d2HMH0Lv79', 'secretKey': '2vfFetxqZ7UghWBfy51nZROK5f5KOIBt', } # 接口参数 action_params = { # API 版本号 'Version': '2017-03-12', 'InstanceIds.0': in_id, 'Password': '******', 'ForceStop': True } try: service = QcloudApi(module, config) print(service.generateUrl(action, action_params)) res = service.call(action, action_params) print(eval(res)) cz_mima.mima.append(action_params['Password']) except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc())
def post(self, request): if u'content' and u'type' in request.data: r_content = request.data[u'content'] r_type = request.data[u'type'] if r_content != "" and r_type != "" : params = {u'content': r_content, u'type': r_type} try: service = QcloudApi(module, config) # print service.generateUrl(action, params) result_data = json.loads(service.call(action, params)) # print '--------------result_data:', result_data except Exception, e: print '----------exception:', e return Response({u'code': 400, u'message': 'null'}, status=status.HTTP_400_BAD_REQUEST) # return my404(request) result_data[u'content'] = r_content result_data[u'type'] = r_type # fixed message with None text if result_data[u'message'] == "": result_data[u'message'] = None # get ip ip = request.META.get('REMOTE_ADDR', None) result_data[u'ip'] = ip # handle codedesc codedesc = result_data.get(u'codeDesc', None) del(result_data[u'codeDesc']) result_data[u'codedesc'] = codedesc # output serializer = SensModSerializer(data=result_data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def _create_instance(self, token): module = 'cvm' action = 'RunInstances' params = { 'Version': '2017-03-12', 'InstanceChargeType': 'POSTPAID_BY_HOUR', 'Placement': { 'Zone': 'ap-hongkong-1', # 香港一区 }, 'InstanceType': 'S1.SMALL1', 'ImageId': 'img-pyqx34y1', # Ubuntu Server 16.04.1 LTS 64 'InternetAccessible': { 'InternetChargeType': 'TRAFFIC_POSTPAID_BY_HOUR', 'InternetMaxBandwidthOut': 100 }, 'InstanceName': self.instance_name, 'LoginSettings': { 'Password': self.instance_password, }, 'SecurityGroupIds': [self.sg_id], 'ClientToken': token, } service = QcloudApi(module, self._get_api_config()) response = json.loads(service.call(action, params)) print(response) if 'Error' in response['Response']: raise QCloudException(1, response['Response']['Error']['Message']) if 'InstanceIdSet' in response['Response'] and response['Response'][ 'InstanceIdSet']: print(response) return response['Response']['InstanceIdSet'][0] else: return None
def getContentTranscode(url): ''' parameter: url:The target url return: data ''' module = 'wenzhi' action = 'ContentTranscode' region = "sz" path = Util.getDataPath("keys/keys.txt") with open(path) as f: secretId = f.readline().strip('\n') secretKey = f.readline().strip('\n') config = { 'Region': region, 'secretId': secretId, 'secretKey': secretKey} action_params = { 'url':url } try: service = QcloudApi(module, config) print(service.generateUrl(action, action_params)) result = service.call(action, action_params) print(result) except Exception as e: print('traceback.format_exc():\n%s' % traceback.format_exc()) if(result == None): return data = json.loads(result.decode('utf-8')) if(result != None and data["code"] != 0): return None else: return data
def __init__(self): self.qdata = json.load(open("../Private/wechat.data")) # params = {'Limit':1} # 接口参数 module = 'cvm' action = 'DescribeInstances' action_params = { 'limit':1, } self.config = { 'Region': 'sh', 'secretId': self.qdata["Eric"]["SecretId"], 'secretKey': self.qdata["Eric"]["SecretKey"], 'method': 'GET', #'Version':'2017-03-20', 'SignatureMethod': 'HmacSHA1' } try: service = QcloudApi(module, self.config) # 生成请求的URL,不发起请求 # print(service.generateUrl(action, action_params)) # 调用接口,发起请求 response=json.loads(service.call(action, action_params).decode("utf-8")) if response["code"]: print(response) except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc())
def postRequest(self, module, region, action, action_params): try: service = QcloudApi(module, self.__config) # 重新设置请求的region # bj,广州:gz,上海:sh,香港:hk,北美:ca region_list = ['bj', 'gz', 'sh', 'hk', 'ca'] if region in region_list: service.setRegion(region) # 重新设置请求的method # method = 'GET' # service.setRequestMethod(method) # 生成请求的URL,不发起请求 # print(service.generateUrl(action, action_params)) # 调用接口,发起请求 ret = service.call(action, action_params) null = None false = False print(ret) return json.loads(ret) except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc())
def syncQcloud(): try: module = 'cvm' action = 'DescribeInstances' config = { 'Region': qcloud_region, 'secretId': qcloud_secretId, 'secretKey': qcloud_secretKey } params = {'limit': 100} service = QcloudApi(module, config) host_list = eval(service.call(action, params)) for info in host_list['instanceSet']: print info['instanceName'], info['lanIp'], info['os'], info[ 'cpu'], info['mem'], info['wanIpSet'][0] if not Asset.objects.filter(hostname=info['instanceName']): if info['wanIpSet']: wan_ip = info['wanIpSet'][0] else: wan_ip = 'none' Asset.objects.create(hostname=info['instanceName'], ip=info['lanIp'], system_type=info['os'], cpu=str(info['cpu']) + ' cores', memory=str(info['mem']) + 'G', asset_type='CVM', wan_ip=wan_ip) except Exception, e: print e
def transTX(srcStr, srcL, tarL): with open("config.json", "r") as confile: configJson = json.load(confile) module = 'tmt' action = 'TextTranslate' config = { 'Region': 'gz', 'secretId': configJson["secretId"], 'secretKey': configJson["secretKey"] } action_params = {'sourceText': srcStr, 'source': srcL, 'target': tarL} try: service = QcloudApi(module, config) service.generateUrl(action, action_params) # print(service.generateUrl(action, action_params)) str_json = str(service.call(action, action_params), encoding="utf-8") # print(str_json) datarturn = json.loads(str_json) return datarturn['targetText'] except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc())
def get_backup_info(self, host_re): for item in host_re: project_name = item[0] sid = item[1] self.params = {'instanceId': sid} service = QcloudApi(self.module, self.config) total = service.call(self.action, self.params) backup_info = json.loads(total)["data"]["items"][0] backup_name = backup_info["name"] format_backup_name = urllib.unquote(str(backup_name)) backup_status = backup_info["status"] backup_start_time = backup_info["date"] backup_end_time = backup_info["finishTime"] backup_internetUrl = backup_info["internetUrl"] backup_intranetUrl = backup_info["intranetUrl"] backup_mode = backup_info["type"] backup_size = backup_info["size"] backup = (project_name, format_backup_name, backup_status, backup_start_time, backup_end_time, backup_internetUrl, backup_intranetUrl, backup_mode, backup_size) self.all_backup.append(backup) return self.all_backup
def DeleteSnapshot(user_region, user_secretId, user_secretKey, snapshotId): status = None module = 'snapshot' action = 'DeleteSnapshot' config = { 'Region': user_region, 'secretId': user_secretId, 'secretKey': user_secretKey, 'method': 'GET', 'SignatureMethod': 'HmacSHA1' } action_params = { 'snapshotIds.n': snapshotId, } try: service = QcloudApi(module, config) # 生成请求的URL,不发起请求 #print(service.generateUrl(action, action_params)) # 调用接口,发起请求 status = service.call(action, action_params) except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc()) return (status)
def get_record_id(domain, sub_domain, record_type): module = 'cns' action = 'RecordList' config = { 'Region': 'ap-beijing', 'secretId': SECRET_ID, 'secretKey': SECRET_KEY, 'method': 'GET', 'SignatureMethod': 'HmacSHA256' } action_params = { 'domain': domain, 'subDomain': sub_domain, 'recordType': record_type, } result = None try: service = QcloudApi(module, config) logging.debug("Get Query URL: %s" % service.generateUrl(action, action_params)) result = service.call(action, action_params) result = str(result, encoding='utf-8') result = json.loads(result) except Exception: import traceback logging.error(traceback.format_exc()) if result is None or len(result['data']['records']) != 1: return None, None return result['data']['records'][0]['id'], result['data']['records'][0][ 'value']
def _init_security_group_policy(self, sg_id): module = 'dfw' action = 'ModifySecurityGroupPolicys' params = { 'sgId': sg_id, 'ingress': [{ 'ipProtocol': 'tcp', 'cidrIp': '0.0.0.0/0', 'portRange': 8387, 'desc': 'allow ssserver port', 'action': 'ACCEPT', }, { 'ipProtocol': 'tcp', 'cidrIp': '0.0.0.0/0', 'portRange': 22, 'desc': 'ssh port', 'action': 'ACCEPT', }], 'egress': [{ 'action': 'ACCEPT' }] } service = QcloudApi(module, self._get_api_config()) response = json.loads(service.call(action, params)) if response['code'] != 0: raise QCloudException(code=response['code'], message=response['message'])
def select_insid(): ''' module: 设置需要加载的模块 已有的模块列表: cvm 对应 cvm.api.qcloud.com cdb 对应 cdb.api.qcloud.com lb 对应 lb.api.qcloud.com trade 对应 trade.api.qcloud.com sec 对应 csec.api.qcloud.com image 对应 image.api.qcloud.com monitor 对应 monitor.api.qcloud.com cdn 对应 cdn.api.qcloud.com ''' module = 'cvm' ''' action: 对应接口的接口名,请参考产品 API 文档上对应接口的接口名 ''' action = 'DescribeInstances' ''' config: 云API的公共参数 ''' config = { 'Region': 'ap-beijing', 'secretId': 'AKIDTp13vccxugHgv0QjOsBJG2d2HMH0Lv79', 'secretKey': '2vfFetxqZ7UghWBfy51nZROK5f5KOIBt', } # 接口参数 action_params = { #API 版本号 'Version':'2017-03-12', 'Filters':[ { 'Name':'zone', 'Values':['ap-beijing-3'] }, #这里加Filter条件 ], 'Limit':1, } try: service = QcloudApi(module, config) print(service.generateUrl(action, action_params)) res=service.call(action, action_params) import json temp=str(res).strip('b') tmp=json.loads(temp.replace('\'','')) instans_id = tmp['Response']['InstanceSet'][0]['InstanceId'] instans_id=str(instans_id) print('查询负载均衡成功,它的id是%s'%instans_id) return instans_id except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc())
def cvm_total(): module = 'cvm' action = 'DescribeInstances' service = QcloudApi(module, config) resp = service.call(action, {'Version': '2018-07-12', 'Limit': 1}) count = json.loads(resp)['Response']['TotalCount'] return count
def describe_images(self): module = 'image' action = 'DescribeImages' params = { 'Limit': 30, } service = QcloudApi(module, self._get_api_config()) response = json.loads(service.call(action, params)) return response['Response']['ImageSet']
def _create_security_group(self): module = 'dfw' action = 'CreateSecurityGroup' params = {'sgName': self.sg_name} service = QcloudApi(module, self._get_api_config()) data = json.loads(service.call(action, params)) if data['code'] == 0: return data['data']['sgId'] else: raise QCloudException(code=data['code'], message=data['message'])
def requestQcloud(module, action, secretId, secretKey, params): module = module ''' action 对应接口的接口名,请参考产品文档上对应接口的接口名 ''' action = action config = { 'Region': 'ap-beijing', 'secretId': secretId, 'secretKey': secretKey, 'method': 'get' } ''' params 请求参数,请参考产品文档上对应接口的说明 ''' params = { 'Version': "2017-03-12", } # if Offset is not None: # params['Offset'] = Offset # if Limit is not None: # params['Limit'] = Limit try: service = QcloudApi(module, config) # 生成请求的URL,不发起请求 service.generateUrl(action, params) print service.generateUrl(action, params) # 调用接口,发起请求 print params result = service.call(action, params) print service.call(action, params) return result except Exception, e: traceback.print_exc() print 'exception:', e
def __init__(self): super(TencentWenZhi, self).__init__() self.module = "wenzhi" self.config = { 'Region': 'ap-guangzhou', 'secretId': 'AKIDDKGOQWmRErJaga9sFRcdVDj4ED1e2Qdg', 'secretKey': '85xeCev3zmOpEboqhNrAIF4jMo8HIH5i', 'method': 'POST', 'SignatureMethod': 'HmacSHA1' } self.service = QcloudApi(self.module, self.config)
def get_host_metric_list(): module = 'monitor' action = 'DescribeBaseMetrics' params = { 'Version': '2018-07-12', 'namespace': 'qce/cvm' } service = QcloudApi(module, config) resp = service.call(action, params) return json.loads(resp)['metricSet']
def _destroy_instance(self, instance_id): module = 'cvm' action = 'TerminateInstances' params = { 'Version': '2017-03-12', 'InstanceIds': [instance_id], } service = QcloudApi(module, self._get_api_config()) response = json.loads(service.call(action, params)) if 'Error' in response['Response']: raise QCloudException(1, response['Response']['Error']['Message'])
def wzAPI(comment): # 使用腾讯文智自然语言处理,这部分代码本来按照规范应该写到pipelines.py里面的。。结果不知道为啥子一直不执行。。后续要填坑 try: ssl._create_default_https_context = ssl._create_unverified_context # 这一行是为了不让其验证自签名的证书,避免报错 ''' 设置需要加载的模块 ''' module = 'wenzhi' ''' action: 对应接口的接口名 ''' action = 'TextSentiment' ''' config: 云API的公共参数 ''' config = { 'secretId': 'AKIDdaXQSNUiAahrupg8f1EcDg1ODuQqxhux', 'secretKey': '8VmIl4MkWEmlhUByhWg7cMYqDf6WMFTk', 'Region': 'gz', 'method': 'GET' } ''' 接口参数 ''' params = {"content": comment} # 这里需要考虑如何将豆瓣的评论传入到其中,因为豆瓣的评论爬取出来是不规则的 service = QcloudApi(module, config) # print(service.generateUrl(action, params)) # 这段可以不print出来 wzResult = eval(service.call(action, params)) # 调用API,并将字符串结果用eval函数转换为字典 ''' 分别得到正向情感和负向情感的值 ''' positive = wzResult["positive"] negative = wzResult["negative"] # # print(positive) # print(negative) return positive, negative except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc()) return None, None
def setUp(self): cadc_conf = CadcConf("../.tmp/certbot_adc.yaml") p = cadc_conf.name_mappings.get("btpka3") self.api = QcloudApi( "cns", { 'Region': p["region"], 'secretId': p["keyId"], 'secretKey': p["keySecret"], 'method': 'get' }) self.q = CadcProviderQcloud(self.api)
def upload(self, source, target): """Upload a local file to qcloud.tencent.com server""" module = 'cdn' action = 'UploadCdnEntity' params = { 'entityFileName': target, 'entityFile': source } service = QcloudApi(module, self.config) # print(('URL:\n' + service.generateUrl(action, params))) response=json.loads(service.call(action, params).decode("utf-8")) if response["code"]: print(response["code"], response["codeDesc"], response["message"])
def Post(self): module = 'wenzhi' action = 'TextDependency' config = { 'method': 'GET', 'Region': 'ap-shanghai', 'secretId': 'AKID67xY021Y6NXXM2vJv79KLBtLcjhWI3zk', 'secretKey': 'CJPLzYUIF4892MNH1e9ScdWUI1c1IWce', 'SignatureMethod': 'HmacSHA1' } params = {'content': self._content, 'code': 0x00200000, 'type': 4} service = QcloudApi(module, config) url = service.generateUrl(action, params) response = service.call(action, params) self._responses = json.loads(response)['keywords']
action: 对应接口的接口名,请参考wiki文档上对应接口的接口名 ''' action = 'DescribeInstances' ''' config: 云API的公共参数 ''' config = { 'Region': 'ap-guangzhou', 'secretId': '您的secretId', 'secretKey': '您的secretKey', } # 接口参数 action_params = { 'Version': '2017-03-12', 'Filters': [{ 'Name': 'zone', 'Values': ['ap-guangzhou-1', 'ap-guangzhou-2'] }], 'limit': 1, } try: service = QcloudApi(module, config) print(service.generateUrl(action, action_params)) print(service.call(action, action_params)) except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc())