9

我有一个用 sqlalchemy 构建和填充的大型数据库(原始的 - 不是 flask-SQLAlachemy)。我想在网站上添加烧瓶安全性,我意识到它依赖于烧瓶-SQLAlchemy(而不是原来的),但我的理解是烧瓶-SQLAlchemy 可以使用(刚开始尝试了解更多关于它的信息)原本的。将用户输入数据库似乎可行。当我导航到受限页面时,它会提示我登录(应该如此)。输入正确的电子邮件地址和密码时,我收到错误AttributeError: type object 'User' has no attribute 'query'消息,并且由于错误的回溯没有引用我的任何代码,我不知道如何解决它。

认为这可能是 sqlalchemy 到 flask-SQLAlchemy 的转换问题,我觉得除了创建新数据库之外我已经尝试了所有方法。我在 flask-security 或 flask-SQLAlchemy 文档中没有找到任何可以帮助解决此问题的内容。任何人都知道如何解决这个问题?

这是我的代码:

测试.py

from flask import Flask, render_template
from sqlalchemy import create_engine, asc, and_, or_, func, desc
from sqlalchemy.orm import sessionmaker
import database_setup
from database_setup import Base, User, Role
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required

application.config['SECRET_KEY'] = 'super-secret'

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(database_setup, User, Role)
security = Security(application, user_datastore)

engine = create_engine('sqlite:///landtohuntalpha.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

@application.route('/user/add/', methods = ['GET','POST'])
def addUser():
if request.method == 'POST':
    submission = User(
        email = request.form['email'],
        password = request.form['password'],
    )
    session.add(submission)
    session.commit()
    return redirect(url_for('completedUser'))
else:
    return render_template('addUser.html')

@application.route('/restricted_page/')
@login_required
def restrictedPage():
    return render_template('restricted_page.html')

数据库设置.py

import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, Boolean, Float, Date, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required

Base = declarative_base()

roles_users = Table('roles_users', Base.metadata, Column('user_id', Integer, ForeignKey('user.id')), Column('role_id', Integer, ForeignKey('role.id')))

class Role(Base, RoleMixin):
    __tablename__ = 'role'
    id = Column(Integer, primary_key=True)
    name = Column(String(80), unique=True)
    description = Column(String(255))

class User(Base, UserMixin):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    email = Column(String(250), nullable=False)
    password = Column(String(30))
    last_login_at = Column(DateTime)
    active = Column(Boolean)
    confirmed_at = Column(DateTime)
    current_login_at = Column(DateTime)
    last_login_ip = Column(String(45))
    current_login_ip = Column(String(45))
    login_count = Column(Integer)

回溯错误

File "C:\Python34\lib\site-packages\flask\app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
File "C:\Python34\lib\site-packages\flask\app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
File "C:\Python34\lib\site-packages\flask\app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
File "C:\Python34\lib\site-packages\flask\app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
File "C:\Python34\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
File "C:\Python34\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Python34\lib\site-packages\flask_security\decorators.py", line 205, in wrapper
    return f(*args, **kwargs)
File "C:\Python34\lib\site-packages\flask_security\views.py", line 75, in login
    if form.validate_on_submit():
File "C:\Python34\lib\site-packages\flask_wtf\form.py", line 166, in validate_on_submit
    return self.is_submitted() and self.validate()
File "C:\Python34\lib\site-packages\flask_security\forms.py", line 230, in validate
    self.user = _datastore.get_user(self.email.data)
File "C:\Python34\lib\site-packages\flask_security\datastore.py", line 191, in get_user
    rv = self.user_model.query.filter(query).first()
AttributeError: type object 'User' has no attribute 'query'
4

3 回答 3

5

您的 User 类继承自没有查询属性的 UserMixin(来自 flask-login)。无法完全解释我们项目之间的差异,但这是我的基本设置:

初始化.py:

from flask import Flask, render_template, session
from flask.ext.sqlalchemy import SQLAlchemy
import flask.ext.login as FL


# define the main app object
app = Flask(__name__)
app.config.from_object('config')
app.secret_key = 'super secret string'

login_manager = FL.LoginManager()
login_manager.init_app(app)
login_manager.login_view = "/"

# create the database object
db = SQLAlchemy(app)

然后在models.py(确保导入db)中使用户类继承自db.Model:

from flasker import db
import datetime
from flask.ext.login import UserMixin

class User(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    email = db.Column(db.Unicode(128))
    name = db.Column(db.Unicode(128))
    password = db.Column(db.Unicode(1024))
    authenticated = db.Column(db.Boolean, default=False)
    posts = db.relationship('Post')
    #-----login requirements-----
    def is_active(self):
    #all users are active
        return True 

    def get_id(self):
        # returns the user e-mail. not sure who calls this
        return self.email

    def is_authenticated(self):
        return self.authenticated

    def is_anonymous(self):
        # False as we do not support annonymity
        return False

    #constructor
    def __init__(self, name=None, email=None, password=None):
        self.name = name
        self.email = email
        self.password = password
        self.authenticated = True
于 2016-01-22T09:34:59.490 回答
5

添加

Base.query = db_session.query_property()

在下面

Base = declarative_base()

database_setup.py

参考:https ://pythonhosted.org/Flask-Security/quickstart.html#id2

于 2020-07-02T05:44:37.850 回答
2

您可以尝试修改创建数据库模型的方式,如下所示:

class User(db.Model):
    # parms

一般以这种方式创建模型就能让用户使用查询方法。希望能帮助到你。

于 2019-07-05T03:25:47.673 回答