def get_current_nfl_week(config: AppConfigParser, dev_offline):

    api_url = "https://bet.rotoworld.com/api/nfl/calendar/game_count"

    current_nfl_week = config.getint("Settings", "current_week")

    if not dev_offline:
        logger.debug("Retrieving current NFL week from the Fox Sports API.")

        try:
            nfl_weekly_info = requests.get(api_url).json()
            current_nfl_week = nfl_weekly_info.get("period")
        except (KeyError, ValueError) as e:
            logger.warning(
                "Unable to retrieve current NFL week. Defaulting to value set in \"config.ini\"."
            )
            logger.debug(e)

    else:
        logger.debug(
            "The Fantasy Football Metrics Weekly Report app is being run in offline mode. "
            "The current NFL week will default to the value set in \"config.ini\"."
        )

    return current_nfl_week
def get_valid_config(config_file="config.ini"):
    config = AppConfigParser()

    root_directory = Path(__file__).parent.parent

    config_file_path = root_directory / Path(config_file)

    # set local config file (check for existence and access, stop app if does not exist or cannot access)
    if config_file_path.is_file():
        if os.access(config_file_path, mode=os.R_OK):
            logger.debug(
                "Configuration file \"config.ini\" available. Running Fantasy Football Metrics Weekly Report app..."
            )
            config_template = AppConfigParser()
            config_template.read(root_directory / "EXAMPLE-config.ini")
            config.read(config_file_path)

            if not set(config_template.sections()).issubset(
                    set(config.sections())):
                missing_sections = []
                for section in config_template.sections():
                    if section not in config.sections():
                        missing_sections.append(section)

                logger.error(
                    "Your local \"config.ini\" file is missing the following sections:\n\n{0}\n\n"
                    "Please update your \"config.ini\" with the above sections from \"EXAMPLE-config.ini\" "
                    "and try again.".format(", ".join(missing_sections)))
                sys.exit("...run aborted.")
            else:
                logger.debug(
                    "All required local \"config.ini\" sections present.")

            config_map = defaultdict(set)
            for section in config.sections():
                section_keys = set()
                for (k, v) in config.items(section):
                    section_keys.add(k)
                config_map[section] = section_keys

            missing_keys_map = defaultdict(set)
            for section in config_template.sections():
                if section in config.sections():
                    for (k, v) in config_template.items(section):
                        if k not in config_map.get(section):
                            missing_keys_map[section].add(k)

            if missing_keys_map:
                missing_keys_str = ""
                for section, keys in missing_keys_map.items():
                    missing_keys_str += "Section: {0}\n".format(section)
                    for key in keys:
                        missing_keys_str += "  {0}\n".format(key)
                    missing_keys_str += "\n"
                missing_keys_str = missing_keys_str.strip()

                logger.error(
                    "Your local \"config.ini\" file is  missing the following keys (from their respective "
                    "sections):\n\n{0}\n\nPlease update your \"config.ini\" with the above keys from "
                    "\"EXAMPLE-config.ini\" and try again.".format(
                        missing_keys_str))

                sys.exit("...run aborted.")
            else:
                logger.debug("All required local \"config.ini\" keys present.")

            return config
        else:
            logger.error(
                "Unable to access configuration file \"config.ini\". Please check that file permissions are properly set."
            )
            sys.exit("...run aborted.")
    else:
        logger.debug("Configuration file \"config.ini\" not found.")
        create_config = input(
            "{2}Configuration file \"config.ini\" not found. {1}Do you wish to create one? {0}({1}y{0}/{2}n{0}) -> {3}"
            .format(Fore.YELLOW, Fore.GREEN, Fore.RED, Style.RESET_ALL))
        if create_config == "y":
            return create_config_from_template(config, root_directory,
                                               config_file_path)
        if create_config == "n":
            logger.error(
                "Configuration file \"config.ini\" not found. Please make sure that it exists in project root directory."
            )
            sys.exit("...run aborted.")
        else:
            logger.warning("Please only select \"y\" or \"n\".")
            time.sleep(0.25)
            get_valid_config(config_file)
