问题描述
我正在尝试从另一个API服务获取一些JSON数据并更新我的flask应用程序的数据库,同时用户可以下载一些PDF文件。该API具有3个键。第一个是“状态”。当该“状态”键具有"success"
值时,它也具有其他两个键和值。然后,应用程序运行正常,没有错误。
但是,当“状态”具有'fail'
值时,其他两个键和值将不存在。我写了一些异常,但是它不起作用,并以KeyError KeyError: 'country'
这是我的代码。
@app.route("/pdf/download/<int:pdf_id>",methods=['GET','POST'])
def downloads(pdf_id):
current_ip = someIPaddress
req = requests.request("GET",'http://anotherwebsite.com/json/someIPaddress?fields=169')
req_two = req.json()
status = req_two['status']
country = req_two['country']
city = req_two['city']
download_file = Pdf_info.query.get(pdf_id)
if Ipaddress.query.filter(Ipaddress.ip_address == current_ip,Ipaddress.pdfid == pdf_id).first():
try:
return send_from_directory("pdfs/pdf/",filename=download_file.file_location_name,as_attachment=True)
except FileNotFoundError:
abort(404)
else:
if status == "success":
ip_adding = Ipaddress(ip_address=current_ip,pdfid=pdf_id,downtime=datetime.utcnow(),country=country,location=city)
db.session.add(ip_adding)
db.session.commit()
try:
return send_from_directory("pdfs/pdf/",as_attachment=True)
except FileNotFoundError:
abort(404)
else:
ip_adding = Ipaddress(ip_address=current_ip,downtime=datetime.utcnow())
db.session.add(ip_adding)
db.session.commit()
try:
return send_from_directory("pdfs/pdf/",as_attachment=True)
except FileNotFoundError:
abort(404)
有人可以解释为什么这行不通吗或请提及解决方案吗?。
解决方法
您正在尝试获取:
country = req_two['country']
city = req_two['city']
在测试以下内容的输出之前:
status = req_two['status']
因此,如果status
为fail
,则country=
和city=
将失败。
使用:
country = req_two.get('country')
city = req_two.get('city')
如果未找到密钥,则会返回None
,而不是随后的“ KeyError . It also allows you test the
国家and
城市`变量。