Search code examples
pythonjsonflaskkeyerror

Python Flask JSON KeyError


I'm trying to get some JSON data from another API service and update my flask app's database while user can download some PDF files. That API have 3 keys. 1st one is 'Status'. When that 'Status' key has "success" value, it also have other two keys and values too. Then app works fine without errors. But when the 'Status' has the 'fail' value, other two keys and values won't be there. I wrote a some exception but it doesn't work and end up with a KeyError, KeyError: 'country'

Here is my code.


    @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)

Can someone explain why this doesn't work or mention a solution please ?.


Solution

  • You are trying to fetch:

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

    before you have tested the output of:

    status = req_two['status']
    

    so if status is fail then country= and city= will fail.

    Use:

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

    That will return None if the key is not found instead of a ``KeyError. It also allows you test the countryandcity` variables afterwards.