告诉我如何处理错误?我知道服务器并不想响应我的请求,只是阻止了我。如何绕过它?我正在尝试保存来自 NASA 网站的照片。理论上,一切都应该有效,因为这是 Microsoft DEV330x 课程中的一项任务,它适用于所有人。但看起来美国宇航局已经厌倦了这些要求,他们对学生采取了某种保护措施。
%%writefile apod.py
import argparse
from datetime import date, timedelta
from random import randint
import os
import urllib.request
def parse_command_line():
parser = argparse.ArgumentParser()
parser.add_argument("-d",'--date', nargs = 3, metavar = ("month", "day", "year"), action = "store", type = int, help = "month day year formatted date (i.e. 03 28 1998)")
parser.add_argument ('-s', '--surprise', action = 'store_true', help = 'select a random date for a surprise image')
parser.add_argument ('-k', '--api_key', action = "store", type = str, help = 'NASA developer key')
parser.add_argument ('-v', '--verbose', action = 'store_true', help = 'verbose mode')
args = parser.parse_args()
return args
def create_date(datelist, surprise):
try:
if datelist != None:
d = date(datelist[2], datelist[0], datelist[1])
return d
else:
if surprise:
start_date = date(1995,6,16)
end_date = date.today()
delta = end_date - start_date
delta_random = randint(0, delta.days)
d = date.today() - timedelta(delta_random)
return d
else:
end_date = date.today()
d = date.today() - timedelta(days = 1)
return d
except :
return None
def query_url(d, api_key):
global date_obj
date_obj = d.strftime("%Y-%m-%d")
URL = "https://api.nasa.gov/planetary/apod?api_key={}&date={}"
complete_URL = URL.format(api_key,date_obj)
return complete_URL
def save_image(d, image):
year = d.strftime("%Y")
month = d.strftime("%m")
file_path = year+"/"+month+"/"+date_obj+".jpg"
open(file_path, 'wb')
return file_path
def request(url):
# request the content of url and save the retrieved binary data
with urllib.request.urlopen(url) as response:
data = response.read()
# convert data from byte to string
data = data.decode('UTF-8')
# convert data from string to dictionary
data = eval(data)
return data
def download_image(url):
# request the content of url and return the retrieved binary image data
with urllib.request.urlopen(url) as response:
image = response.read()
return image
def main():
# NASA developer key (You can hardcode yours for higher request rate limits!)
API_KEY = "cZX0zRDveiz7AfGfOW23typMH3NCnS3uvQJc0ZNS"
# parse command line arguments
args = parse_command_line()
# update API_KEY if passed on the command line
print(args.api_key)
if args.api_key != '':
API_KEY = args.api_key
# create a request date
d = create_date(args.date, args.surprise)
# ascertain a valid date was created, otherwise exit program
if d is None:
print("No valid date selected!")
exit()
# verbose mode
if args.verbose:
print("Image date: {}".format(d.strftime("%b %d, %Y")))
# generate query url
url = query_url(d, API_KEY)
# verbose mode
if args.verbose:
print("Query URL: {}".format(url))
# download the image metadata as a Python dictionary
metadata = request(url)
# verbose mode
if args.verbose:
# display image title, other metadata can be shown here
print("Image title: {}".format(metadata['title']))
# get the url of the image data from the dictionary
image_url = metadata['url']
# verbose mode
if args.verbose:
print("Downloading image from:", image_url)
# download the image itself (the returned info is binary)
image = download_image(image_url)
# save the downloaded image into disk in (year/month)
# the year and month directories correspond to the date of the image (d)
# the file name is the date (d) + '.jpg'
save_image(d, image)
print("Image saved")
if __name__ == '__main__':
main()
更正这段代码,就是这样:
您只是没有正确检查,因此在 complete_url 您收到 None 而不是密钥。