~josealberto4444/apodnasabot

2ae28dcaf5edf3c0db2be7e95ecd9b8dfbbba6a1 — José Alberto Orejuela García 2 years ago b589bb0
Refactor code
1 files changed, 38 insertions(+), 24 deletions(-)

M api.py
M api.py => api.py +38 -24
@@ 17,27 17,41 @@ import configparser
import requests
import youtube_dl

config = configparser.ConfigParser()
config.read('config.cfg')
api_key = config['NASA_API']['api_key']

baseurl = 'https://api.nasa.gov/planetary/apod'
payload = {'api_key': api_key}
r = requests.get(baseurl, params = payload)
api_response = r.json()
filename = 'data/' + api_response['date']

with open(filename + '.json', 'wt') as f:
    f.write(str(api_response))

if api_response['media_type'] == 'image':
    r = requests.get(api_response['hdurl'])
    filename = filename + '.jpg'
    with open(filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=128):
            f.write(chunk)
elif api_response['media_type'] == 'video':
    filename = filename + '.%(ext)s'
    ydl_opts = {'outtmpl': filename}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([api_response['url']])
def read_api_key():
    config = configparser.ConfigParser()
    config.read('config.cfg')
    return config['NASA_API']['api_key']

def ask_api(api_key, date):
    baseurl = 'https://api.nasa.gov/planetary/apod'
    payload = {'api_key': api_key, 'date': date}
    r = requests.get(baseurl, params = payload)
    return r.json()

def save_json(filename, api_response):
    with open(filename + '.json', 'wt') as f:
        f.write(str(api_response))

def save_media(filename, api_response):
    if api_response['media_type'] == 'image':
        r = requests.get(api_response['hdurl'])
        filename = filename + '.jpg'
        with open(filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=128):
                f.write(chunk)
    elif api_response['media_type'] == 'video':
        filename = filename + '.%(ext)s'
        ydl_opts = {'outtmpl': filename, 'quiet': True}
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([api_response['url']])

def save_api_response(api_response):
    filename = 'data/' + api_response['date']
    save_json(filename, api_response)
    save_media(filename, api_response)

date = '2019-07-10'

api_key = read_api_key()
api_response = ask_api(api_key, date)
save_api_response(api_response)