コード例 #1
0
def cartolafc():
    api = cartolafc.Api()
    times = Cartolas.objects.all()

    for nomeTime in times:
        time = api.time(nome=nomeTime.cartolaTime)
        print(time.info.nome, '-', time.ultima_pontuacao)
コード例 #2
0
    def setUp(self):
        with requests_mock.mock() as m:
            m.post('https://login.globo.com/api/authentication',
                   text='{"id": "Authenticated", "userMessage": "Usuario autenticado com sucesso", "glbId": "GLB_ID"}')

            self.api = cartolafc.Api(email='*****@*****.**', password='******', redis_url='redis://localhost:6379/0')
            self.api_url = self.api._api_url
コード例 #3
0
    def test_api_auth_invalida(self):
        # Arrange
        with requests_mock.mock() as m:
            user_message = 'Seu e-mail ou senha estao incorretos.'
            m.post('https://login.globo.com/api/authentication', status_code=codes.unauthorized,
                   text='{"id": "BadCredentials", "userMessage": "%s"}' % user_message)

            # Act and Assert
            with self.assertRaisesRegexp(cartolafc.CartolaFCError, user_message):
                cartolafc.Api(email='*****@*****.**', password='******')
コード例 #4
0
    def test_api_auth_http_error(self):
        # Arrange
        with requests_mock.mock() as m:
            user_message = 'Seu e-mail ou senha estao incorretos.'
            m.post('https://login.globo.com/api/authentication', exc=HTTPError)

            # Act and Assert
            with self.assertRaisesRegex(cartolafc.CartolaFCError,
                                        'Erro authenticando no Cartola'):
                cartolafc.Api(email='*****@*****.**', password='******')
コード例 #5
0
    def test_api_auth_com_sucesso(self):
        # Arrange
        with requests_mock.mock() as m:
            m.post('https://login.globo.com/api/authentication',
                   text='{"id": "Authenticated", "userMessage": "Usuario autenticado com sucesso", "glbId": "GLB_ID"}')

            # Act
            api = cartolafc.Api(email='*****@*****.**', password='******')

            # Assert
            self.assertEqual(api._glb_id, 'GLB_ID')
コード例 #6
0
    def test_api_attempts(self):
        # Arrange and Act
        with requests_mock.mock() as m:
            api = cartolafc.Api(attempts=2)

            url = '{api_url}/mercado/status'.format(api_url=api._api_url)
            error_message = 'Mensagem de erro'
            m.get(url, status_code=codes.ok, text='{"mensagem": "%s"}' % error_message)

            with self.assertRaisesRegexp(cartolafc.CartolaFCError, error_message):
                api.mercado()
コード例 #7
0
def api_oauth(authfile):
    with open(authfile, "r") as f:
        ak = f.readlines()
    f.close()

    us_name = ak[0].split("\n")[0]
    us_pass = ak[1].split("\n")[0]

    #print("User Name:{}".format(us_name))
    #print("User Pass:{}".format(us_pass))

    api = cartolafc.Api(email=us_name, password=us_pass)
    return api
コード例 #8
0
    def test_api_auth_unauthorized(self):
        # Arrange
        with requests_mock.mock() as m:
            m.post('https://login.globo.com/api/authentication',
                   text='{"id": "Authenticated", "userMessage": "Usuario autenticado com sucesso", "glbId": "GLB_ID"}')

            api = cartolafc.Api(email='*****@*****.**', password='******')

            url = '{api_url}/mercado/status'.format(api_url=api._api_url)
            m.get(url, status_code=codes.unauthorized)

            # Act and Assert
            with self.assertRaises(cartolafc.CartolaFCOverloadError):
                api.mercado()
コード例 #9
0
    def test_api_attempts_com_servidores_sobrecarregados(self):
        # Arrange and Act
        with requests_mock.mock() as m:
            api = cartolafc.Api(attempts=2)

            url = '{api_url}/mercado/status'.format(api_url=api._api_url)
            error_message = 'Globo.com - Desculpe-nos, nossos servidores estão sobrecarregados.'
            m.get(url,
                  response_list=[
                      dict(status_code=codes.ok,
                           text='{"mensagem": "%s"}}' % error_message),
                      dict(status_code=codes.ok,
                           text='{"mensagem": "%s"}}' % error_message)
                  ])

            with self.assertRaisesRegex(cartolafc.CartolaFCError,
                                        error_message):
                api.mercado()
