繁体   English   中英

Flask-Login: AttributeError: type object 'User' 没有属性 'get'

[英]Flask-Login: AttributeError: type object 'User' has no attribute 'get'

我在 Flask 登录时遇到问题。 每次我尝试登录时,都会出现此错误:

 AttributeError: type object 'User' has no attribute 'get'

我不知道这是从哪里来的,因为我使用的是 flask 文档中的推荐代码。 这是代码:

from flask import Flask, escape, request, render_template, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from flask_login import UserMixin, login_manager, login_user, login_required, logout_user, current_user, LoginManager
from flask_wtf import FlaskForm
from flask_wtf.form import FlaskForm
from flask_wtf.recaptcha import validators
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Length, ValidationError
from flask_bcrypt import Bcrypt



app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data_task.db'
db = SQLAlchemy(app)
app.config['SECRET_KEY'] = "HEXODECICUL"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

bcrypt = Bcrypt(app)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), nullable=False, unique=True)
    password = db.Column(db.String(80), nullable=False)

class RegisterForm(FlaskForm):
    username = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
    password = PasswordField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Password"})
    submit = SubmitField("Register")

    def validate_username(self, username):
        existing_usernames = User.query.filter_by(username=username.data).first()

        if existing_usernames:
            raise ValidationError("That username alreadu exists. Please choose a different one.")

class LoginForm(FlaskForm):
    username = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
    password = PasswordField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
    submit = SubmitField("Login")



@app.route('/dash', methods=['GET', 'POST'])
@login_required
def dash():
    return render_template("index.html")


@app.route("/login", methods=["GET", "POST"])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user:
            if bcrypt.check_password_hash(user.password, form.password.data):
                login_user(user)
                return redirect(url_for('dash'))
    return render_template("login.html", form = form)


@app.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))



@app.route("/register", methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data)
        new_user = User(username=form.username.data, password=hashed_password)
        db.session.add(new_user)
        db.session.commit()
        return redirect(url_for('login'))
    return render_template("register.html", form=form)


@app.route('/', methods=["GET", "POST"])
def accueil():
    return "Home"


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

flask中的错误:

    AttributeError
AttributeError: type object 'User' has no attribute 'get'

Traceback (most recent call last)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 2091, in __call__
    def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:
        """The WSGI server calls the Flask application object as the
        WSGI application. This calls :meth:`wsgi_app`, which can be
        wrapped to apply middleware.
        """
        return self.wsgi_app(environ, start_response)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 2076, in wsgi_app
response = self.handle_exception(e)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 1518, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 1516, in full_dispatch_request
rv = self.dispatch_request()Open an interactive python shell in this frame
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/Users/christophechouinard/Feuille_encaisse/app.py", line 69, in login
return render_template("login.html", form = form)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/templating.py", line 146, in render_template
ctx.app.update_template_context(context)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 756, in update_template_context
context.update(func())
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask_login/utils.py", line 379, in _user_context_processor
return dict(current_user=_get_user())
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask_login/utils.py", line 346, in _get_user
current_app.login_manager._load_user()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask_login/login_manager.py", line 318, in _load_user
user = self._user_callback(user_id)
File "/Users/christophechouinard/Feuille_encaisse/app.py", line 52, in load_user
    password = PasswordField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
    submit = SubmitField("Login")
 
@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)
 
@app.route('/dash', methods=['GET', 'POST'])
@login_required
def dash():
    return render_template("index.html")
AttributeError: type object 'User' has no attribute 'get'
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object
Brought to you by DON'T PANIC, your friendly Werkzeug powered traceback interpreter.

我知道这个问题已经在这里得到回答: https://stackoverflow.com/questions/ask#:~:text=AttributeError%3A%20type%20object%20%27Message,pack()%20display.update()% 20def%20... 但我试过了,但仍然出现这个错误(而且我不太了解这个问题的答案......)

非常感谢 !!

检查您的用户加载程序。 在那你调用User.get(user_id) 但是,它应该如下所示。

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(user_id)

通过这些行,SQLAlchemy 用于根据用户从数据库中的 id 查询用户。

我尝试了这个解决方案,它允许我进入我的网页并实际登录,但我遇到了另一个错误。

/Users/xinyuyang/PycharmProjects/flask authentication/main.py:22: LegacyAPIWarning: Query.get() 方法在 SQLAlchemy 的 1.x 系列中被认为是遗留的,并成为 2.0 中的遗留构造。 该方法现在可用作 Session.get()(自以下版本弃用:2.0)(SQLAlchemy 2.0 的背景位于: https://sqlalche.me/e/b8d9 )返回 User.query.get(user_id)

根据文档,它是一个过时的 function,他们推荐了另一种方法来执行此操作,但如果我尝试新方法,则会出现另一个错误。

我不断收到“TypeError: Session.get() missing 1 required positional argument: 'ident'”的错误

然后我阅读了文档,所以我将这部分代码更改为:

@login_manager.user_loader
def load_user(user_id):
    # session = Session(User)
    return Session.get(User,{"id":int(user_id)})
Then I keep getting the error of "TypeError: Session.get() missing 1 required positional argument: 'ident'"

文档说身份参数通常是字典,但我的字典在这里不起作用。

有谁知道如何解决这一问题? 非常感谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM