Пример #1
0
def getHistoricalIntradayByMinute(ticker, day=None):
    historicalIntradayData = {}
    try:
        historicalIntradayData = get_historical_intraday(ticker, day)
    except Exception as ex:
        Logger.error('Failed querying IEX historical intraday data for {}'.format(ticker))
    return historicalIntradayData
Пример #2
0
    def get(self, endpoint):
        """
        :param endpoint: REST API endpoint to GET
        :returns: Str response. If error, returns None
        """
        try:

            res = requests.get(f"{self.base_url}/{endpoint}",
                               auth=self.auth,
                               headers=self.headers)
            '''
            Return the response text if everything goes correctly
            and the server response with 200 HTTP code.
            '''
            if res.status_code == 200:
                return res.text

            if res.status_code != 200:
                Logger.error("ERROR: Status code is {res.status_code}."
                             f"Response: {res.text}")
                return None

        except requests.exceptions.RequestException as e:
            Logger.error(f"Request failed: {e}")
            return None
Пример #3
0
    def get_q_string(self, query_string):
        """
        :param query_string: query string in dict, where key is LHS, and value
            is RHS for each query string pair
        :returns: Str response. If error, returns None
        """
        q_string = '?'
        for k, v in query_string.items():
            q_string += f"{quote(k)}={quote(v)}&"
        try:
            res = requests.get(f"{self.base_url}{q_string}")
            '''
            Return the response text if everything goes correctly
            and the server response with 200 HTTP code.
            '''
            if res.status_code == 200:
                return res.text
            if res.status_code != 200:
                Logger.error(f"Status code is {res.status_code}."
                             f"Response: {res.text}")
                return None

        except requests.exceptions.RequestException as e:
            Logger.error(f"Request failed: {e}")
            return None
Пример #4
0
 def worker(self, ip):
     hosts = self.config['hosts'].split(',')
     host_records = self._get_records(self.zones[self.zone])
     put_url = f"zones/{self.zones[self.zone]}/records"
     for host in hosts:
         if host == '@':
             host = self.zone
         else:
             host += '.' + self.zone
         if not host.endswith('.'):
             host += '.'
         if host not in host_records:
             Logger.warning(f"Attempted to update host '{host}' "
                            "that is not found under this account!")
             continue
         data = {
             "type": "A",
             "name": host,
             "content": ip,
             "ttl": self.ttl,
         }
         ret = self.rest.put(f"{put_url}/{host_records[host]}", data)
         if not ret:
             Logger.error(f"Unable to update host record for '{host}' at "
                          "zone '{self.zone}'")
             continue
Пример #5
0
    def getPublic():

        try:
            response = requests.get("https://ipinfo.io")
            if response.status_code == 200:
                ip = response.json()
                return ip['ip']
        except requests.exceptions.RequestException as e:
            Logger.error("Unable to get public IP address!")
            Logger.error(e)
            sys, exit(1)
Пример #6
0
    def create_path_if_not_exists(path):
        logger = Logger().getLogger()

        p = Path(path)

        if not p.exists():
            try:
                p.mkdir(parents=True, exist_ok=True)
            except Exception as ex:
                logger.error("Creation of the directory %s failed" % path)
                logger.error(ex)
            else:
                logger.info("Successfully created the directory %s" % path)
Пример #7
0
    def get_json(self, endpoint):
        """
        :param endpoint: REST API endpoint to GET
        :returns: dict representing json response. If error, returns None
        """
        resp = self.get(endpoint)
        json_resp = None

        try:
            json_resp = json.loads(resp)
        except json.JSONDecodeError:
            Logger.error(f"Invalid response to request at endpoint {endpoint}")
        return json_resp
Пример #8
0
 def worker(self, ip):
     hosts = self.config['hosts'].split(',')
     for host in hosts:
         if host == '@':
             host = self.zone
         else:
             host += '.' + self.zone
         if host not in self._zones:
             Logger.warning(f"Attempted to update host '{host}' "
                            "that is not found under this account!")
             continue
         ret = HttpProvider.get(self.update_url + host)
         if not ret:
             Logger.error("Unable to update host record "
                          f"for '{host}' at zone '{self.zone}'")
             continue
Пример #9
0
 def handle_error(e: Exception):
     error_number = ErrorHandler.get_error_number(str(e))
     error_message = str(e)
     if type(e).__name__ == 'ValidationError':
         error_number = 400
     Logger.error(
         message={
             'type': type(e).__name__,
             'message': error_message,
             'traceback': traceback.format_exc()
         })
     return {
         'error': {
             'code': error_number,
             'type': type(e).__name__,
             'description': error_message,
         }
     }, error_number
