Esempio n. 1
0
def get_prices_from_api(request_uri: str) -> dict:
    """using the provided URI, request data from the Octopus API and return a JSON object.
    Try to handle errors gracefully with retries when appropriate."""

    # Try to handle issues with the API - rare but do happen, using an
    # exponential sleep time up to 2**14 (16384) seconds, approx 4.5 hours.
    # We will keep trying for over 9 hours and then give up.

    print('Requesting Agile prices from Octopus API...')
    retry_count = 0
    my_repr = Repr()
    my_repr.maxstring = 80  # let's avoid truncating our error messages too much

    while retry_count <= MAX_RETRIES:

        if retry_count == MAX_RETRIES:
            raise SystemExit('API retry limit exceeded.')

        try:
            success = False
            response = requests.get(request_uri, timeout=5)
            response.raise_for_status()
            if response.status_code // 100 == 2:
                success = True
                return response.json()

        except requests.exceptions.HTTPError as error:
            print(('API HTTP error ' + str(response.status_code) +
                   ',retrying in ' + str(2**retry_count) + 's'))
            time.sleep(2**retry_count)
            retry_count += 1

        except requests.exceptions.ConnectionError as error:
            print(('API connection error: ' + my_repr.repr(str(error)) +
                   ', retrying in ' + str(2**retry_count) + 's'))
            time.sleep(2**retry_count)
            retry_count += 1

        except requests.exceptions.Timeout:
            print('API request timeout, retrying in ' + str(2**retry_count) +
                  's')
            time.sleep(2**retry_count)
            retry_count += 1

        except requests.exceptions.RequestException as error:
            raise SystemExit('API Request error: ' + str(error)) from error

        if success:
            print('API request successful, status ' +
                  str(response.status_code) + '.')
            break
Esempio n. 2
0
def safe_max(*args):
    iterable = args[0] if len(args) == 1 else args
    return max((value for value in iterable if value is not None),
               default=None)


def is_ipython():
    try:
        __IPYTHON__
        return True
    except NameError:
        return False


compact_repr = Repr()
compact_repr.maxstring = 80
compact_repr.maxother = 80
compact_repr = compact_repr.repr


class OmittedType:
    __slots__ = ()

    def __repr__(self):
        return "<...>"


Omitted = OmittedType()


class MissingType:
Esempio n. 3
0
from functools import wraps
from reprlib import Repr
import inspect
from flask import request, g
from flask_logger_decorator.config import config
from flask_logger_decorator.logger import debug

__r = Repr()
__r.maxarray = __r.maxarray * 10
__r.maxdict = __r.maxdict * 10
__r.maxstring = __r.maxstring * 10


def request_tracing(fn):
    """
    A decorator to tracing request.
    """
    @wraps(fn)
    def wrapper(*args, **kwargs):
        tracing_request(fn, *args, **kwargs)
        return fn(*args, **kwargs)

    return wrapper


def tracing_request(fn, *args, **kwargs):
    function_args = ' '.join(_get_fn_args(fn, *args, **kwargs))
    trace_info = ' '.join(_get_fn_extra_info(fn))
    func_msg = 'func_name:{} func_args:{} trace_info:{}'.format(
        fn.__name__, function_args, trace_info)
    request_msg = get_request_trace_info()
Esempio n. 4
0
import bdb
import re

try:
    from reprlib import Repr
except ImportError:
    from reprlib import Repr

from pycopia import IO
from pycopia import UI
from pycopia import CLI

# Create a custom safe Repr instance and increase its maxstring.
# The default of 30 truncates error messages too easily.
_repr = Repr()
_repr.maxstring = 200
_repr.maxother = 50
_saferepr = _repr.repr

DebuggerQuit = bdb.BdbQuit

def find_function(funcname, filename):
    cre = re.compile(r'def\s+%s\s*[(]' % funcname)
    try:
        fp = open(filename)
    except IOError:
        return None
    # consumer of this info expects the first line to be 1
    lineno = 1
    answer = None
    while 1:
Esempio n. 5
0
# - popup menu
# - support partial or total redisplay
# - more doc strings
# - tooltips

# object browser

# XXX TO DO:
# - for classes/modules, add "open source" to object browser

from .TreeWidget import TreeItem, TreeNode, ScrolledCanvas

from reprlib import Repr

myrepr = Repr()
myrepr.maxstring = 100
myrepr.maxother = 100


class ObjectTreeItem(TreeItem):
    def __init__(self, labeltext, object, setfunction=None):
        self.labeltext = labeltext
        self.object = object
        self.setfunction = setfunction

    def GetLabelText(self):
        return self.labeltext

    def GetText(self):
        return myrepr.repr(self.object)
Esempio n. 6
0
# XXX TO DO:
# - popup menu
# - support partial or total redisplay
# - more doc strings
# - tooltips

# object browser

# XXX TO DO:
# - for classes/modules, add "open source" to object browser
from reprlib import Repr

from idlelib.tree import TreeItem, TreeNode, ScrolledCanvas

myrepr = Repr()
myrepr.maxstring = 100
myrepr.maxother = 100


class ObjectTreeItem(TreeItem):
    def __init__(self, labeltext, object, setfunction=None):
        self.labeltext = labeltext
        self.object = object
        self.setfunction = setfunction

    def GetLabelText(self):
        return self.labeltext

    def GetText(self):
        return myrepr.repr(self.object)
Esempio n. 7
0
from pprintpp import pformat as pf, pprint as pp
from reprlib import Repr
import shutil
import sys
from textwrap import indent, wrap

import sqlparse as sp

from tlbx.object_utils import get_class_vars, get_caller


logging.basicConfig(format="%(message)s")


_repr = Repr()
_repr.maxstring = 60
_repr.maxother = 20
_repr.maxlist = 5
_repr.maxtuple = 5
_repr.maxset = 5
repr = _repr.repr

DEFAULT_TERM_WIDTH = 80


class FontSpecialChars:
    ENDC = "\033[0m"


class FontColors:
    BLACK = "\033[30m"
Esempio n. 8
0
standard_library.install_aliases()

from builtins import open

import inspect
import smtplib
import sys
import string
import tempfile
import traceback
import xmlrpc.client

from reprlib import Repr

_repr = Repr()
_repr.maxstring = 3000
_saferepr = _repr.repr


def printTraceBack(tb=None, output=sys.stderr, exc_type=None, exc_msg=None):
    if isinstance(output, str):
        output = open(output, 'w')

    exc_info = sys.exc_info()
    if tb is None:
        tb = exc_info[2]

    if exc_type is None:
        exc_type = exc_info[0]

    if exc_msg is None: