コード例 #1
0
def main(league, time, standings, team, live, use12hour, players,
         output_format, output_file, upcoming, lookup, listcodes, apikey):
    """
    A CLI for live and past football scores from various football leagues.

    League codes:

    \b
    - CL: Champions League
    - PL: English Premier League
    - ELC: English Championship
    - EL1: English League One
    - FL1: French Ligue 1
    - FL2: French Ligue 2
    - BL: German Bundesliga
    - BL2: 2. Bundesliga
    - SA: Serie A
    - DED: Eredivisie
    - PPL: Primeira Liga
    - PD: Primera Division
    - SD: Segunda Division
    """
    headers = {'X-Auth-Token': apikey}

    try:
        if output_format == 'stdout' and output_file:
            raise IncorrectParametersException(
                'Printing output to stdout and '
                'saving to a file are mutually exclusive')
        writer = get_writer(output_format, output_file)
        rh = RequestHandler(headers, LEAGUE_IDS, TEAM_NAMES, writer)

        if listcodes:
            list_team_codes()
            return

        if live:
            rh.get_live_scores(use12hour)
            return

        if standings:
            if not league:
                raise IncorrectParametersException(
                    'Please specify a league. '
                    'Example --standings --league=PL')
            if league == 'CL':
                raise IncorrectParametersException(
                    'Standings for CL - '
                    'Champions League not supported')
            rh.get_standings(league)
            return

        if team:
            if lookup:
                map_team_id(team)
                return
            if players:
                rh.get_team_players(team)
                return
            else:
                rh.get_team_scores(team, time, upcoming, use12hour)
                return

        rh.get_league_scores(league, time, upcoming, use12hour)
    except IncorrectParametersException as e:
        click.secho(str(e), fg="red", bold=True)
コード例 #2
0
ファイル: main.py プロジェクト: p-netm/soccer-cli
try:
    from soccer.validators import *
    from soccer.sub_main import teams as Teams, matches as Matches
    from soccer._utils import *
    from soccer.request_handler import RequestHandler
    from soccer.writers import get_writer
    from soccer.resources import Soccer
except ImportError as error:
    from validators import *
    from sub_main import teams as Teams, matches as Matches
    from _utils import *
    from request_handler import RequestHandler
    from writers import get_writer
    from resources import Soccer

request_handler = RequestHandler()
soccer = Soccer()


def get_input_key():
    """Input API key and validate"""
    click.secho("No API key found!", fg="yellow", bold=True)
    click.secho("Please visit {0} and get an API token.".format(
        RequestHandler.BASE_URL),
                fg="yellow",
                bold=True)
    while True:
        confkey = click.prompt(
            click.style("Enter API key", fg="yellow", bold=True))
        if len(confkey) == 32:  # 32 chars
            try:
コード例 #3
0
 NB: this module does not cushion users from creating possible erroneous API requests. This will then return
 the resultant error message as it is from the API
"""

import click

try:
    from soccer.request_handler import RequestHandler
    from soccer.exceptions import ApiKeyError, APIErrorException
except ImportError as error:
    from request_handler import RequestHandler
    from exceptions import ApiKeyError, APIErrorException
import os, sys

RH = RequestHandler()


def load_config_key():
    """Load API key from config file"""
    global api_token
    try:
        api_token = os.environ['SOCCER_CLI_API_TOKEN']
    except KeyError:
        home = os.path.expanduser("~")
        config = os.path.join(home, ".soccer-cli.ini")
        key = ''
        if os.path.exists(config):
            with open(config, "r") as cfile:
                key = cfile.read()
        if key:
コード例 #4
0
ファイル: main.py プロジェクト: PeriGK/soccer-cli
def main(league, time, standings, team, live, use12hour, players,
         output_format, output_file, upcoming, lookup, listcodes, apikey):
    """
    A CLI for live and past football scores from various football leagues.

    League codes:

    \b
    - CL: Champions League
    - PL: English Premier League
    - ELC: English Championship
    - EL1: English League One
    - FL1: French Ligue 1
    - FL2: French Ligue 2
    - BL: German Bundesliga
    - BL2: 2. Bundesliga
    - SA: Serie A
    - DED: Eredivisie
    - PPL: Primeira Liga
    - PD: Primera Division
    - SD: Segunda Division
    """
    headers = {'X-Auth-Token': apikey}

    try:
        if output_format == 'stdout' and output_file:
            raise IncorrectParametersException('Printing output to stdout and '
                                               'saving to a file are mutually exclusive')
        writer = get_writer(output_format, output_file)
        rh = RequestHandler(headers, LEAGUE_IDS, TEAM_NAMES, writer)

        if listcodes:
            list_team_codes()
            return

        if live:
            rh.get_live_scores(use12hour)
            return

        if standings:
            if not league:
                raise IncorrectParametersException('Please specify a league. '
                                                   'Example --standings --league=PL')
            if league == 'CL':
                raise IncorrectParametersException('Standings for CL - '
                                                   'Champions League not supported')
            rh.get_standings(league)
            return

        if team:
            if lookup:
                map_team_id(team)
                return
            if players:
                rh.get_team_players(team)
                return
            else:
                rh.get_team_scores(team, time, upcoming, use12hour)
                return

        rh.get_league_scores(league, time, upcoming, use12hour)
    except IncorrectParametersException as e:
        click.secho(str(e), fg="red", bold=True)
コード例 #5
0
 def setUp(self):
     dummy_key = 12345678901234567890123456789012
     self.headers = {'X-Auth-Token': dummy_key}
     url = 'http://api.football-data.org/v2/'
     self.dummy_url = url
     self.rq = RequestHandler()
コード例 #6
0
class TestRequestHandler(unittest.TestCase):
    def setUp(self):
        dummy_key = 12345678901234567890123456789012
        self.headers = {'X-Auth-Token': dummy_key}
        url = 'http://api.football-data.org/v2/'
        self.dummy_url = url
        self.rq = RequestHandler()

    def tearDown(self):
        pass

    def test_ok_code(self, mock_get):
        res = {'data': 'data'}
        mock_get.return_value = Mock(status_code=requests.codes.ok)
        mock_get.return_value.json.return_value = res
        try:
            self.rq._get(self.dummy_url, headers=self.headers)
        except APIErrorException:
            self.fail("Threw exception erroneously")

    def test_bad_code(self, mock_get):
        res = {'error': requests.codes.bad, 'message': 'Bad Request'}
        mock_get.return_value = Mock(status_code=requests.codes.bad)
        mock_get.return_value.json.return_value = res

        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url, headers=self.headers)

        self.assertIn('Bad Request', context.exception.__str__())

    def test_forbidden_code(self, mock_get):
        res = {
            'error': requests.codes.forbidden,
            'message': 'Disallowed request'
        }
        mock_get.return_value = Mock(status_code=requests.codes.forbidden)
        mock_get.return_value.json.return_value = res
        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url, headers=self.headers)
            import pdb
            pdb.set_trace()

        self.assertTrue(
            'This resource is restricted' in context.exception.__str__())
        self.assertTrue("Disallowed request" in context.exception.__str__())

    def test_not_found_code(self, mock_get):
        res = {'error': requests.codes.not_found, 'message': 'Page not found'}
        mock_get.return_value = Mock(status_code=requests.codes.not_found)
        mock_get.return_value.json.return_value = res
        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url, headers=self.headers)
        self.assertTrue("This resource does not exist. "
                        "Check parameters" in context.exception.__str__())
        self.assertTrue("Page not found" in context.exception.__str__())

    def test_too_many_requests_code(self, mock_get):
        res = {
            'error': requests.codes.too_many_requests,
            'message': 'Quota excedeed'
        }
        mock_get.return_value = Mock(
            status_code=requests.codes.too_many_requests)
        mock_get.return_value.json.return_value = res
        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url, headers=self.headers)

        self.assertTrue(
            "You have exceeded your allowed "
            "requests per minute/day" in context.exception.__str__())
        self.assertTrue('Quota excedeed' in context.exception.__str__())