<jupyter_start><jupyter_text>Aula 13 - APIs<jupyter_code>import requests
url = 'https://swapi.co/api/people/'
response = requests.get(url)
response_json = response.json()
#print(response_json)
#print(response_json['name'])
from tkinter import *
class TkUrlImage():
    def __init__(self, window, url, width = 400, height = 400):
        self.url = url
        self.window = window
        self.width = width
        self.height = height

        raw_data = requests.get(self.url, stream=True).raw.data
        im = Image.open(io.BytesIO(raw_data))
        self.image = ImageTk.PhotoImage(im)
        self.me = Label(self.window, image=self.image, width=self.width, height=self.height)
    
    def as_label(self):
        return self.me
        
    
import requests
import io
from tkinter import *
from PIL import Image, ImageTk

class Meowner():
    def __init__(self):
        self.janela = Tk()
        self.janela.title('Meowner')
        self.janela.geometry('800x600')
        self.janela.tk_setPalette(background= '#7e7d80', foreground = '#ffFF00', activeBackground = 'blue')
        
        self.btn_update = Button(self.janela, text='OTRO GATO!', command=self.update_cat)
        self.btn_update.pack()
        
        self.update_cat()
        
        self.janela.mainloop()
        
        
    def update_cat(self):
        try:
            self.image.destroy()
        except:
            pass
        
        self.cat_img_url = self.get_random_cat()
        self.image = TkUrlImage(window=self.janela, url=self.cat_img_url, width=600, height=400).as_label()
        self.image.pack()

    def get_random_cat(self):
        url = 'https://aws.random.cat/meow'
        r = requests.get(url)
        r_json = r.json()
        return r_json['file']

m = Meowner()
import requests
import io
from tkinter import *
from PIL import Image, ImageTk

class Meowner():
    def __init__(self):
        self.janela = Tk()
        self.janela.title('Meowner')
        self.janela.geometry('800x600')
        self.janela.tk_setPalette(background= '#7e7d80', foreground = '#ffFF00', activeBackground = 'blue')
        
        self.btn_update = Button(self.janela, text='OTRO GATO!', command=self.update_cat)
        self.btn_update.pack()
        
        self.update_cat()
        
        self.janela.mainloop()
        
        
    def update_cat(self):
        self.cat_img_url = self.get_random_cat()
        self.image = self.get_tkinter_image(self.cat_img_url)
        try:
            self.label.destroy()
        except:
            pass
        self.label = Label(self.janela, image=self.image, width=600, height=400)
        self.label.pack()
        
    def get_tkinter_image(self, img_url):
        raw_data = requests.get(img_url, stream=True).raw.data
        im = Image.open(io.BytesIO(raw_data))
        image = ImageTk.PhotoImage(im)
        return image

    def get_random_cat(self):
        url = 'https://aws.random.cat/meow'
        r = requests.get(url)
        r_json = r.json()
        return r_json['file']

m = Meowner()<jupyter_output><empty_output><jupyter_text>Gatoflix - Com API Requests<jupyter_code>import requests
import csv
import io
from tkinter import *
from tkinter import messagebox
from PIL import Image, ImageTk