Пример #10
0
 def put(self, endpoint, data):
     """
     :param endpoint: REST API endpoint to GET
     :param data: dict of data to send (as json)
     :returns: True if succesful, else False
     """
     try:
         res = requests.put(f"{self.base_url}/{endpoint}",
                            headers=self.headers,
                            auth=self.auth,
                            data=json.dumps(data))
         if res.status_code != 200:
             Logger.error(f"Status code is {res.status_code}. "
                          f"Response: {res.text}")
             return False
     except requests.exceptions.RequestException as e:
         Logger.error(f"Request failed: {e}")
         return False
     return True
class RiotExtractor:
    def __init__(self):
        self.logger = Logger().getLogger()

    def get_data_from_api(self, endpoint="", headers="", api_name=""):
        try:
            self.logger.info("getting {}'s data from {} with headers {}".format(api_name, endpoint, headers))

            response = requests.request("GET", endpoint, headers=headers)

            if response.status_code != 200:
                raise ValueError('API dont work as expected, getting status code {} and error {}'
                                 .format(response.status_code, response.json()))

            return response.json()

        except Exception as ex:
            self.logger.error("getting {}'s data from {} with headers {}".format(api_name, endpoint, headers))
            self.logger.error('Error: {}'.format(ex))
Пример #12
0
    def post(self, endpoint, data):
        try:

            Response = requests.post(f"{self.base_url}/{endpoint}",
                                     headers=self.headers,
                                     auth=self.auth,
                                     data=json.dumps(data))
            '''
            If something goes wrong we'll get status code that
            not eq to 200
            '''
            if Response.status_code != 200:
                Logger.error(f"Response code {Response.status_code}")
                return False

        except requests.exceptions.RequestException as e:
            Logger.error(f"Request failed : {e}")
            return False
        finally:
            return True
class CommandLineArgs(Singleton):
    def __init__(self):
        self.get_args()
        self.logger = Logger().getLogger()

    def get_args(self):
        try:
            ap = argparse.ArgumentParser()

            ap.add_argument("--dest",
                            required=True,
                            default="",
                            help="path that script will put the api files")
            ap.add_argument("--dest_format",
                            default="json",
                            required=False,
                            help="file format to output")
            ap.add_argument("--master_leagues_endpoint",
                            default="",
                            required=False,
                            help="endpoint to access master leagues api")
            ap.add_argument("--champion_mastery_endpoint",
                            default="",
                            required=False,
                            help="endpoint to access champion mastery api")
            ap.add_argument("--champion_mastery_summoner_id",
                            default="",
                            required=False,
                            help="summoner id to filter api by summoner")
            ap.add_argument("--access_key",
                            required=True,
                            default="",
                            help="access key to access API")

            args = ap.parse_args()

            return args

        except Exception as ex:
            self.logger.error("can't get command line arguments")
            self.logger.error('Error: {}'.format(ex))
Пример #14
0
    def get(url):
        """
        :param url: url to HTTP GET
        :returns: Str response. If error, returns None
        """
        try:
            res = requests.get(url)
            '''
            Return the response text if everything goes correctly
            and the server response with 200 HTTP code.
            '''
            if res.status_code == 200:
                return res.text
            if res.status_code != 200:
                Logger.error(f"Status code is {res.status_code}."
                             f"Response: {res.text}")
                return None

        except requests.exceptions.RequestException as e:
            Logger.error(f"Request failed: {e}")
            return None
class RiotChampionPointsXChampionID:
    def __init__(self, data):
        self.logger = Logger().getLogger()
        self.data = data
        self.chart = self.plot_chart()

    def plot_chart(self):
        try:
            self.logger.info("Plotting chart")

            # filter only championId and championPoints columns
            dataframe = pd.DataFrame(
                self.data)[['championId', 'championPoints']]
            dataframe['championId'] = dataframe['championId'].astype(str)

            # sort values to get the top 10 values descending
            dataframe = dataframe.sort_values(by=['championPoints'],
                                              ascending=False).head(10)

            chart = pygal.Bar(x_title='champion ID', y_title='champion Points')
            chart.title = 'Top 10 championPoints by championId'

            # adding data into chart object
            for index, row in dataframe.iterrows():
                chart.add('id ' + row['championId'], row['championPoints'])

            self.logger.info("chart plotted")

            return chart

        except Exception as ex:
            self.logger.error("can't plot chart")
            self.logger.error('Error: {}'.format(ex))

    def save_chart_as_image(self, path=""):
        try:
            path = Utils.remove_slash_in_end_of_string(path)
            path_full_png = path + '/champion_points_champion_id.png'
            path_full_svg = path + '/champion_points_champion_id.svg'

            self.chart.render_to_file(path_full_svg)
            self.chart.render_to_png(filename=path_full_png)

            self.logger.info("chart saved at {} as svg".format(path_full_svg))
            self.logger.info("chart saved at {} as png".format(path_full_png))

        except Exception as ex:
            self.logger.error("can't save chart in {}".format(path))
            self.logger.error('Error: {}'.format(ex))
