Python http.client.HTTPException() Examples

The following are 30 code examples of http.client.HTTPException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module http.client , or try the search function .
Example #1
Source File: main.py    From fulfillment-translate-python with Apache License 2.0 6 votes vote down vote up
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 
Example #2
Source File: test_ucn.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #3
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #4
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #6
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #7
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #8
Source File: mult_arbit.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: mult_arbit.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
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} 
Example #10
Source File: create_org_widget.py    From parsec-cloud with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #11
Source File: test_ucn.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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) 
Example #12
Source File: IronDefense.py    From content with MIT License 6 votes vote down vote up
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!' 
Example #13
Source File: client.py    From Blender-Metaverse-Addon with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #14
Source File: IronDefense.py    From content with MIT License 6 votes vote down vote up
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!' 
Example #15
Source File: AuroraAPI.py    From aurora-sdk-mac with Apache License 2.0 6 votes vote down vote up
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() 
Example #16
Source File: IronDefense.py    From content with MIT License 6 votes vote down vote up
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!' 
Example #17
Source File: test_ucn.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #18
Source File: multibytecodec_support.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        try:
            self.open_mapping_file().close() # test it to report the error early
        except (OSError, HTTPException):
            self.skipTest("Could not retrieve "+self.mapfileurl) 
Example #19
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 5 votes vote down vote up
def route_check_altfirst_t1_bid_oth_lastprice(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip):
        route_gain = -1
        bid_p1 = -1
        t_2_price = -1
        t_3_price = -1
        calc_done = False
        while calc_done == False:
            try:
                prices = client.allPrices()
                for p in prices:
                    symbol = p['symbol']
                    if symbol == pair_2:
                        t_2_price = float(p['price']) + pair_2_pip
                    if symbol == pair_3:
                        t_3_price = float(p['price']) - pair_3_pip

                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)) * (t_2_price - pair_2_pip)  / (t_3_price + pair_3_pip)
                calc_done = True

        return (route_gain, bid_p1, t_2_price, t_3_price)


    # skit_opt_ETH = dc.route_check_altfirst('XLMBNB', 'XLMETH', 'BNBETH', 1E-5, 1E-8, 1E-6)
    # print(skit_opt_ETH) 
Example #20
Source File: comments.py    From instagram-livestream-downloader with MIT License 5 votes vote down vote up
def get_live(self, first_comment_created_at=0):
        comments_collected = self.comments
        commenter_ids = self.user_config.commenters or []

        before_count = len(comments_collected)
        try:
            comments_res = self.api.broadcast_comments(
                self.broadcast['id'], last_comment_ts=first_comment_created_at)
            comments = comments_res.get('comments', [])
            first_comment_created_at = (
                comments[0]['created_at_utc'] if comments else int(time.time() - 5))
            # save comment if it's in list of commenter IDs or if user is verified
            comments_collected.extend(
                list(filter(
                    lambda x: (str(x['user_id']) in commenter_ids or
                               x['user']['username'] in commenter_ids or
                               x['user']['is_verified']),
                    comments)))
            after_count = len(comments_collected)
            if after_count > before_count:
                # save intermediately to avoid losing comments due to unexpected errors
                broadcast = self.broadcast.copy()
                broadcast.pop('segments', None)     # save space
                broadcast['comments'] = comments_collected
                with open(self.destination_file, 'w') as outfile:
                    json.dump(broadcast, outfile, indent=2)
            self.comments = comments_collected

        except (SSLError, timeout, URLError, HTTPException, SocketError) as e:
            # Probably transient network error, ignore and continue
            self.logger.warning('Comment collection error: %s' % e)
        except ClientError as e:
            if e.code == 500:
                self.logger.warning('Comment collection ClientError: %d %s' % (e.code, e.error_response))
            elif e.code == 400 and not e.msg:   # 400 error fail but no error message
                self.logger.warning('Comment collection ClientError: %d %s' % (e.code, e.error_response))
            else:
                raise e
        finally:
            time.sleep(4)
        return first_comment_created_at 
Example #21
Source File: http.py    From mirakuru with GNU Lesser General Public License v3.0 5 votes vote down vote up
def after_start_check(self) -> bool:
        """Check if defined URL returns expected status to a check request."""
        conn = HTTPConnection(self.host, self.port)
        try:
            body = urlencode(self.payload) if self.payload else None
            headers = self.headers if self.headers else {}
            conn.request(
                self.method,
                self.url.path,
                body,
                headers,
            )
            try:
                status = str(conn.getresponse().status)
            finally:
                conn.close()

            if status == self.status or self.status_re.match(status):
                return True
            return False

        except (HTTPException, socket.timeout, socket.error) as ex:
            LOG.debug(
                "Encounter %s while trying to check if service has started.",
                ex
            )
            return False 
Example #22
Source File: httpclient.py    From opsbro with MIT License 5 votes vote down vote up
def get_http_exceptions():
    global _HTTP_EXCEPTIONS
    if _HTTP_EXCEPTIONS is not None:
        return _HTTP_EXCEPTIONS
    HTTP_EXCEPTIONS = (HTTPError, URLError, SocketError, HTTPException)
    _HTTP_EXCEPTIONS = HTTP_EXCEPTIONS
    return _HTTP_EXCEPTIONS 
