Forums

#033[33mAttributeError: 'str' object has no attribute 'execute'#033[0m

Need a little hel[p I''m Getting error :

2021-04-23 15:17:47,254: Exception on /login [POST]
#033[33mTraceback (most recent call last):#033[0m
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/moneynotes/mysite/application.py", line 77, in login
    rows = db.execute("SELECT * FROM users WHERE username = :username",
#033[33mAttributeError: 'str' object has no attribute 'execute'#033[0m
2021-04-23 15:18:11,308: Exception on /register [POST]
#033[33mTraceback (most recent call last):#033[0m
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/moneynotes/.virtualenvs/env/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/moneynotes/mysite/application.py", line 100, in register
    rows = db.execute("SELECT * FROM users WHERE username = :username", username=username)
#033[33mAttributeError: 'str' object has no attribute 'execute'#033[0m

import os
from os import path
import sys

from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session
import MySQLdb.cursors
from flask_mysqldb import MySQL
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
from datetime import datetime
from functools import wraps
from helpers import apology, login_required, usd, save_picture, percentage
from flask_wtf.csrf import CSRFProtect
from forms import (RegistrationForm, LoginForm, UpdateAccountForm, AddExpenseForm, AddIncomeForm,
                   ResetPasswordForm, SetIncomeGoalsForm, PlanBudgetsForm, ManageDebtForm, AddDebtPaymentForm)


# Configure application
app = Flask(__name__)


# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Enter your database connection details below
app.config['MYSQL_HOST'] = 'moneynotes.mysql.pythonanywhere-services.com'
app.config['MYSQL_USER'] = 'moneynotes'
app.config['MYSQL_PASSWORD'] = '******'
app.config['MYSQL_DB'] = 'moneynotes$budget'

# Intialize MySQL
#mysql = MySQL(app)

#  database
db = "moneynotes$budget"

# Custom filter
app.jinja_env.filters["usd"] = usd
app.jinja_env.filters["percentage"] = percentage

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/about")
def about():
    return render_template("about.html")

@app.route("/login", methods=["GET", "POST"])
def login():
    session.clear()
    if request.method == "GET":
        return render_template("login.html")
    else:
        user = request.form.get("username")
        password = request.form.get("password")
        if user == "" or password == "":
            return apology("Must enter username and password")
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))
        if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
            return apology("invalid username and/or password")
        session["user_id"] = rows[0]["id"]
        return redirect("/")


@app.route("/register", methods=["GET", "POST"])
def register():

    # Forget any other user_id
    session.clear()

    if request.method == "GET":
        return render_template("register.html")
    else:
        name = request.form.get("name")
        username = request.form.get("username")
        p1 = request.form.get("password")
        p2 = request.form.get("password2")
        if p1 != p2:
            return apology("Passwords don't match")
        rows = db.execute("SELECT * FROM users WHERE username = :username", username=username)
        if len(rows) == 1:
            return apology("Username taken")


        db.execute("INSERT INTO users (name, username, hash) VALUES (:name, :username, :pw)", name=name, username=username, pw=generate_password_hash(p1))

         # Now pull that user from the database
        rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))

        # Remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # Redirect user to home page
        return redirect("/")

[edited by admin: formatting]

seems like your sql query is incorrect

I can't find any issue . Do you have any ideas?

oh it's because you have

db = "moneynotes$budget"

and the error is

rows = db.execute("SELECT * FROM users WHERE username = :username", username=username)
AttributeError: 'str' object has no attribute 'execute'

why is db = "moneynotes$budget" wrong or better yet what should it be ?

That's way more than we can help with in the forums. We have a series of blog posts here that walk you through how to create a database-backed flask app. Hopefully by the end of that, you will have the answer to that question.