コード例 #10
0
            newClubes.append(lines)

        i += 1

    newClubes = '\n'.join(newClubes)
    newDestaques = '\n'.join(newDestaques)
    newJogadores = '\n'.join(newJogadores)
    arqJogadores = open('Templates\jogadores.html', 'w')
    arqDestaques = open('Templates\destaques.html', 'w')
    arqClubes = open('Templates\clubes.html', 'w')
    arqJogadores.write(newJogadores)
    arqDestaques.write(newDestaques)
    arqClubes.write(newClubes)


api = cartolafc.Api()
mercado = api.mercado()
api = cartolafc.Api(email='*****@*****.**', password='******')

url_rodadas = "https://api.cartolafc.globo.com/rodadas"
with urllib.request.urlopen(url_rodadas) as url:
    data_rodadas = json.loads(url.read(
    ))  #get content of all the rounds of the competition, from url

url_partidas = "https://api.cartolafc.globo.com/partidas"
with urllib.request.urlopen(url_partidas) as url:
    data_partidas = json.loads(
        url.read())  #get content of the past matches, from url

url_jogadoresDestaque = "https://api.cartolafc.globo.com/mercado/destaques"
with urllib.request.urlopen(url_jogadoresDestaque) as url:
コード例 #11
0
 def test_api_auth_sem_password(self):
     # Act and Assert
     with self.assertRaisesRegex(cartolafc.CartolaFCError,
                                 'E-mail ou senha ausente'):
         cartolafc.Api(email='*****@*****.**')
コード例 #12
0
 def test_api_auth_sem_email(self):
     # Act and Assert
     with self.assertRaisesRegex(cartolafc.CartolaFCError,
                                 'E-mail ou senha ausente'):
         cartolafc.Api(password='******')
コード例 #13
0
 def setUp(self):
     self.api = cartolafc.Api()
     self.api_url = self.api._api_url
コード例 #14
0
    def test_api_attempts_menor_que_1(self):
        # Arrange and Act
        api = cartolafc.Api(attempts=0)

        # Assert
        self.assertEqual(api._attempts, 1)
コード例 #15
0
 def test_api_redis_invalid_url(self):
     # Act and Assert
     with self.assertRaisesRegex(cartolafc.CartolaFCError,
                                 'Erro conectando ao servidor Redis.'):
         cartolafc.Api(redis_url='invalid-url')
コード例 #16
0
 def test_api_redis_invalid_server(self):
     # Act and Assert
     with self.assertRaisesRegex(cartolafc.CartolaFCError,
                                 'Erro conectando ao servidor Redis.'):
         cartolafc.Api(redis_url='redis://localhost:1234')
コード例 #17
0
    def test_api_redis_invalid_url(self):
        # Arrange
        api = cartolafc.Api(redis_url='invalid-url')

        # Act and Assert
        self.assertTrue(api._redis.ping())
コード例 #18
0
from flask import Flask, request, render_template
from extract import *
import editHtml
import pandas as pd
from xml.sax import saxutils as su
import datetime
import cartolafc

api = cartolafc.Api()

url_rodadas = "https://api.cartolafc.globo.com/rodadas"
content_rodadas = requests.get(
    url_rodadas).content  #get content of the past rounds, from url

url_partidas = "https://api.cartolafc.globo.com/partidas"
with urllib.request.urlopen(url_partidas) as url:
    data_partidas = json.loads(url.read(
    ))  #get content of the past matches, from url(this one has a json)

url_jogadoresDestaque = "https://api.cartolafc.globo.com/mercado/destaques"
with urllib.request.urlopen(url_jogadoresDestaque) as url:
    data_jogadoresDestaque = json.loads(
        url.read()
    )  #get content of the best players of the last round, from url(this one has a json)

url_jogadores = "https://api.cartolafc.globo.com/atletas/mercado"
with urllib.request.urlopen(url_jogadores) as url:
    data_jogadores = json.loads(url.read(
    ))  #get content of the past matches from url(this one has a json)

コード例 #19
0
import cartolafc

api = cartolafc.Api(email='*****@*****.**', password='******', attempts=5)