Example #23
Source File: SimpleRequestsPy3.py    From Discord-Scraper with The Unlicense 5 votes vote down vote up
def get_response(self, url):
        """Grab the http.client response from a request.

        :param url: The URL of the page.
        """

        # Enclose our file gathering process in a try-catch condition.
        try:

            # Split our URL into the three distinct portions.
            urlsplices = url_split(url)

            # Make a connection to the URL.
            conn = HTTPSConnection(urlsplices.domain) if urlsplices.scheme == 'https' \
                else HTTPConnection(urlsplices.domain)

            # Make a simple request.
            conn.request('GET', urlsplices.path, headers=self.headers)

            # Gather our response.
            resp = conn.getresponse()

            # Return our data if we receive an HTTP 2XX or 3XX response code.
            if 199 < resp.status < 400:
                return resp

            # Otherwise raise an exception for anything else.
            raise HTTPException(f'HTTP {resp.code} {resp.reason}')

        except HTTPException as httpex:

            # Return an error message if we catch an exception.
            error(f'Unknown exception: {httpex}')
            return None 
Example #24
Source File: test_challenges.py    From laravan with MIT License 5 votes vote down vote up
def get_status(host, path, file):
    try:
        conn = HTTPConnection(host)
        conn.request('HEAD', '/{0}/{1}'.format(path, file))
        res = conn.getresponse()
    except (HTTPException, socket.timeout, socket.error):
        return 0
    else:
        return res.status 
Example #25
Source File: test_challenges.py    From trellis with MIT License 5 votes vote down vote up
def get_status(host, path, file):
    try:
        conn = HTTPConnection(host)
        conn.request('HEAD', '/{0}/{1}'.format(path, file))
        res = conn.getresponse()
    except (HTTPException, socket.timeout, socket.error):
        return 0
    else:
        return res.status 
Example #26
Source File: comments.py    From PyInstaLive with MIT License 5 votes vote down vote up
def get_live(self, first_comment_created_at=0):
        comments_collected = self.comments

        before_count = len(comments_collected)
        try:
            comments_res = self.api.broadcast_comments(
                self.broadcast.get('id'), last_comment_ts=first_comment_created_at)
            comments = comments_res.get('comments', [])
            first_comment_created_at = (
                comments[0]['created_at_utc'] if comments else int(time.time() - 5))
            comments_collected.extend(comments)
            after_count = len(comments_collected)
            if after_count > before_count:
                broadcast = self.broadcast.copy()
                broadcast.pop('segments', None)  # save space
                broadcast['comments'] = comments_collected
                with open(self.destination_file, 'w') as outfile:
                    json.dump(broadcast, outfile, indent=2)
            self.comments = comments_collected

        except (SSLError, timeout, URLError, HTTPException, SocketError) as e:
            logger.warn('Comment downloading error: %s' % e)
        except ClientError as e:
            if e.code == 500:
                logger.warn('Comment downloading ClientError: %d %s' %
                            (e.code, e.error_response))
            elif e.code == 400 and not e.msg:
                logger.warn('Comment downloading ClientError: %d %s' %
                            (e.code, e.error_response))
            else:
                raise e
        finally:
            try:
                time.sleep(4)
            except KeyboardInterrupt:
                return first_comment_created_at
        return first_comment_created_at 
Example #27
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 5 votes vote down vote up
def get_high_bid(self, pair):
        bid = -1
        got_bid = False
        while got_bid == False:
            try:
                bid = client.depth(pair, 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:
                got_bid = True
        return bid 
Example #28
Source File: test_httplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_too_many_headers(self):
        headers = '\r\n'.join('Header%d: foo' % i
                              for i in range(client._MAXHEADERS + 1)) + '\r\n'
        text = ('HTTP/1.1 200 OK\r\n' + headers)
        s = FakeSocket(text)
        r = client.HTTPResponse(s)
        self.assertRaisesRegex(client.HTTPException,
                               r"got more than \d+ headers", r.begin) 
Example #29
Source File: test_normalization.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_main(self):
        # Hit the exception early
        try:
            testdata = open_urlresource(TESTDATAURL, encoding="utf-8",
                                        check=check_version)
        except PermissionError:
            self.skipTest("Permission error when downloading %s "
                          "into the test data directory" % TESTDATAURL)
        except (OSError, HTTPException):
            self.fail("Could not retrieve %s" % TESTDATAURL)

        with testdata:
            self.run_normalization_tests(testdata) 
Example #30
Source File: pushalot.py    From mqttwarn with Eclipse Public License 2.0 5 votes vote down vote up
def plugin(srv, item):
    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)

    apikey = item.addrs[0]

    title = item.get('title', srv.SCRIPTNAME)
    message = item.message

    http_handler = HTTPSConnection("pushalot.com")

    data = {'AuthorizationToken': apikey,
            'Title': title.encode('utf-8'),
            'Body': message.encode('utf-8')
            }

    try:
        http_handler.request("POST", "/api/sendmessage",
                             headers={'Content-type': "application/x-www-form-urlencoded"},
                             body=urlencode(data)
                             )
    except (SSLError, HTTPException) as e:
        srv.logging.warn("Pushalot notification failed: %s" % str(e))
        return False

    response = http_handler.getresponse()

    srv.logging.debug("Reponse: %s, %s" % (response.status, response.reason))

    return True