Keren_H
Keren_H

Reputation: 101

Python flask DELETE request

I'm in the middle of developing a Python app and using flask, and this is my DELETE function:

@app.route('/DeleteMessage', methods=['DELETE'])
def DeleteMessage():
    messages = Message.query.all()
    application_id = request.args.get('application_id')
    if application_id:
        messages.filter_by(user_id=application_id)
    session_id = request.args.get('session_id')
    if session_id:
        messages.filter_by(session_id=session_id)    
    message_id = request.args.get('message_id')
    if message_id:
        messages = message.filter_by(message_id=message_id)  
    db.session.delete(messages)
    db.session.commit()
    return 'ok'

When I try to run it, it sends me such an error message:

Method Not Allowed
The method is not allowed for the requested URL.

Upvotes: 1

Views: 14427

Answers (2)

NavaneethaKrishnan
NavaneethaKrishnan

Reputation: 1326

Browsers support PUT and DELETE only with AJAX request, but not with HTML form submission. HTML form tag will allow only GET and POST methods.

In your case, you can send an ajax request like this,

$.ajax({
url: '{{url_for("DeleteMessage")}}',
type: 'DELETE',
success: function(result) {
    // write something if needed
}
});

Upvotes: 3

Mikhail Sidorov
Mikhail Sidorov

Reputation: 1434

You make GET request, but your flask backend awaiting DELETE request on that endpoint /DeleteMessage. You can change request method to GET @app.route('/DeleteMessage', methods=['GET']) and it will work, but it is contrary to the http standard.

You can read about how to send DELETE request in this question: How to send DELETE request?

Additional Information:

https://www.rfc-editor.org/rfc/rfc2616#section-9.3 https://www.restapitutorial.com/lessons/httpmethods.html

Upvotes: 1

Related Questions