print api.amigos()
print api.clubes()
print api.liga(nome='Virtus Premier League')
print api.liga(nome='Nacional', page=2)
print api.liga(nome='Nacional', page=3, order_by=cartolafc.RODADA)
print api.liga(slug='virtus-premier-league')
print api.ligas(query='Virtus')
print api.ligas_patrocinadores()
print api.mercado()
print api.mercado_atletas()
print api.parciais()
print api.pontuacao_atleta(81682)
print api.pos_rodada_destaques()
print api.time(id=471815)
print api.time(nome='Falydos FC')
print api.time(slug='falydos-fc')
print api.time_logado()
print api.time_parcial(id=471815)
print api.time_parcial(nome='Falydos FC')
print api.time_parcial(slug='falydos-fc')
print api.times(query='Faly')
コード例 #20
0
    def autenticate(self):

        self._doc['method'] = 'autenticate'

        _retorno = False

        try:
            #abre o arquivo de autenticação e lê o conteúdo (usuário/senha do cartola)
            with open(self._path, "r") as f:
                ak = f.readlines()
            f.close()

            #registra o log de sucesso na leitura do arquivo
            self._doc[
                'step'] = 'Credenciais de autenticação carregadas do arquivo'
            self._doc['TYPE'] = 'INFO'

            if (self._elk):
                self._es.index(index="cartola_api_index",
                               doc_type="test-type",
                               body=self._doc)
        except IOError as inst:

            #registra log de erro na leitura do arquivo
            self._doc['step'] = "I/O error({}):".format(inst)
            self._doc['TYPE'] = 'ERROR'
            self._doc['timestamp'] = datetime.now()

            if (self._elk):
                self._es.index(index="cartola_api_index",
                               doc_type="test-type",
                               body=self._doc)

        try:
            us_name = ak[0].split("\n")[0]
            us_pass = ak[1].split("\n")[0]

            ##### Registra a tentativa de autenticação ######
            self._doc['step'] = 'Autenticando na API do cartola'
            self._doc['TYPE'] = 'INFO'
            self._doc['timestamp'] = datetime.now()

            if (self._elk):
                self._es.index(index="cartola_api_index",
                               doc_type="test-type",
                               body=self._doc)

            self._api = cartolafc.Api(email=us_name,
                                      password=us_pass,
                                      attempts=5)

            ##### Registra o sucesso na autenticação #####
            self._doc['step'] = 'Autenticado com sucesso na API do Cartola'
            self._doc['timestamp'] = datetime.now()

            if (self._elk):
                self._es.index(index="cartola_api_index",
                               doc_type="test-type",
                               body=self._doc)

            _retorno = (type(self._api) != type(None))
        except CartolaFCError as erro:

            ##### Registra a falha na tentativa de autenticação ######
            self._doc['step'] = 'Erro ao autenticar na API cartola: {}'.format(
                erro)
            self._doc['TYPE'] = 'ERROR'
            self._doc['timestamp'] = datetime.now()

            if (self._elk):
                self._es.index(index="cartola_api_index",
                               doc_type="test-type",
                               body=self._doc)

            _retorno = False
        return _retorno
コード例 #21
0
    def test_api_attempts_nao_inteiro(self):
        # Arrange and Act
        api = cartolafc.Api(attempts='texto')

        # Assert
        self.assertEqual(api._attempts, 1)
コード例 #22
0
import cartolafc

api = cartolafc.Api(email='*****@*****.**',
                    password='******',
                    attempts=5,
                    redis_url='redis://localhost:6379/0')

print(api.amigos())
print(api.clubes())
print(api.liga(nome='Virtus Premier League'))
print(api.liga(nome='Nacional', page=2))
print(api.liga(nome='Nacional', page=3, order_by=cartolafc.RODADA))
print(api.liga(slug='virtus-premier-league'))
print(api.ligas(query='Virtus'))
print(api.ligas_patrocinadores())
print(api.mercado())
print(api.mercado_atletas())
print(api.parciais())
print(api.partidas(1))
print(api.pontuacao_atleta(81682))
print(api.pos_rodada_destaques())
print(api.time(id=2706236))
print(api.time(id=2706236, as_json=True))
print(api.time(nome='ALCAFLA FC'))
print(api.time(nome='ALCAFLA FC', as_json=True))
print(api.time(slug='alcafla-fc'))
print(api.time(slug='alcafla-fc', as_json=True))
print(api.time_logado())
print(api.time_parcial(id=2706236))
print(api.time_parcial(nome='ALCAFLA FC'))
print(api.time_parcial(slug='alcafla-fc'))