2
respostas

[Dúvida] Não retorna a função quando rodo o código

import re

class ExtratorURL:
    def __init__(self, url):
        self.url = self.sanitiza_url(url)
        self.valida_url()



    def sanitiza_url(self, url):
        if type(url) == str:
            return url.strip()
        else:
            return ""

    def valida_url(self):
        if not self.url:
            raise ValueError("A URL está vazia")


        padrao_url = re.compile('(http(s)?://)?(www.)?bytebank.com(.br)?/cambio')
        match = padrao_url.match(self.url)
        if not match:
            raise ValueError("A URL não é válida")

        print("A url é valida")

    def get_url_base(self):
        indice_interrogacao = self.url.find('?')
        url_base = self.url[:indice_interrogacao]
        return url_base

    def get_url_parametros(self):
        indice_interrogacao = self.url.find('?')
        url_parametros = self.url[indice_interrogacao + 1:]
        return url_parametros

    def get_valor_parametro(self, parametro_busca):
        indice_parametro = self.get_url_parametros().find(parametro_busca)
        indice_valor = indice_parametro + len(parametro_busca) + 1
        indice_e_comercial = self.get_url_parametros().find('&', indice_valor)
        if indice_e_comercial == -1:
            valor = self.get_url_parametros()[indice_valor:]
        else:
            valor = self.get_url_parametros()[indice_valor:indice_e_comercial]
        return valor


    def __len__(self):
        return len(self.url)

    def __str__(self):
        return self.url
    def __eq__(self, other):
        return self.url == other.url

    def calcula_cambio(self):
        moeda_origem = self.extrator_url.get_url_parametros("moedaOrigem")
        valor_quantidade = self.extrator_url.get_valor_parametro("quantidade")
        valor_dolar = 5.50
        if moeda_origem == "real":
            convertido = float(valor_quantidade) * valor_dolar
            return f'O valor convertido de {moeda_origem} para dolar é {convertido}'
        else:
            convertido = float(valor_quantidade) / valor_dolar
            return f'O valor convertido de dolar para {moeda_origem} é {convertido}'






url = "https://bytebank.com/cambio?moedaDestino=dolar&quantidade=100&moedaOrigem=real"
extrator_url = ExtratorURL(url)
print("O tamanho da URL: ", len(extrator_url))
valor_quantidade = extrator_url.get_valor_parametro("quantidade")
print(valor_quantidade)
print(extrator_url)
2 respostas

a função não é chamada e foi necessário algumas alterações no código, da uma olhada:

import re

class ExtratorURL:
    def __init__(self, url):
        self.url = self.sanitiza_url(url)
        self.valida_url()



    def sanitiza_url(self, url):
        if type(url) == str:
            return url.strip()
        else:
            return ""

    def valida_url(self):
        if not self.url:
            raise ValueError("A URL está vazia")


        padrao_url = re.compile('(http(s)?://)?(www.)?bytebank.com(.br)?/cambio')
        match = padrao_url.match(self.url)
        if not match:
            raise ValueError("A URL não é válida")

        print("A url é valida")

    def get_url_base(self):
        indice_interrogacao = self.url.find('?')
        url_base = self.url[:indice_interrogacao]
        return url_base

    def get_url_parametros(self):
        indice_interrogacao = self.url.find('?')
        url_parametros = self.url[indice_interrogacao + 1:]
        return url_parametros

    def get_valor_parametro(self, parametro_busca):
        indice_parametro = self.get_url_parametros().find(parametro_busca)
        indice_valor = indice_parametro + len(parametro_busca) + 1
        indice_e_comercial = self.get_url_parametros().find('&', indice_valor)
        if indice_e_comercial == -1:
            valor = self.get_url_parametros()[indice_valor:]
        else:
            valor = self.get_url_parametros()[indice_valor:indice_e_comercial]
        return valor


    def __len__(self):
        return len(self.url)

    def __str__(self):
        return self.url
    def __eq__(self, other):
        return self.url == other.url

    def calcula_cambio(self):
        moeda_origem = 'real'
        valor_quantidade = self.get_valor_parametro("quantidade")
        valor_dolar = 5.50
        if moeda_origem == "real":
            convertido = float(valor_quantidade) * valor_dolar
            return f'O valor convertido de {moeda_origem} para dolar é {convertido}'
        else:
            convertido = float(valor_quantidade) / valor_dolar
            return f'O valor convertido de dolar para {moeda_origem} é {convertido}'






url = "https://bytebank.com/cambio?moedaDestino=dolar&quantidade=100&moedaOrigem=real"
extrator_url = ExtratorURL(url)
print("O tamanho da URL: ", len(extrator_url))
valor_quantidade = extrator_url.get_valor_parametro("quantidade")
print(valor_quantidade)
print(extrator_url)
valor = ExtratorURL(url).calcula_cambio()
print(valor)

Eu fiz de uma maneira um pouco diferente:

import re

class Busca:
    def __init__(self, url, *parametros) -> None:
        #pode receber mais de um parametro de busca
        self.url, self.parametros = self.parametros_check(url, parametros)

    def parametros_check(self, url, args):
        #não quis implementar o regex aqui por que limitaria a url à bytebank
        if not url.strip():
            raise ValueError('A URL está vazia')
        for item in args:
            if not item.strip():
                raise ValueError('não é possivel buscar um parametro vazio')
        return url, args

    @property
    def url_base(self):
        return self.url[:url.find('?')]

    @property
    def url_parametros(self):
        resultado = []
        for parametro in self.parametros:
            atributos = self.url[len(self.url_base)+1:]
            filtrado = atributos[atributos.find(parametro)+len(parametro)+1:]
            if filtrado.find('&') != -1:
                #desta forma é possivel verificar em qualquer URL
                resultado.append(filtrado[:filtrado.find('&')].replace('+', ' '))
            else:
                resultado.append(filtrado.replace('+', ' '))
        return resultado

    def conversor(self):
        dolar = 5.50
        quantidade = float(self.url_parametros[0])
        return f'R${quantidade:.2f} é o mesmo que U${quantidade * dolar:.2f}'



#passo a quantidade de reais através da url
url = 'http://bytebank.com/cambio?moedaOrigem=real&moedaDestino=dolar&quantidade=80'
valor = Busca(url,'quantidade').conversor()
print(valor)


Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software