class Gatoflix():
    def __init__(self):
        self.base_filmes = self.get_movie_base()
        self.do_layout()

    def get_movie_base(self):
        base = {}
        with open('movies.csv', 'r') as file:
            reader = csv.DictReader(file)
            for row in reader:
                titulo = row['title']
                base[titulo] = row
                
        return base
    
    def do_movie_detail(self, evt):
        widget = evt.widget # isso volta o listbox que foi clicado
        index = widget.curselection()
        titulo_filme = widget.get(index)
        
        omdb_info = self.fetch_omdb_detail(titulo_filme)
        if omdb_info is not None:
            self.update_labels(omdb_info)
    
    def fetch_omdb_detail(self, title):
        title_fix = title[:title.index('(')].strip()
        year = title[title.index('('):title.index(')')].strip()
        url = 'https://www.omdbapi.com/?apiKey=d92c22a&t={}&y={}'.format(title_fix.replace(' ', '+'), year)
        response = requests.get(url).json()
        if 'Error' in response:
            messagebox.showinfo("ERRO!", "Filme não encontrado no OmDB")
            return None
        
        return {
            'year': response['Year'],
            'plot': response['Plot'],
            'poster': response['Poster'],
            'awards': response['Awards'],
            'title': title
        }
        
    def update_labels(self, infos):
        self.label_movie_title['text'] = '{}'.format(infos['title'])
        self.label_year['text'] = 'Ano: {}'.format(infos['year'])
        self.label_awards['text'] = 'Prêmios: {}'.format(infos['awards'])
        self.set_poster(infos['poster'], self.frame_image)
        
    def set_poster(self, url, window):
        self.image = self.get_tkinter_image(url)
        try:
            self.label_img.destroy()
        except:
            pass
        self.label_img = Label(window, image=self.image, width=600, height=400)
        self.label_img.pack()
        
    def get_tkinter_image(self, img_url):
        raw_data = requests.get(img_url, stream=True).raw.data
        im = Image.open(io.BytesIO(raw_data))
        image = ImageTk.PhotoImage(im)
        return image
        
    
    def do_layout(self):
        self.janela = Tk()
        self.janela.title('GATOFLIX')
        self.janela.geometry('1024x768')
        
        lbl_programa = Label(self.janela, text = "Gatoflix", font=('arial', 40, 'bold'))
        lbl_programa.pack()
        
        frame_detalhe = Frame(self.janela)
        frame_detalhe.pack(side = TOP)
        
        self.list_box = Listbox(frame_detalhe, width = 45)
        self.list_box.bind('<<ListboxSelect>>', self.do_movie_detail)
        self.list_box.pack()
        
        self.info = Frame(self.janela)
        self.info.pack(side=LEFT)
        
        self.label_movie_title = Label(self.info, text = "Aqui vai o texto", font=('arial', 32, 'italic'))
        self.label_movie_title.pack(side=TOP)
                
        self.label_year = Label(self.info, text = "Ano: ----", font=('arial', 20, 'bold'))
        self.label_year.pack(side=TOP)
        
        self.label_awards = Label(self.info, text = "Prêmios: ----", font=('arial', 20, 'bold'))
        self.label_awards.pack(side=TOP)
        
        # Inserindo no final do list box o titulo de cada filme
        # da base carregada no início
        for filme in sorted(self.base_filmes.keys()):
            self.list_box.insert(END, filme)
            
        self.frame_image = Frame(self.janela)
        self.frame_image.pack(side=LEFT)
            
        url = 'https://m.media-amazon.com/images/M/MV5BMDU2ZWJlMjktMTRhMy00ZTA5LWEzNDgtYmNmZTEwZTViZWJkXkEyXkFqcGdeQXVyNDQ2OTk4MzI@._V1_SX300.jpg'
        self.set_poster(url, self.frame_image)
        
        self.janela.mainloop()
gatoflix = Gatoflix()<jupyter_output><empty_output><jupyter_text>Exercício 4 - APIsPara os próximos exercícios vamos utilizar uma API do Governo Federal para analisar os gastos por meio de cartão de pagamento. O link da API é:“http://www.transparencia.gov.br/api-de-dados/cartoes?mesExtratoInicio={}%2F{}&mesExtratoFim={}%2F{}&pagina={}”.format(mes_ini, ano_ini, mes_fim, ano_fim, pagina)onde os dados retornados correspondem a um intervalo definido por um mês e ano inicial (mes_ini e ano_ini) e um mês e ano final (mes_fim, ano_fim) e são apresentados 14 dados por página, com a primeira página sendo definida por pagina = 1.<jupyter_code>import requests

mes_ini = '06'
ano_ini = 2018
mes_fim = '07'
ano_fim = 2018
pagina = 2
url = 'http://www.transparencia.gov.br/api-de-dados/cartoes?mesExtratoInicio={}%2F{}&mesExtratoFim={}%2F{}&pagina={}'.format(mes_ini, ano_ini, mes_fim, ano_fim, pagina)

response = requests.get(url)
print(response)
response.json()
mes_ini = '06'
ano_ini = 2018
mes_fim = '07'
ano_fim = 2018
pagina = 1
url = 'http://www.transparencia.gov.br/api-de-dados/cartoes?mesExtratoInicio={}%2F{}&mesExtratoFim={}%2F{}&pagina={}'
response = requests.get(url.format(mes_ini, ano_ini, mes_fim, ano_fim, pagina))
total = len(response.json())

while len(response.json()) > 0:
    pagina += 1
    print('Buscando página ', pagina, '...')
    response = requests.get(url.format(mes_ini, ano_ini, mes_fim, ano_fim, pagina))
    total += len(response.json())

print('Transações: ', total)
url = 'https://api.exchangerate-api.com/v4/latest/BRL'
response = requests.get(url)
print(response.json())
from datetime import datetime
timestamp = 1574035858
dt_object = datetime.fromtimestamp(timestamp)
dt_object
'{0:%d/%m/%Y %H:%M:%S}'.format(dt_object)
'{0:%d/%B/%Y %H:%M:%S}'.format(dt_object)
age = 10
f'{age}'<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13293828264758498, 'fraction_numerical': 0.01509391771019678, 'mean_word_length': 2.64953080375357, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 16, 'https://': 6, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '237682', 'license': 'MIT', 'n_tokens_mistral': 3213, 'n_tokens_neox': 3093, 'n_words': 569, 'path': 'Aula_10/Aula 13 - APIs (2).ipynb', 'repo_name': 'elcbasilio/letscode', 'size': '8944'}