Lanski
Lanski

Reputation: 35

Can't submit data to SQLAlchemy: AttributeError: 'scoped_session' object has no attribute 'session'

I'm pretty new to coding and I'm training myself.

I'm trying to create a registration form for a website using a combination of: - Flask - SQLAlchemy - WTForms

I have ran onto many errors and checking the documentation has been helpful so far. Unfortunately, I'm not able to understand how to solve this problem by looking at the documentation. If you do know, I would appreciate it if you'd let me know where so I can be self-sufficient next time. When I submit data on the website to register a user, the following error pops up: AttributeError: 'scoped_session' object has no attribute 'session'

Here's the code:

import os

from flask import Flask, session, render_template, url_for, request
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from forms import RegistrationForm
from models import User

app = Flask(__name__)

# Check for environment variable
if not os.getenv("DATABASE_URL"):
    raise RuntimeError("DATABASE_URL is not set")

# Set up a secret key for CSRF protection in forms (wtforms)
SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Adding this to avoid it throwing an error
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))

...

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

    # Get data from the form based on the class
    form = RegistrationForm(request.form)

    # When submitting data to the form
    if request.method == "POST":

        # Check all validations are correct
        if form.validate_on_submit():

            # Check whether the name already exists in the database
            namecheck = db.session.query(User).filter_by(uname="form.username").first()

            checker = "form.username.data"

            # namecheck = User.query.filter_by(uname="form.username").first()

            if (namecheck == checker):

                return render_template("error.html", message="Username already exists! Please pick another one.")

            else:
                # creates a "user" based on the class "User()" defined in models.py and gives it the data from the form
                user = User(uname="form.username.data", psswd="form.password.data")

                db.session.add(user)
                db.session.commit()
            return render_template("success.html", message="You have registered!")

        # if validations are NOT correct, load the form again with the right error messages
        else:
            return render_template("signup.html", form = form)

    else:
        return render_template("signup.html", form = form)

I would be tremendously grateful if any of you could point me out to what I'm doing wrong.

Upvotes: 0

Views: 2883

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 53007

db.session is commonly used with Flask-SQLAlchemy, in which the flask_sqlalchemy.SQLAlchemy instance is usually named db. You on the other hand are using SQLAlchemy directly, and a scoped_session registry in particular, named db. Use it as you would a session:

db.add(user)
db.commit()

It will proxy those operations to the thread-local Session instance.

Upvotes: 2

Related Questions