Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

jquery - Unexpected KeyError in Flask (Python) when checking for key in json dict

this is my first question on StackOverflow and I have been stumped by a KeyError for the longest time so I hope someone is able to figure out what's wrong. I am making a Flask app which has some POST methods (from AJAX), and my line of Python code checking if the key is in the dict if 'delete' in data is giving me a KeyError. I tried printing but it isn't printing my output either which is weird. This is the Python code:

def index():
    if request.method == 'POST':
        if 'addItem' in request.form:
            # Do stuff

        elif request.get_json():
            data = request.get_json()
            print(data) # This is not printing even though I can see the object in Chrome devtools
            
            if 'delete' in data: # This is the line throwing the error
                to_remove = data['delete']
                session['ingredients'].remove(to_remove)
                session.modified = True
                return redirect('/')
            elif 'name' in data:
                # Do stuff

And this is the Javascript/jQuery for the two types of JSON objects:

    $('.save').on('click', function(event) {
        $.ajax({
            type: 'POST',
            url: '/',
            data: JSON.stringify({
                'name': $(event.target).siblings(".edit[name='name']").text(),
                'key_ingred': $(event.target).siblings(".edit[name='key-ingred']").text(),
                'recipe': $(event.target).siblings(".edit[name='recipe']").text(),
                'meal': $(event.target).siblings('b').text(),
                'date': $(event.target).siblings('.date').text()
            }),
            contentType: 'application/json',
            dataType: 'json'
        });
    })

    $('.delete').on('click', function(event){
        $.ajax({
            type: 'POST',
            url: '/',
            data: JSON.stringify({ 'delete': $(event.target).prev().text() }),
            success: function() { $(event.target).parent().remove(); },
            contentType: 'application/json',
            dataType: 'json'
        });
        $(event.target).parent().remove();
    });

EDIT: Here is the full traceback message:

Traceback (most recent call last):
  File "/Project/env/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Project/env/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Project/env/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Project/env/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Project/env/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Project/env/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Project/app.py", line 40, in index
    if 'delete' in data:
KeyError: 'delete'

I have tried using if data.get('delete') is not None as well and that didn't work either. Thanks in advance!!!

question from:https://stackoverflow.com/questions/65622941/unexpected-keyerror-in-flask-python-when-checking-for-key-in-json-dict

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...