簡體   English   中英

Python Flask JSON KeyError

[英]Python Flask JSON KeyError

我正在嘗試從另一個 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/", filename=download_file.file_location_name, as_attachment=True)
                except FileNotFoundError:
                    abort(404)
            else:
                ip_adding = Ipaddress(ip_address=current_ip, pdfid=pdf_id, downtime=datetime.utcnow())
                db.session.add(ip_adding)
                db.session.commit()
                try:
                    return send_from_directory("pdfs/pdf/", filename=download_file.file_location_name, as_attachment=True)
                except FileNotFoundError:
                    abort(404)

有人可以解釋為什么這不起作用或請提及解決方案嗎?

您正在嘗試獲取:

country = req_two['country']
city = req_two['city']

在測試以下輸出之前:

status = req_two['status']

因此,如果statusfailcountry=city=將失敗。

用:

country = req_two.get('country')
city = req_two.get('city')

如果未找到密鑰,則將返回None而不是 ``KeyError . It also allows you test the . It also allows you test the之后. It also allows you test the country and city` 變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM