#!/usr/bin/python # -*- coding: utf-8 -*- # 引入云API入口模块 from QcloudApi.qcloudapi import QcloudApi module = 'wenzhi' # 对应的接口ActionID action = 'TextSentiment' config = { 'Region': 'gz', 'secretId': 'AKIDnYFmBYZHcowxyqr52lQt7D4vZljHYnmW', 'secretKey': 'g2IKHzXt15ygNuD4ziGaYN5bnlUzMWR9', 'method': 'post', } params = { 'content': '不奇官考何如来,已融汉武争猿吟。奔波暗检家府壮,横得客客梦苍伐。', 'type': 4, } try: service = QcloudApi(module, config) # 生成请求的URL,不发起请求 print(service.generateUrl(action, params)) # 调用接口,发起请求 print(service.call(action, params)) except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc())
class _QcloudDnsClient(): """ Encapsulates base DNS operation with Qcloud DNS SDK: qcloudsdkalidns. """ def __init__(self, secret_key_path=None): try: with open(secret_key_path, 'r') as file: json_content = file.read() self._secretId, self._secretKey = json.loads(json_content)[ "secretId"], json.loads(json_content)["secretKey"] module = 'cns' config = { 'secretId': self._secretId, 'secretKey': self._secretKey, 'method': 'GET', 'SignatureMethod': 'HmacSHA1', } self._client = QcloudApi(module, config) except IOError: LOGGER.error("Qcloud access secret file: %s not found.", secret_key_path) except Exception as error: LOGGER.error("Qcloud SDK client init failed: %s.", error) def add_txt_record(self, domain_name, record_name, record_value): """ : add TXT domain record for authentication; """ record_name = record_name.replace(("." + domain_name), "") action_params = { "domain": domain_name, "subDomain": record_name, "recordType": "TXT", "recordLine": "默认", "value": record_value, "ttl": TTL } action = 'RecordCreate' self._client.generateUrl(action, action_params) response = self._client.call(action, action_params) LOGGER.info("domain_name: %s, record_name: %s, record_value: %s.", \ domain_name, record_name, record_value) result = json.loads(str(response, encoding="utf-8")) LOGGER.info("add result: %s.", result) def delete_txt_record(self, domain_name, record_name, record_value): """ : delete TXT domain record for authentication; """ # describe request for dns record id record_id = None page_num = 1 action_params = { "domain": domain_name, "offset": (page_num - 1) * PAGE_SIZE, "length": PAGE_SIZE, } action = 'RecordList' # delete request for delete corresponsing dns record # del_request = DeleteDomainRecordRequest.DeleteDomainRecordRequest() # del_request.set_accept_format("json") record_name = record_name.replace(("." + domain_name), "") # des_request.set_DomainName(domain_name) self._client.generateUrl(action, action_params) response = self._client.call(action, action_params) record_first_page_result = json.loads(str(response, encoding="utf-8")) # total_record_count = int( record_first_page_result["data"]["info"]["record_total"]) if total_record_count < PAGE_SIZE: result = record_first_page_result["data"]["records"] for record in result: if record["type"] == "TXT" and \ record["name"] == record_name and \ record["value"] == record_value: record_id = record["id"] LOGGER.info("Delete record %s %s-%s, record Id: %s.", \ record_name, domain_name, record["value"], record_id) else: page_num = (total_record_count / PAGE_SIZE) if total_record_count % PAGE_SIZE == 0 \ else (int(total_record_count / PAGE_SIZE) + 1) for page in range(2, page_num + 1): action_params = { "domain": domain_name, "offset": (page - 1) * PAGE_SIZE, "length": PAGE_SIZE, } action = 'RecordList' self._client.generateUrl(action, action_params) response = self._client.call(action, action_params) result = json.loads(str(response, encoding="utf-8")) for record in result: if record["type"] == "TXT" and \ record["name"] == record_name and \ record["value"] == record_value: record_id = record["id"] LOGGER.info("Delete record %s %s-%s, record Id: %s.", \ record_name, domain_name, record["value"], record_id) break LOGGER.info("record id: {}.".format(record_id)) # no record Id no delete operation. if record_id: action_params = { "domain": domain_name, "recordId": record_id, } action = 'RecordDelete' self._client.generateUrl(action, action_params) response = self._client.call(action, action_params) del_result = json.loads(str(response, encoding="utf-8")) LOGGER.info("delete result: %s.", del_result) else: raise Exception("{} {}-{} record cannot be found.".format( record_name, domain_name, record["value"]))
def request_put(self): service = QcloudApi(self.module, self.config) str_results = service.call(self.action, self.params) json_results = json.loads(str_results) return json_results
''' action: 对应接口的接口名,请参考产品 API 文档上对应接口的接口名 ''' #退还实例 action = 'TerminateInstances' ''' config: 云API的公共参数 ''' config = { 'Region': 'ap-beijing', 'secretId': 'AKIDTp13vccxugHgv0QjOsBJG2d2HMH0Lv79', 'secretKey': '2vfFetxqZ7UghWBfy51nZROK5f5KOIBt', } # 接口参数 action_params = { #API 版本号 'Version':'2017-03-12', #退还哪一台主机 'InstanceIds.0':'d69bf457-08ef-452d-ba23-6ebc22fbbf4f', } try: service = QcloudApi(module, config) print(service.generateUrl(action, action_params)) res=service.call(action, action_params) print(eval(res)) except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc())
#API 版本号 'Version':'2017-03-12', 'Filters':[ { 'Name':'zone', 'Values':['ap-beijing-1'] }, #这里加Filter条件 ], 'Limit':1, } try: service = QcloudApi(module, config) print(service.generateUrl(action, action_params)) res=service.call(action, action_params) import json print(res) temp=str(res).replace('b','') tmp=json.loads(temp.replace('\'','')) #添加弹性公网ip action = 'AllocateAddresses' module = 'eip' # 接口参数 action_params = { 'Version':'2017-03-12', 'AddressCount':'2', } print(111111) service = QcloudApi(module, config)
config = { 'Region': 'ap-beijing', 'secretId': 'AKIDYFqHXa0G82sW9bRtlXEwVt7B4kEZHsjO', 'secretKey': 'c2KQK2YwAD5lGaieP2Vo0GNJ3by98vYz', } action_params = { # 'limit':2, 'Version': '2017-03-12', 'InstanceIds.1': 'ins-3aesju6b', 'private-ip-address': '172.21.0.5', 'ForceStop': 'TRUE', } try: service = QcloudApi(module, config) # print(service.generateUrl(action, action_params)) service.call(action, action_params) # res=json.loads(answer) # print res #------------------------------ service.generateUrl(action, action_params) answer = (service.call(action, action_params)) print answer # print answer # zi_dict=eval(answer) `` # print zi_dict['totalCount'] # instance=(zi_dict['instanceSet'][0]) # print(len(zi_dict) # for instance in zi_dict['instanceSet']: # a=dict(instance.items()) # print(a)
class TencentWenZhi(BaseAPI): """docstring for TencentWenZhi""" 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 getAnsl(self, text): action = "TextSentiment" params = {'content': text, 'type': 1} res = self.service.call(action, params) res = json.loads(res.decode("utf-8")) if res['code'] == 0: if res['positive'] > res['negative']: return "1" elif res['positive'] < res['negative']: return "-1" else: return "0" else: print("error:" + text + " in TextSentiment\nMessage:" + res['message']) return "0" def fixWrongWord(text): action = "LexicalCheck" params = {'text': text} res = self.service.call(action, params) res = json.loads(res.decode("utf-8")) if res['code'] == 0: return res['text'] else: print("error:" + text + " in LexicalCheck\nMessage:" + res['message']) return text def cutWord(self, text, times, errormessage): if times > 5: print("error:" + text + " in LexicalAnalysis\nMessage: " + errormessage) jb = JieBa() return jb.cutWord(text) action = "LexicalAnalysis" params = {'text': text, 'code': 0x00200000} res = self.service.call(action, params) res = json.loads(res.decode("utf-8")) if res['code'] == 0: result = [] for r in res['tokens']: result.append(r['word']) return result else: return self.cutWord(text, times + 1, res['message']) def cutWordByCSVFile(self, filenamein, filenameout): rawdata = fileutil.readFileFromCSV(filenamein) fileutil.deleteFileIfExist(filenameout) result = "" totalProcess = len(rawdata) process = 0 for rd in rawdata: text = rd.text res = self.cutWord(text, 0, "") process = process + 1 self.showProcess(process, totalProcess) for r in res: result = result + r + " " result = result + "\n" fileutil.writeFile(filenameout, result)
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())
# '《三国演义》读后感', # '神奇的向日葵', # '论鲁迅先生', # '心有猛虎,细嗅蔷薇', ] for i in range(len(title_list)): params = { "title": title_list[i], "content": text_list[i], # "channel":"CHnews_news_others" } try: print(title_list[i]) print(text_list[i]) service = QcloudApi(module, config) print(service.call(action, params).decode('unicode_escape')) except Exception as e: print("exception:", e) # for sent in text_list: # params = { # "code":0x00200000, # "text":sent # } # print(sent) # try: # service = QcloudApi(module, config) # # print (service.generateUrl(action, params)) # # print(service.call(action, params)) # print(service.call(action, params).decode('unicode_escape')) # except Exception as e:
class Job: def __init__(self, config): self.config = config # scf api client cred = credential.Credential(config['secret_id'], config['secret_key']) self.scf_client = scf_client.ScfClient(cred, config['scf_region']) # cdn api client cdn_config = { 'Region': 'ap-guangzhou', 'method': 'GET', 'secretId': config['secret_id'], 'secretKey': config['secret_key'], 'SignatureMethod': 'HmacSHA1', } self.cdn_client = QcloudApi("cdn", cdn_config) self.cos_path = config['cos_path'] def get_cdn_log_urls(self, host): '''Getting the log download link for CDN (获取CDN的日志下载链接)''' CDN_LOG_STABLE_HOURS = 12 + 1 CDN_LOG_SAVE_HOURS = 1 now = datetime.datetime.now() end = now - datetime.timedelta(hours=CDN_LOG_STABLE_HOURS) start = end - datetime.timedelta(hours=CDN_LOG_SAVE_HOURS) action = "GetCdnLogList" action_params = { 'host': host, 'startDate': start.strftime("%Y-%m-%d %H:%M:%S"), 'endDate': end.strftime("%Y-%m-%d %H:%M:%S"), } rsp = self.cdn_client.call(action, action_params) data = json.loads(rsp) if data['code'] != 0: logging.error("API %s error: %s" % (action, data)) return [] urls = [v['link'] for v in data['data']['list'] if v['type']] if urls: logging.info("time(%s~%s) host[%s] log urls are:\n%s\n." % (start, end, host, "\n".join(urls))) else: logging.info("time(%s~%s) host[%s] log urls are empty" % (start, end, host)) return urls def get_cdn_hosts(self): '''Getting a list of all domain names under the account (获取账号下全部域名列表)''' # action = "DescribeCdnHosts" action = "DescribeDomains" end = datetime.datetime.now() start = end - datetime.timedelta(days=1) action_params = { 'detail': 0, } rsp = self.cdn_client.call(action, action_params) data = json.loads(rsp) if data['code'] != 0: logging.error("API %s error: %s" % (action, data)) return [] hosts = [v['host'] for v in data['data']['hosts']] logging.info("cdn hosts = %s" % hosts) return hosts def get_cos_key(self, url): ''' Parsing the URL to generate the storage path of COS format. The URL format is: /day/hour/dayhour-host.gz 解析URL,生成COS上的存储路径格式 URL格式为: /day/hour/dayhour-host.gz ''' parts = urlparse.urlparse(url) r = r'/(?P<day>[^/]*)/(?P<hour>[^/]*)/(?P<filename>[^-]*-(?P<host>[^/]*).gz)' m = re.match(r, parts.path) if not m: raise RuntimeError("cdn log url format is not support: %s" % url) v = m.groupdict() key = self.cos_path % v return key def invoke_cos_upload(self, url): event = dict(self.config) event.update({"url": url, "cos_key": self.get_cos_key(url)}) action = "Invoke" action_params = { 'InvocationType': "Event", # asynchronous 异步 'FunctionName': self.config['scf_function'], 'ClientContext': json.dumps(event), } # Calling the interface, initiating the request, and printing the returned result. 调用接口,发起请求,并打印返回结果 try: ret = self.scf_client.call(action, action_params) print(json.loads(ret)["Response"]["Result"]["RetMsg"]) except TencentCloudSDKException as err: print(err) def run(self): hosts = self.config['cdn_host'] if not hosts: hosts = self.get_cdn_hosts() cnt = 0 for host in hosts: urls = self.get_cdn_log_urls(host) for url in urls: self.invoke_cos_upload(url) cnt += len(urls) return { "status": "jobs dispatched", "count_url": cnt, "count_host": len(hosts) }
def create_cvm(self): module = 'cvm' ''' action: 对应接口的接口名,请参考产品 API 文档上对应接口的接口名 ''' action = 'RunInstances' ''' config: 云API的公共参数 # region = input('请输入您想要建立的地域:\n例如:beijing \n') # print(region) # print('------------------------') # num=input('请输入可用区:\n例如您想选择北京1区 您只需要输入数字 "1" \n') # print('------------------------') ''' config = { 'Region': 'ap-beijing', 'secretId': 'AKIDTp13vccxugHgv0QjOsBJG2d2HMH0Lv79', 'secretKey': '2vfFetxqZ7UghWBfy51nZROK5f5KOIBt', } ''' print('地域和地区选择成功') print('------------------------') charge_type = input('请输入您所需要的计费模式:\n例如:按量计费则请输入:POSTPAID_BY_HOUR\n按年计费则输入:PREPAID\n') print('------------------------') system_type = input('请选择您所需要/系统盘,类型如下:\n本地硬盘 : LOCAL_BASIC \n本地SSD硬盘 : LOCAL_SSD\n普通云硬盘 : CLOUD_BASIC\n云硬盘 : CLOUD_SSD\n') system_size = input('请选择您所需要的系统盘大小\n') print('系统盘大小和类型填写成功') print('------------------------') data_type = input('请选择您要的数据盘,类型如下:\n本地硬盘 : LOCAL_BASIC\n本地SSD硬盘 : LOCAL_SSD\n普通云硬盘 : CLOUD_BASIC\n高性能云硬盘 : CLOUD_PREMIUMSSD\n云硬盘 : CLOUD_SSD\n') data_size = input('请选择您所需要的数据盘大小\n') print('数据盘大小和类型填写成功') print('------------------------') cvm_name = input('请给您的实例进行命名\n') print('命名成功') print('------------------------') gongwang_ip = int(input('是否分配公网ip,如需分配请输入1 ,不分配则输入0\n')) print('分配成功') print('------------------------') ''' # 接口参数 action_params = { # API 版本号 'Version': '2017-03-12', # 计费类型 按量计费 'InstanceChargeType': 'POSTPAID_BY_HOUR', # 选择地域和可用区 'Placement.Zone': 'ap-beijing-3', # 镜像 'ImageId': 'img-8toqc6s3', # 镜像机型1C1G 标准型 'InstanceType': 'S2.SMALL1', # 系统盘的类型 'SystemDisk.DiskType': 'CLOUD_BASIC', # 'SystemDisk.DiskType':'CLOUD_BASIC', # 系统盘的大小 'SystemDisk.DiskSize': '60', # 数据盘类型 'DataDisks.0.DiskType': 'CLOUD_BASIC', # 数据盘大小 50 'DataDisks.0.DiskSize': '60', # 外网带宽上限10 'InternetAccessible.InternetMaxBandwidthOut': 10, # 分配公网ip 'InternetAccessible.PublicIpAssigned': True, # 实例命名 'InstanceName': 'liyanliang', } try: service = QcloudApi(module, config) print(service.generateUrl(action, action_params)) res = service.call(action, action_params) print(eval(res)) res = json.loads(res.decode()) print(res) self.res = res['Response']['InstanceIdSet'][0] print('云主机创建成功') except Exception as e: print(e) import traceback print('traceback.format_exc():\n%s' % traceback.format_exc())
def request_put(module,config,action,params): service = QcloudApi(module, config) str_results = service.call(action, params) json_results = json.loads(str_results) return json_results
def main_run(): # 遍历字典 for key, value in config_json.items(): # 如果cert_filename为空,则将证书文件名为默认的[domain_name].crt # 否则则加载配置文件中的文件名 if value['cert_filename'] == "": cert_filename = key + '.crt' else: cert_filename = value['cert_filename'] # 如果cert_filename为空,则将证书文件名为默认的[domain_name].key # 否则则加载配置文件中的文件名 if value['key_filename'] == "": key_filename = key + '.key' else: key_filename = value['key_filename'] check_cert_info_dict = check_cert_info(cert_file_folder + cert_filename) open_temp_file = try_to_open_file(tmp_file_path, 0) if open_temp_file[0]: open_temp_file = json.loads(open_temp_file[1]) if key in open_temp_file: if open_temp_file[key] == check_cert_info_dict['crt_serial_number']: continue else: pass else: pass else: pass if crt_chk_alt_name(key, check_cert_info_dict['crt_altname']): pass else: continue crt_not_valid_before = check_cert_info_dict['crt_not_valid_before'] crt_not_valid_after = check_cert_info_dict['crt_not_valid_after'] # 调用函数,检查证书是否合规 crt_key_dict = format_cert_key(key, cert_filename, key_filename, crt_not_valid_before, crt_not_valid_after) # 不合规则跳过,进入下一循环 if crt_key_dict: # 腾讯云基础设定 config = { 'secretId': value['secret_id'], 'secretKey': value['secret_key'], } cdn_domain_list = get_cdn_domain(config) if key in cdn_domain_list: action = 'SetHttpsInfo' module = 'cdn' params = { 'host': key, 'httpsType': value['https_type'], 'forceSwitch': value['https_force_switch'], 'http2': value['http2'], 'cert': crt_key_dict['crt'], 'privateKey': crt_key_dict['key'] } # 调用API service = QcloudApi(module, config) # 可输出编码后的URL,主要用于日志,也可以生成URL后手动执行 # 自动化应用一般不需要 # print(service.generateUrl(action, params)) # 执行API qcloud_output = service.call(action, params).decode() print(qcloud_output) write_temp_file(qcloud_output, key, check_cert_info_dict['crt_serial_number']) else: continue else: continue
Wenzhi_action = 'TextSentiment' Wenzhi_module = 'wenzhi' service = QcloudApi(Wenzhi_module, Wenzhi_config) # number_to_claw = input('输入想要抓取的新闻数, 默认为10\r\n') # if not number_to_claw: number_to_claw = 10 while True: print("开始抓取数据") data = ts.get_latest_news(number_to_claw, True) for index, val in data.iterrows(): print('processing {}/{}'.format(index + 1, len(data))) exist = rq.post('https://www.lyquant.com/api/news/check', {'url': val['url']}) if exist.status_code == 200: continue analysis = service.call(Wenzhi_action, { 'content': val['content'] }).decode('utf-8') result = rq.post( 'https://www.lyquant.com/api/news', { 'title': val['title'], 'url': val['url'], 'classify': val['classify'], 'content': val['content'], 'analysis': analysis }) print("等待下一轮查询") time.sleep(120)
'secretId': 'AKIDUs6A3kManoeoqgGxUtGSSGtKYaSDBtnV', 'secretKey': 'iFcpqfKyRirwLfmnsnY7Zs1yjKl283o6', 'method': 'post' } if __name__ == "__main__": service = QcloudApi(module, config) statusDao = StatusDao() # 过滤条件 filterCondition = {"emotion", None} statusItems = statusDao.queryCondition(filterCondition) for each in statusItems: text = each.text # 微博文本 if text is None: continue params = {"content": text} try: result = json.loads(service.call(action, params)) if result: if result["codeDesc"] == "Success": each.emotion = str(result["positive"]) statusDao.updateByItem(each) except Exception, e: print 'exception:', e
class Wenzhi(object): def __init__(self, secret_id, secret_key, region, method): """ 调用腾讯文智API处理文本的初始化 :param secret_id: 自己的secretID :param secret_key: 自己的secretKey :param region: 区域 :param method: 一般是POST """ self.module = 'wenzhi' self.config = { 'secretId': secret_id, 'secretKey': secret_key, 'Region': region, 'method': method } self.service = QcloudApi(self.module, self.config) def text_classify(self, content): """ 文本分类API,参考:http://nlp.qq.com/help.cgi# :param content: 格式参考文本分类API的文档 字段 类型 说明 title string 文章标题(选填),编码格式utf8 content string 正文内容,编码格式utf8( 必填) secd_nav string 二级导航(选填),编码格式utf8 url string 文章对应的url(选填) :return: dict """ action = 'TextClassify' # Key check keys = content.keys() if 'content' not in keys: raise KeyError("No param:content") result = self.service.call(action, content) return json.loads(result) def lexical_analysis(self, content): """ 分词与命名实体API,参考:http://nlp.qq.com/help.cgi# :param content: 格式参考分词与命名实体API的文档,不过content不需要提供code,将使用默认值 字段 类型 说明 text string 待词法分析的文本 code int text的编码(0x00200000== utf-8) 目前文智统一输入为utf-8,实际使用中本参数值为:2097152 type int (可选参数,默认为0) 0为基础粒度版分词,倾向于将句子切分的更细,在搜索场景使用为佳。 1为混合粒度版分词,倾向于保留更多基本短语不被切分开。 :return: dict """ action = 'LexicalAnalysis' # Key check keys = content.keys() if 'text' not in keys: raise KeyError("No param:text") if 'code' in keys: raise KeyError("No param:code need") content['code'] = 2097152 result = self.service.call(action, content) return json.loads(result) def text_sentiment(self, content): """ 情感分析API,参考:http://nlp.qq.com/help.cgi# :param content: 格式参考情感分析API的文档 字段 类型 说明 content string 待分析的文本(只能为utf8编码) type int (可选参数,默认为4) 1:电商;2:APP;3:美食;4:酒店和其他。 :return: dict """ action = 'TextSentiment' # Key check keys = content.keys() if 'content' not in keys: raise KeyError("No param:content in content") result = self.service.call(action, content) return json.loads(result.decode()) def text_keywords(self, content): """ 关键词提取API,参考:http://nlp.qq.com/help.cgi# :param content: 格式参考关键词提取API的文档 字段 类型 说明 title string 新闻标题(必填) channel string 新闻频道(选填 不填默认是科技) CHnews_news_sports 体育新闻 CHnews_news_ent 娱乐新闻 CHnews_news_astro 星座新闻 CHnews_news_auto 汽车新闻 CHnews_news_cul 文化新闻 CHnews_news_digi 数码新闻 CHnews_news_finance 财经新闻 CHnews_news_game 游戏新闻 CHnews_news_house 房产新闻 CHnews_news_lad 时尚新闻 CHnews_news_mil 军事新闻 CHnews_news_ssh 社会新闻 CHnews_news_tech 科技新闻 CHnews_news_others 其它 content string 新闻正文(必填) :return: dict """ action = 'TextKeywords' # Key check keys = content.keys() if 'title' not in keys: raise KeyError("No param:title") if 'content' not in keys: raise KeyError("No param:content in content") result = self.service.call(action, content) return json.loads(result) def text_dependency(self, content): """ 句法分析API,参考:http://nlp.qq.com/help.cgi# :param content: 格式参考句法分析API文档 字段 类型 说明 content string 待分析的文本(只能为utf8编码) :return: dict """ action = 'TextDependency' # Key check keys = content.keys() if 'content' not in keys: raise KeyError("No param:content in content") result = self.service.call(action, content) return json.loads(result)