首页 > 解决方案 > 无法向 SQLAlchemy 提交数据:AttributeError:“scoped_session”对象没有属性“session”

问题描述

我对编码很陌生,我正在训练自己。

我正在尝试使用以下组合为网站创建注册表单: - Flask - SQLAlchemy - WTForms

我遇到了很多错误,到目前为止检查文档很有帮助。不幸的是,我无法通过查看文档来理解如何解决这个问题。如果你知道,如果你能告诉我在哪里,我将不胜感激,这样我下次就可以自给自足了。当我在网站上提交数据注册用户时,弹出以下错误: AttributeError: 'scoped_session' object has no attribute 'session'

这是代码:

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)

如果你们中的任何人能指出我做错了什么,我将不胜感激。

标签: pythonflasksqlalchemy

解决方案


db.session通常与 Flask-SQLAlchemy 一起使用,其中flask_sqlalchemy.SQLAlchemy实例通常命名为db. 另一方面,您直接使用 SQLAlchemy,scoped_session特别是一个名为db. 像会话一样使用它:

db.add(user)
db.commit()

它将这些操作代理到线程本地Session实例。


推荐阅读