当前位置: 首页>>代码示例>>Python>>正文


Python client.HTTPException方法代码示例

本文整理汇总了Python中http.client.HTTPException方法的典型用法代码示例。如果您正苦于以下问题:Python client.HTTPException方法的具体用法?Python client.HTTPException怎么用?Python client.HTTPException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在http.client的用法示例。


在下文中一共展示了client.HTTPException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: translate_text

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def translate_text(query, source_lang_code, target_lang_code):
    """returns translated text or text indicating a translation/network error

    Takes a text to be translated, source language and target language code
    2 letter ISO code found in language_list.py
    """

    try:
        translations = TRANSLATION_SERVICE.translations().list(
            source=source_lang_code,
            target=target_lang_code,
            q=query
        ).execute()
        translation = translations['translations'][0]
        if 'detectedSourceLanguage' in translation.keys():
            source_lang_code = translation['detectedSourceLanguage']
        resp = random.choice(_TRANSLATE_RESULT).format(
            text=translation['translatedText'],
            fromLang=language_code_dict[source_lang_code],
            toLang=language_code_dict[target_lang_code])
    except (HTTPError, URLError, HTTPException):
        resp = random.choice(_TRANSLATE_NETWORK_ERROR)
    except Exception:
        resp = random.choice(_TRANSLATE_ERROR)
    return resp 
开发者ID:dialogflow,项目名称:fulfillment-translate-python,代码行数:27,代码来源:main.py

示例2: send

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def send(verb, endpoint, body):
    __API_LISTENER = __IP_ADDR + ":" + __PORT
    iprint("sending to: " + __API_LISTENER)
    try:
        conn = httplib.HTTPConnection(__API_LISTENER)
        if len(body) != 0:
            conn.request(
                verb,
                endpoint,
                body,
                {"Content-Type": "application/json"}
            )
        else :
            conn.request(verb, endpoint)

        response = conn.getresponse()
        body = response.read()
        return response.status, response.reason, body
    except (httplib.HTTPException, socket.error) as ex:
        print ("Error: %s" % ex)
        quit() 
开发者ID:nanoleaf,项目名称:aurora-sdk-mac,代码行数:23,代码来源:AuroraAPI.py

示例3: upload

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def upload(server, username, token, filename, file):
    print("Connecting to Server")
    route = routes(server)
    data = None
    connection = _form_connect(server)
    try:
        connection.connect()
        print("Connection Established...")
        headers, body = multipart_encoder(
            {"username": username, "token": token}, {"file": file})

        print("Sending Request",
              route["asset_upload"], " This may take a while.")
        connection.request("POST", route["asset_upload"], body, headers)

        res = connection.getresponse()
        data = res.read()
        print("Response:")
        print(data)
    except HTTPException as e:
        print("HttpException Occurred", e)
    finally:
        connection.close()

    return data.decode("utf-8") 
开发者ID:Menithal,项目名称:Blender-Metaverse-Addon,代码行数:27,代码来源:client.py

示例4: test_named_sequences_full

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def test_named_sequences_full(self):
        # Check all the named sequences
        url = ("http://www.pythontest.net/unicode/%s/NamedSequences.txt" %
               unicodedata.unidata_version)
        try:
            testdata = support.open_urlresource(url, encoding="utf-8",
                                                check=check_version)
        except (OSError, HTTPException):
            self.skipTest("Could not retrieve " + url)
        self.addCleanup(testdata.close)
        for line in testdata:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            seqname, codepoints = line.split(';')
            codepoints = ''.join(chr(int(cp, 16)) for cp in codepoints.split())
            self.assertEqual(unicodedata.lookup(seqname), codepoints)
            with self.assertRaises(SyntaxError):
                self.checkletter(seqname, None)
            with self.assertRaises(KeyError):
                unicodedata.ucd_3_2_0.lookup(seqname) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:23,代码来源:test_ucn.py

示例5: update_analyst_ratings

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def update_analyst_ratings(self, alert_id, severity='SEVERITY_UNDECIDED', expectation='EXP_UNKNOWN', comments='',
                               share_irondome=False):
        self.logger.debug('Submitting analyst rating: Alert ID={} Severity={} Expected={} Comments={} Share '
                          'w/IronDome={}'.format(alert_id, severity, expectation, comments, share_irondome))

        req_body = {
            'alert_id': alert_id,
            'analyst_severity': 'SEVERITY_' + severity.upper(),
            'analyst_expectation': 'EXP_' + expectation.upper(),
            'comment': comments,
            'share_comment_with_irondome': share_irondome
        }
        response = self._http_request('POST', '/RateAlert', body=json.dumps(req_body))
        if response.status_code != 200:
            err_msg = self._get_error_msg_from_response(response)
            self.logger.error('Failed to rate alert ({}). The response failed with status code {}. The response was: '
                              '{}'.format(alert_id, response.status_code, response.text))
            raise HTTPException('Failed to rate alert {} ({}): {}'.format(alert_id, response.status_code, err_msg))
        else:
            self.logger.debug('Successfully submitted rating for alert ({})'.format(alert_id))
            return 'Submitted analyst rating to IronDefense!' 