def create_config_from_template(config: AppConfigParser,
                                root_directory,
                                config_file_path,
                                platform=None,
                                league_id=None,
                                season=None,
                                current_week=None):
    logger.debug("Creating \"config.ini\" file from template.")
    config_template_file = os.path.join(root_directory, "EXAMPLE-config.ini")
    config_file_path = shutil.copyfile(config_template_file, config_file_path)

    config.read(config_file_path)

    if not platform:
        logger.debug("Getting ")
        platform = input(
            "{0}For which fantasy football platform are you generating a report? ({1}) -> {2}"
            .format(Fore.GREEN, "/".join(supported_platforms),
                    Style.RESET_ALL))
        if platform not in supported_platforms:
            logger.warning(
                "Please only select one of the following platforms: {0}".
                format(", or ".join([
                    ", ".join(supported_platforms[:-1]),
                    supported_platforms[-1]
                ])))
            time.sleep(0.25)
            config = create_config_from_template(config, root_directory,
                                                 config_file_path)
        logger.debug(
            "Retrieved fantasy football platform for \"config.ini\": {0}".
            format(platform))

    config.set("Settings", "platform", platform)

    if not league_id:
        league_id = input("{0}What is your league ID? -> {1}".format(
            Fore.GREEN, Style.RESET_ALL))
        logger.debug(
            "Retrieved fantasy football league ID for \"config.ini\": {0}".
            format(league_id))

    config.set("Settings", "league_id", league_id)

    if not season:
        season = input(
            "{0}For which NFL season (starting year of season) are you generating reports? -> {1}"
            .format(Fore.GREEN, Style.RESET_ALL))
        try:
            if int(season) > current_year:
                logger.warning(
                    "This report cannot predict the future. Please only input a current or past NFL season."
                )
                time.sleep(0.25)
                config = create_config_from_template(config,
                                                     root_directory,
                                                     config_file_path,
                                                     platform=platform,
                                                     league_id=league_id)
            elif int(season) < 2019 and platform == "espn":
                logger.warning(
                    "ESPN leagues prior to 2019 are not supported. Please select a later NFL season."
                )
                time.sleep(0.25)
                config = create_config_from_template(config,
                                                     root_directory,
                                                     config_file_path,
                                                     platform=platform,
                                                     league_id=league_id)

        except ValueError:
            logger.warning("You must input a valid year in the format YYYY.")
            time.sleep(0.25)
            config = create_config_from_template(config,
                                                 root_directory,
                                                 config_file_path,
                                                 platform=platform,
                                                 league_id=league_id)
        logger.debug(
            "Retrieved fantasy football season for \"config.ini\": {0}".format(
                season))

    config.set("Settings", "season", season)

    if not current_week:
        current_week = input(
            "{0}What is the current week of the NFL season? (week following the last complete week) -> {1}"
            .format(Fore.GREEN, Style.RESET_ALL))
        try:
            if int(current_week) < 0 or int(current_week) > 17:
                logger.warning(
                    "Week {0} is not a valid NFL week. Please select a week from 1 to 17."
                    .format(current_week))
                time.sleep(0.25)
                config = create_config_from_template(config,
                                                     root_directory,
                                                     config_file_path,
                                                     platform=platform,
                                                     league_id=league_id,
                                                     season=season)
        except ValueError:
            logger.warning(
                "You must input a valid integer to represent the current NFL week."
            )
            time.sleep(0.25)
            config = create_config_from_template(config,
                                                 root_directory,
                                                 config_file_path,
                                                 platform=platform,
                                                 league_id=league_id,
                                                 season=season)
        logger.debug(
            "Retrieved current NFL week for \"config.ini\": {0}".format(
                current_week))

    config.set("Settings", "current_week", current_week)

    with open(config_file_path, "w") as cf:
        config.write(cf, space_around_delimiters=True)

    return config
    if league.save_data:
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)

        with open(file_path, "w", encoding="utf-8") as data_out:
            data_out.write(html_soup.prettify())

    return html_soup


