【问题标题】:'scoped_session' object has no attribute 'create_all' 'scoped_session' object has no attribute 'session'“scoped_session”对象没有属性“create_all”“scoped_session”对象没有属性“session”
【发布时间】:2020-05-11 03:30:33
【问题描述】:

所以我尝试使用烧瓶和 SQLAlchemy 创建一个网站来存储数据库,但我不断收到上述两个错误

这是我的 app.py 代码

import os

from flask import Flask, session,render_template, request
from flask_session import Session
from sqlalchemy import create_engine,Column, Integer, String
from sqlalchemy.orm import scoped_session, sessionmaker
from flask_sqlalchemy import SQLAlchemy
from models import *
app = Flask(__name__)

#app.config["DATABASE_URL"] = "sqlite:////plz_work.db"
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)


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

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

# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
class User:
    def __init__(self,username,password):
        self.username = username
        self.password = password


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

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

@app.route("/send", methods = ['GET','POST'])
def send():
    username = request.form['username']
    password = request.form['password']
    users = User(username,password)
    db.session.add(users)
    db.session.commit()
    return render_template('index.html')

if __name__ == "__main__":
    app.run(debug = True)
    db.create_all()

这是我的 models.py 文件

import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class USERS(db.Model):
    __tablename__ = "Users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String)
    password = db.Column(db.String)
def __repr__(self):
        value = "USER:({}, {})".format(self.username, self.password)
        return value

我一直在网上寻找一个解决方案这么久,但我找不到任何适合我的东西,我花了 2 天时间解决这个问题,任何帮助将不胜感激。

谢谢!!

【问题讨论】:

  • 我认为如果您使用的是 flsk-sqlalchemy,您应该始终将 db 定义为 db = SQLAlchemy()

标签: python flask sqlalchemy flask-sqlalchemy cs50


【解决方案1】:

我猜你在你的 models.py 文件中覆盖了你的数据库对象。 我建议您使用 sqlalchemy 本身或 flask-sqlalchemy 不要一起使用它们。在我看来,如果将它们一起使用,事情会变得复杂。

你可以这样实现:

在你的 app.py 中

...your_other_imports...
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from .models import *

app = Flask(__name__)

...your_other_configs...

# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
#NOW db carries your database session
#Do not define your database models in app.py remove User class from here.
#You should define your database model and also your query method (not necessary)
#if you're used to query with flask-sqlalchemy. Would make queries look similar to you
dbModel = declarative_base()
dbModel.query = db.query_property()

# define the function which will create your tables
def init_db():
    from .models import *
    dbModel.metadata.create_all(bind=engine)

...your_routes...

if __name__ == "__main__":
    app.run(debug = True)

    # now call the function to create your tables
    init_db()

在你的 models.py 中

from .app import dbModel
from sqlalchemy import Column, Integer, String

class User(dbModel):
    __tablename__ = "users"
    id = Columnn(Integer, primary_key=True)
    username = Column(String)
    password = Column(String)
    def __repr__(self):
        value = "USER:({}, {})".format(self.username, self.password)
        return value

使用 query_property,您现在可以从数据库中查询数据并使用会话将数据放入数据库中,如下所示:

User.query.filter_by(username=...).first()

newUser = User(
        username=...,
        password=...
    )
db.add(newUser)
db.commit()

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多