Home > Mobile >  Error in Flask and Python sqlite3 Integration
Error in Flask and Python sqlite3 Integration

Time:12-22

Alright! So, I was creating a simple Login Program for a recent website that I was working on! I'm using Flask to serve my HTML Page Templates.... I'm using the sqlite3 Python module for easy usage of modules...

So, I created an App Route for my main website for the login pages.. You can check the code below:

def login():
    msg = ''
    
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
        # Create variables for easy access
        username = request.form['username']
        password = request.form['password']

        #Connection Est.
        connection = sqlite3.connect("Users.db")

        #cursor
        USer_crsr = connection.cursor()

        user_cm = """SELECT username, password FROM accounts"""

        USer_crsr.execute(user_cm)
        USer_result = USer_crsr.fetchall()

        if username and password in USer_result:
            # Create session data, we can access this data in other routes
              session['loggedin'] = True
              session['id'] = USer_result['id']
              session['username'] = USer_result['username']
              # Redirect to home page
              return 'Logged in successfully!'
        else:
            # Account doesnt exist or username/password incorrect
            msg = 'Incorrect username/password!'
    return render_template("login.html", msg=msg)

I run my program and I get no errors at all! I open my login page and the page opens without raising an error! Here's the page look: Login Page

But when I Submit my form, I get an Error (not in the console, but in the webpage itself) : 405 - Method Not allowed!

Also, here's the code for the database file I used to create my database :


#Connection to FILE
User_DATA_connection = sqlite3.connect('Users.db')

crsr = User_DATA_connection.cursor()

#command here
command = """CREATE TABLE IF NOT EXISTS 'accounts' (
  'id' int(11) NOT NULL,
  'username' varchar(50) NOT NULL,
  'password' varchar(250) NOT NULL,
  'email' varchar(100) NOT NULL,
  PRIMARY KEY ('id')
) 
"""

#execute
crsr.execute(command)

comm = """INSERT INTO accounts VALUES (1, 'test', 'test', '[email protected]');"""

crsr.execute(comm)

User_DATA_connection.commit()

#close data
User_DATA_connection.close()

CodePudding user response:

When you decorate your Flask route's function, you need to allow the POST method. Example:

@app.route('/login', methods=["GET", "POST"])
def login():
    if request.method == "GET":
        # Render your page
    if request.method == "POST":
        # Process the data you POST-ed from your frontend (insert them into the DB, etc.)
  • Related