def payment_verify(receipt_data, sandbox=False): """apple_store支付票据验证 Args: receipt_data: 为apple前端支付后回来的票据, 已用base64编码 sandbox: 是否是沙箱环境 Returns: 验证成功返回支付数据,失败返回None """ # if sandbox: # verify_url = APPLE_SANDBOX_VERIFY_RECEIPTS_URL # else: # verify_url = APPLE_VERIFY_RECEIPTS_URL post_data = json.dumps({'receipt_data': receipt_data}) headers = {"Content-type": "application/json"} http_code, content = http.post(APPLE_VERIFY_RECEIPTS_URL, post_data, headers=headers, validate_cert=False) if http_code != 200: return None result = json.loads(content) if result['status'] == 21007: # The 21007 status code indicates that this receipt is a sandbox receipt, # but it was sent to the production service for verification. http_code, content = http.post(APPLE_SANDBOX_VERIFY_RECEIPTS_URL, post_data, headers=headers, validate_cert=False) if http_code != 200: return False result = json.loads(content) receipt = result.get('receipt') if not receipt or result['status'] != APPLE_VERIFY_SUCCESS_STATUS: return None return receipt
def test(): message = mix.Message() plain_text = "Nobody inspects the spammish repetition" message.text = None chain = ['no.onion', 'no.onion'] message.encode(plain_text, chain) http.post(message.packet.encode('base64'))
def beary_notify(message, chat_id, token): if chat_id is None or chat_id is "": return if token is None or token is "": return beary_hook_url = ("https://hook.bearychat.com/%s/incoming/%s" % (chat_id, token)) body = ('{"text":"%s"}' % (message)) http.post('beary', beary_hook_url, data=body, headers=http.def_headers)
def telegram_notify(message, chat_id, token): if chat_id is None or chat_id is "": return if token is None or token is "": return telegram_url = "https://api.telegram.org/bot%s/sendMessage" % (token) param = {"chat_id": chat_id, "text": message} http.post('telegram', telegram_url, params=param)
def init(): while True: inp = raw_input('1. Register RFID\n0. exit\n') if inp == 0 or inp == '0': break inp = raw_input('Enter RFID card number: ') print('Place RFID card on reader...') RFID = get_rfid_with_wait() print http.post([("card_id", inp), ("id", RFID)], "RFIDController/add")
def deregister_with_dnsseeder(self): deregister_url = '{}/deregister'.format(config.get_dnsseeder_url()) logger.info('trying to connect to dnsseeder at {}'.format(deregister_url)) try: http.post(deregister_url, {'port': config.get('port')}) logger.info('deregistered with dnsseeder') except: logger.info('could not deregister with dnsseeder')
def ding_talk_notify(message, token): if token is None or token is "": return ding_talk_hook_url = "https://oapi.dingtalk.com/robot/send?access_token=" + token body = ('{"msgtype":"text","text":{"content":"%s"}}' % (message)) http.post('ding_talk', ding_talk_hook_url, data=body, headers=http.def_headers)
def ding_talk_notify(message, token): if token is None or token is "": return try: ding_talk_hook_url = "https://oapi.dingtalk.com/robot/send?access_token=" + token body = ('{"msgtype":"text","text":{"content":"%s"}}' % (message)) http.post('ding_talk', ding_talk_hook_url, data=body, headers=http.def_headers) except Exception as e: logger.error("dingTalk notify error, msg:%s, exception:%s", message, e)
def _submit(metric_name, metric_value): host_port = MetricConfig.get_prometheus_host_port() if host_port is None or host_port is "": return url = 'http://%s/metrics/job/%s' % (host_port, metric_name) data = '%s\n' % metric_value http.post(Prometheus.action, url, data=data, headers=Prometheus.headers)
def telegram_notify(message, chat_id, token): if chat_id is None or chat_id is "": return if token is None or token is "": return try: telegram_url = "https://api.telegram.org/bot%s/sendMessage" % (token) param = {"chat_id": chat_id, "text": message} http.post('telegram', telegram_url, params=param) except Exception as e: logger.error("telegram notify error, msg:%s, exception:%s", message, e)
def _submit(metric): host_port = MetricConfig.get_prometheus_host_port() if host_port is None or host_port is "": return url = 'http://%s/metrics/job/%s/instance/%s' % ( host_port, Prometheus.job, Prometheus.instance) data = '%s\n' % metric http.post(Prometheus.action, url, data=data, headers=Prometheus.headers)
def beary_notify(message, chat_id, token): if chat_id is None or chat_id is "": return if token is None or token is "": return try: beary_hook_url = ("https://hook.bearychat.com/%s/incoming/%s" % (chat_id, token)) body = ('{"text":"%s"}' % (message)) http.post('beary', beary_hook_url, data=body, headers=http.def_headers) except Exception as e: logger.error("beary notify error, msg:%s, exception:%s", message, e)
def create_profile(state): try: http.post(state['api']+'/create_user', json=state['profile']).raise_for_status().close() except Exception as ex: print(ex) return False profile_json = ujson.dumps(state['profile']) database.set("tildr_profile", profile_json) return True
def dispatch(self, url, mode, parameters={}): oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, token = self.access_token, http_url = url, parameters = parameters, http_method = mode) oauth_request.sign_request(self.signature_method, self.consumer, self.access_token) if mode == "GET": url = oauth_request.to_url() response = get(url) return simplejson.loads(response) elif mode == "POST": header = oauth_request.to_header() post(url, parameters, header)
def add_tabs(config_file, es_url, sources=None): if sources == None: add_default_tabs(config_file, es_url) else: tabs = get_tabs(es_url, "True") data_sources = list_data_sources(config_file, json.loads(tabs)) for source in sources.split(", "): data_sources.append(source) tabs_list = list_tabs(config_file, data_sources) ordered_tabs_list = order_tabs(tabs_list) sources = tabs_to_post(ordered_tabs_list) http.post( es_url, sources, "\nTabs have been added successfully. Current tabs at (" + es_url.split("@")[1].split("/.kibana")[0] + "):\n")
def create_thread(): title = dialogs.prompt_text("Whats the title of the new thread?:") request = { "who": sim800.imei(), "title": title, } request_json = ujson.dumps(request) try: http.post(api_url + '/threads', json=request_json).raise_for_status().close() except: ugfx.clear() ugfx.text(5, 100, "Error. Try again later. :(", ugfx.BLACK) return False
def create_comment(thread): title = dialogs.prompt_text("Whats your comment?:") request = { "who": sim800.imei(), "comment": title, } request_json = ujson.dumps(request) try: http.post(api_url + "/threads/" + thread.threadID, json=request_json).raise_for_status().close() except: ugfx.clear() ugfx.text(5, 100, "Error. Try again later. :(", ugfx.BLACK) return False
def deploy_vm(self, name, os): url = "%s/%s/%s" % (self.url_openstack, self.id_tenant, "servers") print url headers = { 'X-Auth-Token': self.token, 'Content-Type': "application/json" } if os == 'ubuntu': payload = '{"server": '\ '{"name": " ' + name + '", '\ '"imageRef": "5babf339-0c4f-4947-a4cd-d87bd3b10a97", '\ '"flavorRef": "2"}}' else: payload = '{"server": '\ '{"name": " ' + name + '", '\ '"imageRef": "df44f62d-9d66-4dc5-b084-2d6c7bc4cfe4", '\ '"flavorRef": "2"}}' response = http.post(url, headers, payload) ## Si la respuesta es la adecuada, creo el diccionario de los datos en JSON. if response.status != 200 and response.status != 202: print 'error to deploy the vm ' + str(response.status) sys.exit(1) else: var = response.read() server = json.loads(var) self.id = server['server']['id'] self.ip = self.while_till_deployed(self.id) return self.ip
def __add_environment(self, url, environment_payload, headers=None): request_headers = {'X-Auth-Token': self.token, 'Tenant-Id': self.vdc, 'Content-Type': "application/xml"} if headers is not None: request_headers.update(headers) return http.post(url, request_headers, environment_payload)
def __add_tier(self, url, tier_payload): headers = { 'X-Auth-Token': self.token, 'Tenant-Id': self.vdc, 'Content-Type': "application/xml" } return http.post(url, headers, tier_payload)
def _request(self, method, timeout=DEFAULT_TIMEOUT, **kwargs): for key, value in kwargs.iteritems(): kwargs[key] = _to_request_encoding(value) if self.token: # http://vkontakte.ru/developers.php?oid=-1&p=Выполнение_запросов_к_API params = dict( access_token=self.token, ) params.update(kwargs) params['timestamp'] = int(time.time()) url = SECURE_API_URL + method secure = True else: # http://vkontakte.ru/developers.php?oid=-1&p=Взаимодействие_приложения_с_API params = dict( api_id=str(self.api_id), method=method, format='JSON', v='3.0', random=random.randint(0, 2 ** 30), ) params.update(kwargs) params['timestamp'] = int(time.time()) params['sig'] = self._signature(params) url = API_URL secure = False data = urllib.urlencode(params) headers = {"Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"} # urllib2 doesn't support timeouts for python 2.5 so # custom function is used for making http requests return http.post(url, data, headers, timeout, secure=secure)
def __request(self, method, url, headers, body, error): """ Launch a request and returns its response :param method: method used ex: POST, GET, DELETE, etc :param url: <IP>:<port>/<path> :param headers: headers used :param body: body in case of POST method :param error: error types :return: response """ headers['X-Auth-Token'] = utils.errorLabel (headers['X-Auth-Token'], error) url = utils.errorUrl(url, error) if error == "GET" or error == "PUT" or error == "POST" or error == "DELETE": method = error if method == "GET": response = http.get(url, headers) elif method == "POST": response = http.post(url, headers, body) elif method == "PUT": response = http.put(url, headers, body) elif method == "DELETE": response = http.delete(url, headers) #utils.printRequest(method,url,headers,body) # show request #utils.printResponse(response) # show response return response
def add_product(self, product_name, product_description, attributes, metadatas): url = "%s/%s" % (self.sdc_url, "catalog/product") headers = {'Content-Type': 'application/xml'} attributes = self.__process_attributes(attributes) metadatas = self.__process_attributes(metadatas) product = Product(product_name, product_description) for att in attributes: product.add_attribute(att) for meta in metadatas: product.add_metadata(meta) payload = product.to_product_xml() response = http.post(url, headers, tostring(payload)) ## Si la respuesta es la adecuada, creo el diccionario de los datos en JSON. if response.status != 200: print 'error to add the product sdc ' + str(response.status) sys.exit(1) else: self.products.append(product)
def _get_txn_id(self): status_code, response = http.post(auth_urls.GENERATE_OTP, json={"mobile": self.number}) if status_code != 200: print("OTP already sent") sys.exit() return response["txnId"]
def __request(self, method, url, headers, body, error): """ Launch a request and returns its response :param method: method used ex: POST, GET, DELETE, etc :param url: <IP>:<port>/<path> :param headers: headers used :param body: body in case of POST method :param error: error types :return: response """ headers['X-Auth-Token'] = utils.errorLabel(headers['X-Auth-Token'], error) url = utils.errorUrl(url, error) if error == "GET" or error == "PUT" or error == "POST" or error == "DELETE": method = error if method == "GET": response = http.get(url, headers) elif method == "POST": response = http.post(url, headers, body) elif method == "PUT": response = http.put(url, headers, body) elif method == "DELETE": response = http.delete(url, headers) #utils.printRequest(method,url,headers,body) # show request #utils.printResponse(response) # show response return response
def add_product(self, product_name, product_description, attributes, metadatas): print 'add_product' url = "%s/%s" % (self.sdc_url, "catalog/product") headers = { 'X-Auth-Token': self.token, 'Tenant-Id': self.vdc, 'Accept': "application/json", 'Content-Type': 'application/xml' } attributes = self.__process_attributes(attributes) metadatas = self.__process_attributes(metadatas) product = Product(product_name, product_description) for att in attributes: product.add_attribute(att) for meta in metadatas: product.add_metadata(meta) payload = product.to_product_xml() response = http.post(url, headers, tostring(payload)) ## Si la respuesta es la adecuada, creo el diccionario de los datos en JSON. if response.status != 200: print 'error to add the product sdc ' + str(response.status) sys.exit(1) else: self.products.append(product)
def deploy_vm(self, name, os): url = "%s/%s/%s" % (self.url_openstack, self.id_tenant, "servers") print url headers = {'X-Auth-Token': self.token, 'Content-Type': "application/json"} if os == 'ubuntu': payload = '{"server": '\ '{"name": " ' + name + '", '\ '"imageRef": "5babf339-0c4f-4947-a4cd-d87bd3b10a97", '\ '"flavorRef": "2"}}' else: payload = '{"server": '\ '{"name": " ' + name + '", '\ '"imageRef": "df44f62d-9d66-4dc5-b084-2d6c7bc4cfe4", '\ '"flavorRef": "2"}}' response = http.post(url, headers, payload) ## Si la respuesta es la adecuada, creo el diccionario de los datos en JSON. if response.status != 200 and response.status != 202: print 'error to deploy the vm ' + str(response.status) sys.exit(1) else: var = response.read() server = json.loads(var) self.id = server['server']['id'] self.ip = self.while_till_deployed(self.id) return self.ip
def add_tabs(config_file, es_url, sources=None): if sources == None: add_default_tabs(config_file, es_url) else: tabs = get_tabs(es_url, "True") data_sources = list_data_sources(config_file, json.loads(tabs)) for source in sources.split(", "): data_sources.append(source) tabs_list = list_tabs(config_file, data_sources) ordered_tabs_list = order_tabs(tabs_list) sources = tabs_to_post(ordered_tabs_list) http.post( es_url, sources, "\nTabs have been added successfully. Current tabs at (" + es_url.split("@")[1].split("/.kibana")[0] + "):\n", )
def __add_product_sdc(self, url, product_sdc_payload): """ Add product to SDC catalog """ headers = { 'X-Auth-Token': self.token, 'Tenant-Id': self.vdc, 'Content-Type': "application/xml" } return http.post(url, headers, product_sdc_payload)
def remove_tabs(config_file, es_url, sources=None): tabs = get_tabs(es_url, "True") data_sources = list_data_sources(config_file, tabs) ds = list(data_sources) if sources == None: for source in ds: data_sources.remove(source) else: for source in sources.split(", "): data_sources.remove(source) tabs_list = list_tabs(config_file, data_sources) ordered_tabs_list = order_tabs(tabs_list) sources = tabs_to_post(ordered_tabs_list) http.post( es_url, sources, "\nTabs have been removed successfully. Current tabs at (" + es_url.split("@")[1].split("/.kibana")[0] + "):\n")
def remove_tabs(config_file, es_url, sources=None): tabs = get_tabs(es_url, "True") data_sources = list_data_sources(config_file, tabs) ds = list(data_sources) if sources == None: for source in ds: data_sources.remove(source) else: for source in sources.split(", "): data_sources.remove(source) tabs_list = list_tabs(config_file, data_sources) ordered_tabs_list = order_tabs(tabs_list) sources = tabs_to_post(ordered_tabs_list) http.post( es_url, sources, "\nTabs have been removed successfully. Current tabs at (" + es_url.split("@")[1].split("/.kibana")[0] + "):\n", )
def create_pin(board,note,link,image_url): url = pinterest_api_url + 'pins/' params = { 'board': board, 'note': note, 'link': link, 'image_url': image_url } response = post(url, params)
def login_verify(login_type, openid, openkey, userip='', is_sandbox=False): """ 登录验证 :param login_type: 环境 1: 手机QQ 2: 微信 :param openid: 普通用户唯一标识(QQ平台) | 普通用户唯一标识(微信平台) :param openkey: 授权凭证access_token | 授权凭证 :param userip: 用户客户端ip :param is_sandbox: 是否沙箱 :return: """ env = mapping[login_type] config = PLATFORM_SETTINGS.get(env) if not config: return False now = int(time.time()) if env == 'wechat': # 微信 params = { 'openid': openid, 'accessToken': openkey, } else: # 手机QQ params = { 'appid': config['app_id'], 'openid': openid, 'openkey': openkey, 'userip': userip } app_key = config['app_key'] qs = urllib.urlencode({ 'appid': config['app_id'], 'timestamp': now, 'sig': mk_msdk_sig(app_key, now), 'encode': 1, 'openid': openid, }) host = get_host(is_sandbox) url = '%s%s?%s' % (host, config['login_verify_url'], qs) http_code, content = http.post(url, json.dumps(params), timeout=10) if http_code != 200: return None obj = json.loads(content) if obj.get('ret') != 0: return None return openid
def __get__token(self, url, payload): """ Builds the request to get a token from Keystone :param url: Full URL to execute POST method :param payload: Body of the request :return: HTTPlib response """ headers = {'Content-Type': 'application/json', 'Accept': "application/json"} return http.post(url, headers, payload)
def login_verify(authorization_code, app_type): """ sid用户会话验证 Args: authorization_code: authorization_code app_type: 标识ios类型,1表示正式版,0表示越狱版, 2表示android Returns: 用户标识id """ platform_mapping = {0: 'cmge', 1: 'cmgeapp', 2: 'androidcmge'} conf = PLATFORM_CMGE_SETTINGS[app_type] access_token = get_access_token(authorization_code, conf) if not access_token: return None userinfo_post_data = urllib.urlencode({ 'access_token': access_token, }) http_code, content = http.post(conf['user_info_uri'], userinfo_post_data) if http_code != 200: return None obj = json.loads(content) # {u'username': u'U12638056', u'cmStatus': 0, u'codes': u'0', u'id': 10721935, u'sdkuserid': u'U12638056'} if int(obj['codes']) != 0: return None openid = obj['id'] tel = obj.get('tel', '') if tel: # TODO: 前端发新包之后删除 # 2014年5月20日12:00~5月30日12:00 end_time = 1401422400 # 5月30日12:00 if time.time() < 30 * 24 * 3600 + end_time: from models.user import UnameUid, User account = '%s_%s' % (platform_mapping.get(app_type, ''), openid) uu = UnameUid.get(account) if uu.current_server: uid = uu.servers.get(uu.current_server) if uid: u = User.get(uid, uu.current_server) if not u.mobile: u.moblie = tel u.save() return { 'openid': openid, 'access_token': access_token, 'sdkuserid': obj['sdkuserid'], 'username': obj['username'], 'code': authorization_code, 'tel': tel, }
def process_putlocker_ws(hoster, url): payload = { 'freeuser': '******', 'confirm': 'Continue as Free User', } data = post(url=url, data=payload) for line in data.split('\n'): if 'url: \'' in line: line = re.sub(r'^.*url: \'', '', line) return re.sub(r'\',.*$', '', line) return None
def __add_environment(self, url, environment_payload): headers = {'X-Auth-Token': self.token, 'Tenant-Id': self.vdc, 'Content-Type': "application/xml"} print headers response = http.post(url, headers, environment_payload) ## Si la respuesta es la adecuada, creo el diccionario de los datos en JSON. if response.status != 200 and response.status != 204: data = response.read() print 'error to add an environment ' + str(response.status) + " " + data sys.exit(1)
def _confirm_otp(self, txn_id): otp = str(input("Enter OTP: ")) hashed_otp = sha256(otp).hexdigest() status_code, response = http.post(auth_urls.CONFIRM_OTP, json={ "otp": hashed_otp, "txnId": txn_id }) if status_code == 200: return response["token"] sys.exit()
def get_keystone_token(): """Gets Keystone Auth token""" req_json = {"auth":{"passwordCredentials":{"username":config.USERNAME, "password":config.PASSWORD}}} header = '{"Host": "identity.api.rackspacecloud.com",' header += '"Content-Type": "application/json","Accept": "application/json"}' url = config.AUTH_URL response = http.post(url = url, header = header, body = req_json) responsebody = json.loads(response.text) authtoken = responsebody["access"]["token"]["id"] return authtoken
def __get__token(self, url, payload): """ Builds the request to get a token from Keystone :param url: Full URL to execute POST method :param payload: Body of the request :return: HTTPlib response """ headers = { 'Content-Type': 'application/json', 'Accept': "application/json" } return http.post(url, headers, payload)
def login(email, password): """Tries to authenticate the specified user Returns: The portalid string in case of success or None otherwise """ response, headers, cookies = http.post(constants.loginUrl, data = { 'j_username': email, 'j_password': password, 'returnURL': constants.baseUrl + '/forward.php', }, returnHeaders = True) return cookies['portalid'] if 'portalid' in cookies else None
def add_service (self, template_id, service): url = "http://{0}/v1/templates/{1}/services".format(self.murano_url, template_id) headers = {'X-Auth-Token': self.token, 'Accept': "application/json", 'Content-Type': 'application/json'} payload = json.dumps(service.to_json()) response = http.post(url, headers, payload) print "Deploying services in the template " + url print payload if response.status != 200: print 'error to deploy service in template ' + str(response.status) exit ()
def _request(self, url, data): """ self._request('', {}) """ authObj = self._auth() headers = self._getAuthHeaders('POST', url) params = self._getParams(authObj) response = http.post(url, data=data, params=params, headers=headers) obj = self._proccessResult(response) if not self._isCloudUser and obj.get('error_code', '') == 110: authObj = self._auth(True) params = self._getParams(authObj) response = http.post(url, data=data, params=params, headers=headers) obj = self._proccessResult(response) return obj
def process_sockshare_ws(hoster, url): root = get_tree(url) try: filehash = root.xpath('//input[@name="hash"]')[0].attrib['value'] except IndexError: return None payload = { 'hash': filehash, 'agreeButton': 'Continue as Free User', } data = post(url=url, data=payload) root = html.fromstring(data) return root.xpath('//a[@id="player"]')[0].attrib['href']
def post_gist(text): payload = { "description": "Jake Bot Output", "public": False, "files": { "output.txt": { "content": text } } } json_data = http.post('https://api.github.com/gists', payload, headers={"Content-Type": "application/json"}) return json_data['html_url']
def deploy_env (self, env_id, conf_id): url = "http://{0}/v1/environments/{1}/sessions/{2}/deploy".format(self.murano_url, env_id, conf_id) headers = {'X-Auth-Token': self.token, 'X-Configuration-Session': conf_id, 'Accept': "application/json", 'Content-Type': 'application/json'} print "Deploying the environment " + url payload="" response = http.post(url, headers, payload) if response.status != 200: print 'error to deploy the env ' + str(response.status) return
def deploy_software (self, token, env_id, conf_id, service): url = "http://{0}/v1/environments/{1}/services".format(self.murano_url, env_id) headers = {'X-Auth-Token': token, 'X-Configuration-Session': conf_id, 'Accept': "application/json", 'Content-Type': 'application/json'} payload = json.dumps(service.to_json()) response = http.post(url, headers, payload) print "---------------------------------------------" print "Deploying services in the environment " + url print payload print "---------------------------------------------" if response.status != 200: print 'error to get the product ' + str(response.status) exit ()
def configure_env (self,token, env_id): url = "http://{0}/v1/environments/{1}/configure".format(self.murano_url, env_id) headers = {'X-Auth-Token': token, 'Accept': "application/json", 'Content-Type': 'application/json'} payload='' response = http.post(url, headers, payload) if response.status != 200: print 'error to get the product ' + str(response.status) return else: response_json = json.load(response) id = response_json['id'] return id
def process_putlocker_com(hoster, url): root = get_tree(url) try: filehash = root.xpath('//input[@name="hash"]')[0].attrib['value'] except IndexError: return None payload = { 'hash': filehash, 'confirm': 'Continue as Free User', } data = post(url=url, data=payload) root = html.fromstring(data) remote_file = root.xpath( '//a[@class="download_file_link"]' )[0].attrib['href'] return 'http://www.{}{}'.format(hoster, remote_file)
def add_product_release(self, product_name, version): url = "%s/%s/%s/%s" % (self.sdc_url, "catalog/product", product_name, "release") headers = {'Content-Type': 'application/xml'} # product = self.get_product_info (product_name) product = Product(product_name) product_release = ProductRelease(product, version) payload = product_release.to_product_xml() response = http.post(url, headers, tostring(payload)) ## Si la respuesta es la adecuada, creo el diccionario de los datos en JSON. if response.status != 200: print 'error to add the product release to sdc ' + str(response.status) sys.exit(1) else: self.products.append(product)
def create_template(self, template_name): url = "http://{0}/v1/templates".format(self.murano_url) headers = {'X-Auth-Token': self.token, 'Accept': "application/json", 'Content-Type': 'application/json'} payload="{\"name\": \""+template_name+"\"}" print "Creating a blueprint template " + url print payload response = http.post(url, headers, payload) if response.status != 200: print 'error to create the environment ' + str(response.status) exit() else: response_json = json.load(response) id = response_json['id'] return id
def request(api_id, api_secret, method, timestamp=None, timeout=DEFAULT_TIMEOUT, **kwargs): #raise Exception(method) params = dict( api_id = str(api_id), method = method, format = 'JSON', v = '3.0', random = random.randint(0, 2**30), timestamp = timestamp or int(time.time()) ) params.update(kwargs) params['sig'] = signature(api_secret, params) data = urllib.urlencode(params) # urllib2 doesn't support timeouts for python 2.5 so # custom function is used for making http requests headers = {"Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"} return http.post(API_URL, data, headers, timeout)
def convert_to_environment(token, template_id, env_name): url = "http://130.206.84.6:8082/v1/templates/"+template_id+"/create-environment" headers = {'X-Auth-Token': token, 'Accept': "application/json", 'Content-Type': 'application/json'} payload="{\"name\": \""+env_name+"\", \"network\": \"dd\"}" response = http.post(url, headers, payload) print "Convert template into environment " + url if response.status != 200: print 'error to get the product ' + str(response.status) exit () else: result = [] response_json = json.load(response) result.append(response_json['environment_id']) result.append(response_json['session_id']) return result
def convert_to_environment(self, template_id, env_name): url = "http://{0}/v1/templates/{1}/create-environment".format(self.murano_url, template_id) headers = {'X-Auth-Token': self.token, 'Accept': "application/json", 'Content-Type': 'application/json'} payload="{\"name\": \""+env_name+"\"}" response = http.post(url, headers, payload) print "Convert template into environment " + url if response.status != 200: print 'error convert to environment' + str(response.status) exit () else: result = [] response_json = json.load(response) result.append(response_json['environment_id']) result.append(response_json['session_id']) return result
def process_gorillavid_in(hoster, url): root = get_tree(url) try: ident = root.xpath('//form/input[@name="id"]')[0].attrib['value'] except IndexError: return None payload = { 'op': 'download1', 'usr_login': '', 'channel': '', 'method_free': 'Kostenloser Download', 'id': ident, } data = post(url=url, data=payload) for line in data.split('\n'): if 'file: "' in line: line = re.sub(r'^.*file: "', '', line) return re.sub(r'",.*$', '', line) return None
def request(method, url, headers, body, error): headers['X-Auth-Token'] = errorLabel (headers['X-Auth-Token'], error) url = errorUrl(url, error) if error == "GET" or error == "PUT" or error == "POST" or error == "DELETE": method = error if method == "GET": response = http.get(url, headers) elif method == "POST": response = http.post(url, headers, body) elif method == "PUT": response = http.put(url, headers, body) elif method == "DELETE": response = http.delete(url, headers) printRequest(method,url,headers,body) #printResponse(response) return response
def create_env(self, token, env): url = "http://{0}/v1/environments".format(self.murano_url) headers = {'X-Auth-Token': token, 'Accept': "application/json", 'Content-Type': 'application/json'} payload=json.dumps(env.to_json()) #payload="{\"name\": \""+env_name+"\", \"defaultNetworks\": { \"environment\": {\"?\": {\"id\": 234, \"type\": \"io.murano.resources.ExistingNeutronNetwork\"}, \"internalNetworkName\": \"node-int-net-01\" }}}" print "---------------------------------------------" print "Creating an empty environment " + url print "---------------------------------------------" response = http.post(url, headers, payload) if response.status != 200: print 'error to create the environment ' + str(response.status) exit() else: response_json = json.load(response) print response_json id = response_json['id'] return id