flaskhttp-status-code-405

Error "405 Method Not Allowed" on accessing Flask App


I'm trying to set up a website that uses Flask to send data via app.py into a database. However, when I try to open the app in the browser, I get a 405 error. The method, as seen in the code below, is POST.

My code: app.py

from flask import *
import sqlite3

app = Flask(__name__)

# Ensures the correct table is present before sending the form data

@app.route('/', methods=['POST'])
def main():
    connection = sqlite3.connect('database.db')
    cursor = connection.cursor()
    create_table_query = '''
        CREATE TABLE IF NOT EXISTS voters (
            VoterID INTEGER PRIMARY KEY AUTOINCREMENT,
            VoterName TEXT
            VoterAge INTEGER
            CandidateID INTEGER REFERENCES candidates(CandidateID)
    )'''

    cursor.execute(create_table_query)
    connection.commit()
    connection.close()
    return render_template('index.html')


# Pass the form data through app.py and to the database
@app.route('/index.html', methods = ['POST'])
def send_to_database():
    votername = request.form['name']
    voterage = request.form['age']
    connection = sqlite3.connect('database.db')
    cursor = connection.cursor()
    query1 = "INSERT INTO database (name,age) VALUES ('{n}','{a}')".format(n=votername,a=voterage)
    cursor.execute(query1)
    connection.commit()


if __name__== '__main__':
    app.run(debug=True)

Solution

  • When you load your app, you're presumably going to the / route. When using a browser to visit a page, a GET request is sent. Since the / route only allows POST requests, Flask returns an error.

    POST requests are used when data needs to be sent to the server. See the corresponding MDN page for more information

    Since no processing of user data is done in the main function, remove methods=["POST"] from its decorator. This will set the allowed methods to GET. (see Flask Docs)