def UpdateDomainRecord(accessKeyId,accessSecret,NewIP): client = AcsClient(accessKeyId,accessSecret, 'default') request = CommonRequest() request.set_accept_format('json') request.set_domain('alidns.aliyuncs.com') request.set_method('POST') request.set_protocol_type('https') # https | http request.set_version('2015-01-09') request.set_action_name('UpdateDomainRecord') request.add_query_param('RR', 'WWW') request.add_query_param('Value', NewIP) request.add_query_param('Type', 'A') request.add_query_param('RecordId', '') response = str(client.do_action(request), encoding = 'utf-8') msg=json.loads(response) if 'Message' in msg: msg = msg['Message'] content = stamp_to_time() + ' ' + msg + '\n' WriteContent('log.conf', content) else : content = stamp_to_time() + ' ' + 'the ip of demain liuyaoze.cn has change to :'+NewIP + '\n' WriteContent('log.conf', content)
def __common_request_settings(self): request = self.request request.set_accept_format('json') request.set_method('POST') request.set_protocol_type('https') # https | http request.set_version('2014-05-26') return request
def _baseControl(self, opt): """http交互""" host = Channel.HOST url = 'http://' + host + '/rest/3.0/' + self._product_name + '/' + self._resource_name http_method = 'POST' opt[Channel.SIGN] = self._genSign(http_method, url, opt) request = RequestCore(url) headers = dict() headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8' headers['User-Agent'] = 'BCCS_SDK/3.0' +\ Channel.SYSTEM_INFO +\ 'python/2.7.3 (Baidu Push Server SDK V3.0.0) cli/Unknown' for (headerKey , headerValue) in list(headers.items()): headerValue = headerValue.replace('\r', '') headerValue = headerValue.replace('\n', '') if (headerValue is not None): request.add_header(headerKey, headerValue) request.set_method(http_method) request.set_body(urllib.parse.urlencode(opt).encode(encoding='UTF8')) if(isinstance(self._curlOpts, dict)): request.set_curlopts(self._curlOpts) request.handle_request() return ResponseCore(request.get_response_header(), request.get_response_body(), request.get_response_code())
def _baseControl(self, opt): """http交互""" host = Channel.HOST url = 'http://' + host + '/rest/3.0/' + self._product_name + '/' + self._resource_name http_method = 'POST' opt[Channel.SIGN] = self._genSign(http_method, url, opt) request = RequestCore(url) headers = dict() headers[ 'Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8' headers['User-Agent'] = 'BCCS_SDK/3.0' +\ Channel.SYSTEM_INFO +\ 'python/2.7.3 (Baidu Push Server SDK V3.0.0) cli/Unknown' for (headerKey, headerValue) in list(headers.items()): headerValue = headerValue.replace('\r', '') headerValue = headerValue.replace('\n', '') if (headerValue is not None): request.add_header(headerKey, headerValue) request.set_method(http_method) request.set_body(urllib.parse.urlencode(opt).encode(encoding='UTF8')) if (isinstance(self._curlOpts, dict)): request.set_curlopts(self._curlOpts) request.handle_request() return ResponseCore(request.get_response_header(), request.get_response_body(), request.get_response_code())
def _open(self, method, path, headers=None, data=None): """Perform an HTTP request. Args: method: The HTTP method (GET, PUT, POST, DELETE). path: The HTTP path to retrieve. headers: A dictionary of HTTP headers to add. data: The data to send as the body of the request. Returns: A Response object. """ url = urllib.parse.urljoin(self.site, path) self.log.info('%s %s', method, url) request = self._request(url) request.set_method(method) if headers: for key, value in headers.items(): request.add_header(key, value) if self.auth: # Insert basic authentication header request.add_header('Authorization', 'Basic {}'.format(self.auth.decode())) if request.headers: header_string = '\n'.join([':'.join((k, v)) for k, v in request.headers.items()]) self.log.debug('request-headers:%s', header_string) if data: request.add_header('Content-Type', self.format.mime_type) request.add_data(data) self.log.debug('request-body:%s', request.get_data()) elif method in ['POST', 'PUT']: # Some web servers need a content length on all POST/PUT operations request.add_header('Content-Type', self.format.mime_type) request.add_header('Content-Length', '0') if self.timeout and not _urllib_has_timeout(): # Hack around lack of timeout option in python < 2.6 old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(self.timeout) try: http_response = None try: http_response = self._handle_error(self._urlopen(request)) except urllib.error.HTTPError as err: http_response = self._handle_error(err) except urllib.error.URLError as err: raise Error(err, url) response = Response.from_httpresponse(http_response) self.log.debug('Response(code=%d, headers=%s, msg="%s")', response.code, response.headers, response.msg) finally: if http_response: http_response.close() if self.timeout and not _urllib_has_timeout(): socket.setdefaulttimeout(old_timeout) self.log.info('--> %d %s %db', response.code, response.msg, len(response.body)) return response
def _prepare_request(method, uri, data): """Prepares the HttpRequest object""" if data is None: request = HttpRequest(uri) else: request = HttpRequest(uri, data) request.set_method(method) request.add_header('User-agent', mygpoclient.user_agent) return request
def get_token(): # 创建AcsClient实例 client = AcsClient("AccessKey ID", "AccessKeySecret", "cn-shanghai") # 创建request,并设置参数 request = CommonRequest() request.set_method('POST') request.set_domain('nls-meta.cn-shanghai.aliyuncs.com') request.set_version('2018-05-18') request.set_uri_pattern('/pop/2018-05-18/tokens') response = client.do_action_with_exception(request) response = json.loads(response.decode("utf-8")) print(response) # token_expireTime token的有效期(时间戳) access_token = response.get("Token").get("Id") token_expireTime = response.get("Token").get("ExpireTime") return access_token, token_expireTime
def alarm(message): print('开始发送信息:' + message) client = AcsClient(ACCESS_KEY_ID, ACCESS_SECRET, 'cn-hangzhou') request = CommonRequest() request.set_accept_format('json') request.set_domain('dysmsapi.aliyuncs.com') request.set_method('POST') request.set_protocol_type('https') request.set_version('2017-05-25') request.set_action_name('SendSms') request.add_query_param('RegionId', "cn-hangzhou") request.add_query_param('PhoneNumbers', PHONE_NUMBER) request.add_query_param('SignName', "KisPig网") request.add_query_param('TemplateCode', "SMS_184215625") request.add_query_param('TemplateParam', "{\"message\": \"" + message + "\"}") response = client.do_action_with_exception(request) print("通知短信%s已发送%s" % (message, response)) quit()
def make_fetch_call(rpc, url, payload=None, method=GET, headers={}, allow_truncated=False, follow_redirects=True, validate_certificate=None): """Executes the RPC call to fetch a given HTTP URL. The first argument is a UserRPC instance. See urlfetch.fetch for a thorough description of remaining arguments. Raises: InvalidMethodError: if requested method is not in _VALID_METHODS ResponseTooLargeError: if the response payload is too large InvalidURLError: if there are issues with the content/size of the requested URL Returns: The rpc object passed into the function. """ assert rpc.service == 'urlfetch', repr(rpc.service) if isinstance(method, str): method = method.upper() method = _URL_STRING_MAP.get(method, method) if method not in _VALID_METHODS: raise InvalidMethodError('Invalid method %s.' % str(method)) if _is_fetching_self(url, method): raise InvalidURLError( "App cannot fetch the same URL as the one used for " "the request.") request = urlfetch_service_pb.URLFetchRequest() response = urlfetch_service_pb.URLFetchResponse() if isinstance(url, str): url = url.encode('UTF-8') request.set_url(url) if method == GET: request.set_method(urlfetch_service_pb.URLFetchRequest.GET) elif method == POST: request.set_method(urlfetch_service_pb.URLFetchRequest.POST) elif method == HEAD: request.set_method(urlfetch_service_pb.URLFetchRequest.HEAD) elif method == PUT: request.set_method(urlfetch_service_pb.URLFetchRequest.PUT) elif method == DELETE: request.set_method(urlfetch_service_pb.URLFetchRequest.DELETE) elif method == PATCH: request.set_method(urlfetch_service_pb.URLFetchRequest.PATCH) if payload and method in (POST, PUT, PATCH): request.set_payload(payload) for key, value in headers.items(): header_proto = request.add_header() header_proto.set_key(key) header_proto.set_value(str(value)) request.set_followredirects(follow_redirects) if validate_certificate is not None: request.set_mustvalidateservercertificate(validate_certificate) if rpc.deadline is not None: request.set_deadline(rpc.deadline) rpc.make_call('Fetch', request, response, _get_fetch_result, allow_truncated) return rpc
def __test_msg(params): """测试短信接口 :return: 无返回值,测试结果通过控制台退出码获得。0为成功,非0为失败 """ params_config = { 'sms_interface_type': { 'must': True, 'data': True, 'short': 'I', 'long': 'interface' }, 'mobile': { 'must': True, 'data': True, 'short': 'M', 'long': 'mobile' }, 'ali_accesskeyid': { 'must': True, 'data': True, 'short': 'K', 'long': 'keyid' }, 'ali_accesssecret': { 'must': True, 'data': True, 'short': 'S', 'long': 'secret' }, 'ali_signname': { 'must': True, 'data': True, 'short': 'N', 'long': 'signname' }, 'ali_verify_templatecode': { 'must': True, 'data': True, 'short': 'T', 'long': 'template_id' }, } ret_dict = get(params_config, params) errcode = ret_dict.get('errcode') if errcode and errcode < 0: sys.exit(131) try: sms_interface_type = ret_dict.get('data').get('sms_interface_type') mobile = ret_dict.get('data').get('mobile') ali_accesskeyid = ret_dict.get('data').get('ali_accesskeyid') ali_accesssecret = ret_dict.get('data').get('ali_accesssecret') ali_signname = ret_dict.get('data').get('ali_signname') ali_verify_templatecode = ret_dict.get('data').get( 'ali_verify_templatecode') if sms_interface_type == "2": import urllib import urllib.request import hashlib statusStr = { '0': '短信发送成功', '-1': '参数不全', '-2': '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间', '30': '密码错误', '40': '账号不存在', '41': '余额不足', '42': '账户已过期', '43': 'IP地址限制', '50': '内容含有敏感词' } smsapi = "http://api.smsbao.com/" data = urllib.parse.urlencode({ 'u': ali_accesskeyid, 'p': ali_accesssecret, 'm': mobile, 'c': ali_signname }) send_url = smsapi + 'sms?' + data response = urllib.request.urlopen(send_url) the_page = response.read().decode('utf-8') if the_page != "0": print("\033[1;31m\n短信接口测试失败\n\033[0m") print(statusStr[the_page]) sys.exit(131) else: from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest client = AcsClient(ali_accesskeyid, ali_accesssecret, 'cn-hangzhou') request = CommonRequest() request.set_accept_format('json') request.set_domain('dysmsapi.aliyuncs.com') request.set_method('POST') request.set_protocol_type('https') # https | http request.set_version('2017-05-25') request.set_action_name('SendSms') request.add_query_param('RegionId', "cn-hangzhou") request.add_query_param('PhoneNumbers', mobile) request.add_query_param('SignName', ali_signname) request.add_query_param('TemplateCode', ali_verify_templatecode) request.add_query_param('TemplateParam', "{\"code\":8888}") response = client.do_action(request) result = str(response, encoding='utf-8') if result.find('"OK"') == -1: print("\033[1;31m\n短信接口测试失败\n\033[0m") print(result) sys.exit(131) print("\033[1;32m\n短信接口测试成功\n\033[0m") sys.exit(0) except Exception as e: print("\033[1;31m\n短信接口测试失败!\n\033[0m") print(e) sys.exit(131)
def make_fetch_call(rpc, url, payload=None, method=GET, headers={}, allow_truncated=False, follow_redirects=True, validate_certificate=None): """Executes the RPC call to fetch a given HTTP URL. The first argument is a UserRPC instance. See urlfetch.fetch for a thorough description of remaining arguments. Raises: InvalidMethodError: if requested method is not in _VALID_METHODS ResponseTooLargeError: if the response payload is too large InvalidURLError: if there are issues with the content/size of the requested URL Returns: The rpc object passed into the function. """ assert rpc.service == 'urlfetch', repr(rpc.service) if isinstance(method, str): method = method.upper() method = _URL_STRING_MAP.get(method, method) if method not in _VALID_METHODS: raise InvalidMethodError('Invalid method %s.' % str(method)) if _is_fetching_self(url, method): raise InvalidURLError("App cannot fetch the same URL as the one used for " "the request.") request = urlfetch_service_pb.URLFetchRequest() response = urlfetch_service_pb.URLFetchResponse() if isinstance(url, str): url = url.encode('UTF-8') request.set_url(url) if method == GET: request.set_method(urlfetch_service_pb.URLFetchRequest.GET) elif method == POST: request.set_method(urlfetch_service_pb.URLFetchRequest.POST) elif method == HEAD: request.set_method(urlfetch_service_pb.URLFetchRequest.HEAD) elif method == PUT: request.set_method(urlfetch_service_pb.URLFetchRequest.PUT) elif method == DELETE: request.set_method(urlfetch_service_pb.URLFetchRequest.DELETE) elif method == PATCH: request.set_method(urlfetch_service_pb.URLFetchRequest.PATCH) if payload and method in (POST, PUT, PATCH): request.set_payload(payload) for key, value in headers.items(): header_proto = request.add_header() header_proto.set_key(key) header_proto.set_value(str(value)) request.set_followredirects(follow_redirects) if validate_certificate is not None: request.set_mustvalidateservercertificate(validate_certificate) if rpc.deadline is not None: request.set_deadline(rpc.deadline) rpc.make_call('Fetch', request, response, _get_fetch_result, allow_truncated) return rpc