def patch_http_connection_pool(**constructor_kwargs):
    """This allows you to override the default parameters of the HTTPConnectionPool constructor. For example, to
    increase the pool size to fix problems with "HttpConnectionPool is full, discarding connection" call this function
    with maxsize=16 (or whatever size you want to give to the connection pool).
    """
    class MyHTTPSConnectionPool(connectionpool.HTTPSConnectionPool):
        def __init__(self, *args, **kwargs):
            kwargs.update(constructor_kwargs)
            super(MyHTTPSConnectionPool, self).__init__(*args, **kwargs)

    poolmanager.pool_classes_by_scheme['https'] = MyHTTPSConnectionPool


if __name__ == "__main__":

    local_config = AppConfigParser()
    local_config.read("../config.ini")
    local_current_nfl_week = get_current_nfl_week(config=local_config,
                                                  dev_offline=False)
    print(local_current_nfl_week)
import os
import sys
from utils.app_config_parser import AppConfigParser

module_dir = os.path.dirname(os.path.dirname(__file__))
sys.path.append(module_dir)

from calculate.bad_boy_stats import BadBoyStats
from calculate.beef_stats import BeefStats
from calculate.covid_risk import CovidRisk

test_data_dir = os.path.join(module_dir, "tests")
if not os.path.exists(test_data_dir):
    os.makedirs(test_data_dir)

config = AppConfigParser()
config.read(
    os.path.join(os.path.dirname(os.path.dirname(__file__)), "config.ini"))

player_first_name = "Dion"
player_last_name = "Lewis"
player_full_name = "{0} {1}".format(player_first_name, player_last_name)
player_team_abbr = "PHI"
player_position = "RB"


def test_bad_boy_init():
    bad_boy_stats = BadBoyStats(data_dir=test_data_dir,
                                save_data=True,
                                dev_offline=False,
                                refresh=True)
示例#6
0
                # noinspection PyTypeChecker
                response = self.sc.files_upload(
                    channels=self.get_channel_id(self.config.get("Slack", "slack_channel")),
                    filename=file_name,
                    filetype=file_type,
                    file=file_to_upload,
                    title=file_name,
                    initial_comment=message
                )
            return response
        except SlackApiError as e:
            logger.error("Slack client error: %s", e)


if __name__ == "__main__":
    local_config = AppConfigParser()
    local_config.read(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config.ini"))
    repost_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                               local_config.get("Slack", "repost_file"))

    post_to_slack = SlackMessenger(local_config)

    # general slack integration testing
    print(json.dumps(post_to_slack.api_test().data, indent=2))
    # print(json.dumps(post_to_slack.list_channels().data, indent=2))
    # print(json.dumps(post_to_slack.list_channels().get("channels"), indent=2))

    # public channel integration testing
    # print(json.dumps(post_to_slack.test_post_to_slack("test"), indent=2))
    # print(json.dumps(post_to_slack.test_file_upload_to_slack(repost_file).data, indent=2))
示例#7
0
        if not folder:
            new_parent_folder = drive.CreateFile({
                "title":
                folder_name,
                "parents": [{
                    "kind": "drive#fileLink",
                    "id": parent_folder_id
                }],
                "mimeType":
                "application/vnd.google-apps.folder"
            })
            new_parent_folder.Upload()
            parent_folder_id = new_parent_folder["id"]
        else:
            parent_folder_id = folder["id"]

        return parent_folder_id


if __name__ == "__main__":
    local_config = AppConfigParser()
    local_config.read(
        os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
            "config.ini"))
    reupload_file = local_config.get("Drive", "google_drive_reupload_file")

    google_drive_uploader = GoogleDriveUploader(reupload_file, local_config)
    upload_message = google_drive_uploader.upload_file()
    print(upload_message)