Пример #16
0
class Writer:
    def __init__(self):
        self.logger = Logger().getLogger()

    def write_json(self, data="", file_name="data.json", output_path=""):
        try:

            output_path = Utils.remove_slash_in_end_of_string(output_path)
            full_output_path = file_name + '.json' if output_path == "" else '{}/{}.json'.format(
                output_path, file_name)

            if data is not None:
                self.logger.info("Writing {} in json format".format(file_name))

                with open(full_output_path, 'w') as f:
                    json.dump(data, f)
            else:
                raise ValueError(
                    'file data is none, cannot write in file system')

        except Exception as ex:
            self.logger.error("can't write json in file system")
            self.logger.error('Error: {}'.format(ex))
Пример #17
0
    def _load_sections(self, file):
        """
        Inspired by diffoscope/comparator/elf.py ElfContainer
        """
        self._analyzer = ElfAnalyzer(file, self.config)

        # Get all the sections in this file to pass them to the analyzer
        cmd = [
            "readelf",
            "--wide",
            "--section-headers",
            file,
        ]
        output = subprocess.check_output(cmd,
                                         shell=False,
                                         stderr=subprocess.DEVNULL)

        try:
            output = output.decode("utf-8").split("\n")

            # Entries of readelf --section-headers have the following columns:
            # [Nr]  Name  Type  Address  Off  Size  ES  Flg  Lk  Inf  Al
            for line in output:
                if not self.elf_section_regex.match(line):
                    continue

                # Strip number column because there may be spaces in the brakets
                line = line.split("]", 1)[1].split()
                name, type, flags = line[0], line[1], line[6]

                if self._should_skip_section(name, type):
                    continue

                self._analyzer.add_section(name, flags)
        except Exception as e:
            Logger.error("error in _load_sections: {}".format(e))
Пример #18
0
    for zone in config.sections():

        '''
        We have to exclude the global section of the
        configuration file from parsing as a zone
        '''
        if zone == 'global':
            continue

        provider = config[zone].get('provider')


        try:
            module = __import__("plugins." + provider, fromlist=[provider])
        except ImportError:
            Logger.error(f"Unknown provider in zone '{zone}': {provider}")

        zones[zone] = getattr(module, provider)(zone, config[zone])

    '''
    Get the update interval from the configuration file or
    fallback to default interval 300 seconds
    '''
    update_interval_sec = config['global'].get('interval')
    if not update_interval_sec:
        update_interval_sec = 300
    
    ip = None
    while True:
        new_ip = IP.getPublic()
        if not ip or ip != new_ip:
Пример #19
0
# initialize.PyfyApp().run()
print("does this run now?")
if args.symbol:
    symbol = args.symbol
    Logger.trace("Symbol passed in: {}".format(args.symbol))
    quote = iex.getQuote(symbol)
    Logger.trace("Queried Symbol Quote is ...")
    Logger.trace(quote)
    if (quote != None):
        Logger.info('Current Price: {}'.format(quote.get('latestPrice')))
        Logger.info('PE Ratio: {}'.format(quote.get('peRatio')))
        Logger.info('52-Week High: {}'.format(quote.get('week52High')))
        Logger.info('52-Week Low: {}'.format(quote.get('week52Low')))
    else:
        Logger.error(
            'Could not print symbol information for {}'.format(symbol))

if args.price_dates:
    parsedDate = dateparser.parse(args.graphprice)
    if (parsedDate.weekday() < 5):
        graphs.byMinuteIntradayLineGraph(symbol, 'average', parsedDate)
    else:
        Logger.all('Provided date is not a weekday, the day was: ' +
                   parsedDate.strftime('%A'))

if args.volume_dates:
    if (len(args.volume_dates) > 1):
        parsedStartDate = dateparser.parse(args.volume_dates[0])
        parsedEndDate = dateparser.parse(args.volume_dates[1])
        graphs.valueOverRangeLineGraph(symbol, 'volume', parsedStartDate,
                                       parsedEndDate)
Пример #20
0

def populate_commands_v2():
    cli.add_command(antiddos_v2, name="antiddos")
    cli.add_command(cloud_v2, name="cloud")
    cli.add_command(customer_v2, name="customer")
    cli.add_command(ipaddr_v2, name="ipaddr")


def populate_commands_v3():
    pass


if config.get("CB_API_VERSION") == "v3":
    populate_commands_v3()
    log.error("Access to APIv3 is not yet implemented.")
else:
    populate_commands_v2()


@click.command(
    name="version",
    help="Checks the local version against the latest remote at GitHub")
def version():
    check_version()


cli.add_command(version)

if __name__ == "__main__":
    cli()