我有一个大型数据库,并使用sqlalchemy填充(原始 - 不是flask-SQLAlachemy)。我想在网站上添加烧瓶安全性,我意识到它依赖于flask-SQLAlachemy(而不是原始版本),但这是我的理解(刚开始尝试了解更多关于它)烧瓶-SQLAlchemy可以使用原本的。将用户输入数据库似乎可行。当我导航到受限制的页面时,它会提示我登录(应该如此)。输入正确的电子邮件地址和密码后,我收到错误AttributeError: type object 'User' has no attribute 'query'
,由于错误的追溯并未引用我的任何代码,因此我不确定如何解决。
认为这可能是一个sqlalchemy to flask-SQLAlchemy转换问题,我觉得我已经尝试了创建新数据库的所有内容。我还没有在flask-security或flask-SQLAlchemy文档中找到任何内容来帮助解决此问题。任何人都知道如何解决这个问题?
这是我的代码:
testing.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')
database_setup.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'
答案 0 :(得分:3)
您的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)使User类继承自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
答案 1 :(得分:1)
添加
Base.query = db_session.query_property()
在
下 Base = declarative_base()
在
database_setup.py
参考:https://pythonhosted.org/Flask-Security/quickstart.html#id2
答案 2 :(得分:0)
您可以尝试修改创建数据库模型的方式,如下所示:
class User(db.Model):
# parms
通常以这种方式创建模型将能够让用户使用查询方法。 希望对您有所帮助。