开发者ID:demisto,项目名称:content,代码行数:23,代码来源:IronDefense.py

示例6: add_comment_to_alert

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def add_comment_to_alert(self, alert_id, comment='', share_irondome=False):
        self.logger.debug('Submitting comment: Alert ID={} Comment={} Share '
                          'w/IronDome={}'.format(alert_id, comment, share_irondome))

        req_body = {
            'alert_id': alert_id,
            'comment': comment,
            'share_comment_with_irondome': share_irondome
        }
        response = self._http_request('POST', '/CommentOnAlert', body=json.dumps(req_body))
        if response.status_code != 200:
            err_msg = self._get_error_msg_from_response(response)
            self.logger.error('Failed to add comment to alert ({}). The response failed with status code {}. The '
                              'response was: {}'.format(alert_id, response.status_code, response.text))
            raise HTTPException('Failed to add comment to alert {} ({}): {}'.format(alert_id, response.status_code,
                                err_msg))
        else:
            self.logger.debug('Successfully added comment to alert ({})'.format(alert_id))
            return 'Submitted comment to IronDefense!' 
开发者ID:demisto,项目名称:content,代码行数:21,代码来源:IronDefense.py

示例7: set_alert_status

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def set_alert_status(self, alert_id, status='STATUS_NONE', comments='', share_irondome=False):
        self.logger.debug('Submitting status: Alert ID={} Status={} Comments={} Share '
                          'w/IronDome={}'.format(alert_id, status, comments, share_irondome))

        req_body = {
            'alert_id': alert_id,
            'status': 'STATUS_' + status.upper().replace(" ", "_"),
            'comment': comments,
            'share_comment_with_irondome': share_irondome
        }
        response = self._http_request('POST', '/SetAlertStatus', body=json.dumps(req_body))
        if response.status_code != 200:
            err_msg = self._get_error_msg_from_response(response)
            self.logger.error('Failed to set status for alert ({}). The response failed with status code {}. The '
                              'response was: {}'.format(alert_id, response.status_code, response.text))
            raise HTTPException('Failed to set status for alert {} ({}): {}'.format(alert_id, response.status_code,
                                err_msg))
        else:
            self.logger.debug('Successfully submitted status for alert ({})'.format(alert_id))
            return 'Submitted status to IronDefense!' 
开发者ID:demisto,项目名称:content,代码行数:22,代码来源:IronDefense.py

示例8: _do_api_request

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def _do_api_request(email, organization_id):
    data = json.dumps({"email": email, "organization_id": organization_id}).encode("utf-8")
    url = os.environ.get("BOOTSTRAP_API_URL", "https://bms.parsec.cloud/api/quickjoin")
    req = Request(url, method="POST", data=data, headers={"Content-Type": "application/json"})
    try:
        response = await trio.to_thread.run_sync(lambda: urlopen(req))
        if response.status != 200:
            raise JobResultError("invalid_response")
        try:
            content = await trio.to_thread.run_sync(lambda: response.read())
            content = json.loads(content)
            if content.get("error", None):
                raise JobResultError(content["error"])
            return (
                content["parsec_id"],
                BackendOrganizationBootstrapAddr.from_url(content["bootstrap_link"]),
            )
        except (TypeError, KeyError) as exc:
            raise JobResultError("invalid_response", exc=exc)
    except (HTTPException, URLError) as exc:
        raise JobResultError("offline", exc=exc) 
开发者ID:Scille,项目名称:parsec-cloud,代码行数:23,代码来源:create_org_widget.py

示例9: get_ord_book

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def get_ord_book(self, pair):
        error_count = 0
        book_returned = False
        ord_book = {}
        fail = False
        self.lg.log('Getting order book for pair ' + pair)

        while not book_returned and not fail:
            try:
                ord_book = client.depth(pair, limit=5)
            except (MalformedRequest, InternalError, StatusUnknown,
                    ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__) + ' ' + 'Order book retrieve for ' + pair +
                            ' failed, keep trying')
                error_count += 1
                time.sleep(1)
                client.set_offset()
            else:
                book_returned = True
            finally:
                if error_count >= 5:
                    self.lg.log("Tried to get order book 5 times and failed")
                    fail = True
        return {"ord_book": ord_book, "fail_flag": fail} 
开发者ID:Reidmcc,项目名称:Binance-bot,代码行数:26,代码来源:mult_arbit.py

示例10: get_open_ords

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def get_open_ords(self, pair):
        error_count = 0
        got_ords = False
        open_ords = {}
        # self.lg.log('Getting open orders for pair ' + pair)
        while not got_ords and error_count < 10:
            try:
                open_ords = client.openOrders(pair)
            except (
            MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError,
            HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__) + ' ' + 'Open order request failed try again')
                error_count += 1
                time.sleep(1)
                client.set_offset()
            else:
                got_ords = True
            finally:
                if error_count >= 10:
                    self.lg.log('Open orders check failed 10 times')
        return open_ords 
