0

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.
toffee
  • 47
  • 2
  • 3
  • 9

2 Answers2

2

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
}
});
NavaneethaKrishnan
  • 1,213
  • 1
  • 9
  • 22
1

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

Community
  • 1
  • 1
Mikhail Sidorov
  • 1,325
  • 11
  • 15
  • I tried: @ app.route ('/ DeleteMessage', methods = ['GET']) But I received such an error message: sqlalchemy.orm.exc.UnmappedInstanceError: Class 'flask_sqlalchemy.BaseQuery' is not mapped – toffee Apr 29 '20 at 21:46
  • Please, update the question and include code for your models and db engine. – Mikhail Sidorov Apr 29 '20 at 21:48