python - 无法向 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)
如果你们中的任何人能指出我做错了什么,我将不胜感激。
解决方案
db.session
通常与 Flask-SQLAlchemy 一起使用,其中flask_sqlalchemy.SQLAlchemy
实例通常命名为db
. 另一方面,您直接使用 SQLAlchemy,scoped_session
特别是一个名为db
. 像会话一样使用它:
db.add(user)
db.commit()
它将这些操作代理到线程本地Session
实例。
推荐阅读
- json - 迁移到清单 v3 时,Chrome 扩展程序显示错误
- python - python sshtunnel:我收到以下错误:“IndexError:列表索引超出范围”
- apache - Apache https 并在 ubuntu 20.4 上重写实现
- java - 我无法在 Mysql 中发布我的数据,如何解决这个问题?
- c++ - lambda 函数不更新引用数组
- image - Flutter Web 如何将 Uint8List 转换为文件
- google-vault-api - 是否可以通过 Vault API 以编程方式继续导出?
- dart - 工厂构造函数的意义是什么?
- macos - 使用 dmg 更新 Mac 上的应用程序而不会丢失数据
- .net - 如何使用无服务器框架将参数传递给预定的 .Net lambda 函数?