开发者ID:Reidmcc,项目名称:Binance-bot,代码行数:23,代码来源:mult_arbit.py

示例11: route_check_altfirst

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def route_check_altfirst(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip):
        calc_done = False
        route_gain = -1
        bid_p1 = -1
        ask_p2 = -1
        bid_p3 = -1
        while calc_done == False:
            try:
                bid_p1 = float(client.depth(pair_1, limit = 5)['bids'][0][0])
                ask_p2 = float(client.depth(pair_2, limit = 5)['asks'][0][0])
                bid_p3 = float(client.depth(pair_3, limit = 5)['bids'][0][0])
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                route_gain = (1 / (bid_p1 + pair_1_pip)) * (ask_p2 - pair_2_pip)  / (bid_p3 + pair_3_pip)
                calc_done = True

        return (route_gain, bid_p1, ask_p2, bid_p3) 
开发者ID:Reidmcc,项目名称:Binance-bot,代码行数:21,代码来源:data_checks.py

示例12: route_check_altlast

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def route_check_altlast(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip):
        calc_done = False
        route_gain = -1
        bid_p2 = -1
        ask_p3 = -1
        ask_p1 = -1
        while calc_done == False:
            try:
                ask_p1 = float(client.depth(pair_1, limit = 5)['asks'][0][0]) - float(pair_1_pip)
                bid_p2 = float(client.depth(pair_2, limit = 5)['bids'][0][0]) + float(pair_2_pip)
                ask_p3 = float(client.depth(pair_3, limit = 5)['asks'][0][0]) - float(pair_3_pip)
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                # route_gain = ((ask_p1 - pair_1_pip) / ((bid_p2 + pair_2_pip)) * (ask_p3 - pair_3_pip))
                route_gain = ask_p1  / bid_p2 * ask_p3
                calc_done = True
        return (route_gain, ask_p1, bid_p2, ask_p3) 
开发者ID:Reidmcc,项目名称:Binance-bot,代码行数:21,代码来源:data_checks.py

示例13: route_check_altlast_take_t3

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def route_check_altlast_take_t3(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip):
        calc_done = False
        route_gain = -1
        ask_p1 = -1
        bid_p2 = -1
        bid_p3 = -1
        p3_bid_quant = -1
        while calc_done == False:
            try:
                ask_p1 = float(client.depth(pair_1, limit = 5)['asks'][0][0])
                bid_p2 = float(client.depth(pair_2, limit = 5)['bids'][0][0])
                p3_depth = client.depth(pair_3, limit = 5)
                bid_p3 = float(p3_depth['bids'][0][0])
                p3_bid_quant = float(p3_depth['bids'][0][1])
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                route_gain = ((ask_p1 - pair_1_pip) / ((bid_p2 + pair_2_pip)) * (bid_p3))
                calc_done = True
        return (route_gain, ask_p1, bid_p2, bid_p3, p3_bid_quant) 
开发者ID:Reidmcc,项目名称:Binance-bot,代码行数:23,代码来源:data_checks.py

示例14: route_check_alt_last_lastprice

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def route_check_alt_last_lastprice(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip):
        route_gain = -1
        calc_done = False
        t_1_price = -1
        t_2_price = -1
        t_3_price = -1
        while calc_done == False:
            try:
                prices = client.allPrices()
                for p in prices:
                    symbol = p['symbol']
                    if symbol == pair_1:
                        t_1_price =  float(p['price'])
                    if symbol == pair_2:
                        t_2_price =  float(p['price'])
                    if symbol == pair_3:
                        t_3_price =  float(p['price'])
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                route_gain = (t_1_price / (t_2_price) * t_3_price)
                calc_done = True

        return route_gain 
开发者ID:Reidmcc,项目名称:Binance-bot,代码行数:27,代码来源:data_checks.py

示例15: route_check_t3_ask_oth_lastprice

# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import HTTPException [as 别名]
def route_check_t3_ask_oth_lastprice(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip):
        route_gain = -1
        ask_p3 = -1
        calc_done = False
        t_1_price = -1
        t_2_price = -1
        while calc_done == False:
            try:
                prices = client.allPrices()
                for p in prices:
                    symbol = p['symbol']
                    if symbol == pair_1:
                        t_1_price = float(p['price']) - pair_1_pip
                    if symbol == pair_2:
                        t_2_price = float(p['price']) + pair_2_pip

                ask_p3 = float(client.depth(pair_3, limit=5)['asks'][0][0]) - pair_3_pip
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                route_gain = t_1_price / t_2_price * ask_p3
                calc_done = True

        return (route_gain, t_1_price, t_2_price, ask_p3) 
开发者ID:Reidmcc,项目名称:Binance-bot,代码行数:27,代码来源:data_checks.py


注:本文中的http.client.HTTPException方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。