烧瓶check_password始终返回false

如何解决烧瓶check_password始终返回false

如果用户单击登录名,则在主页上为用户创建登录名,然后显示登录页面。如果电子邮件名和密码正确,则在其中输入电子邮件名和密码,然后将用户重定向到主页。现在的问题是用户登录的密码是错误还是正确,而另一个问题是如果我打印user.check_password(form.password.data),那么它将返回false。我不明白问题是什么。我有config.json,并且在那里定义了参数,所以不用担心。 set_password(self,password)可以正常工作并存储在数据库中,除了检查密码外,其他一切都很好。这是我的python代码。

local_server=True

app=Flask(__name__)
app.secret_key='supper-secret-key'
login_manager=LoginManager(app)
login_manager.init_app(app)
login_manager.session_protection="strong"

db = SQLAlchemy(app)

class Users(UserMixin,db.Model):
    __tablename__='users'
    user_id=db.Column(db.Integer,primary_key=True)
    first_name=db.Column(db.String(80),nullable=False)
    last_name=db.Column(db.String(80),nullable=False)
    email=db.Column(db.String(80),nullable=False)
    password_hash=db.Column(db.String(255),nullable=False)

    def get_id(self):
        return self.user_id

    def set_password(self,password):
        self.password_hash = generate_password_hash(password)

    def check_password(self,password):
        return check_password_hash(self.password_hash,password)

class LoginForm(FlaskForm):
    email=StringField('email',validators=[DataRequired()])
    password=PasswordField('password',validators=[DataRequired()])
    remember_me=BooleanField('Remember me')
    submit=SubmitField('login')

@login_manager.user_loader
def load_user(user_id):
    return Users.query.get(int(user_id))
    
@app.route("/")
def home():
    return render_template("index.html",params=params)
    
def is_safe_url(target):
    ref_url=urlparse(request.host_url,target)
    test_url = urlparse(urljoin(request.host_url,target))
    return test_url.scheme in ('http','https') and \
            ref_url.netloc==test_url.netloc

@app.route("/login",methods=['POST','GET'])
def login():
    if current_user.is_authenticated:
        return render_template('index.html',params=params)
    form=LoginForm()
    if form.validate_on_submit():
        user=Users.query.filter_by(email=form.email.data).first()
        user.check_password(form.password.data)
        if not user:
            flash('Please check login details and try again','danger')
            return redirect(url_for('login'))
        print(user.check_password(form.password.data))                   #False
        flash('Successfully logged in','success')
        login_user(user,remember=form.remember_me.data)
        next=flask.request.args.get('next')
        if not is_safe_url(next):
            return flask.abort(400)
        return flask.redirect(next or flask.url_for('home'))
    return render_template("login.html",params=params,form=form)
    
@app.route("/logout")
def logout():
    logout_user()
    flash('You were logged out','warning')
    return redirect(url_for('home'))

@app.route("/register")
def register():
    if current_user.is_authenticated:
        return render_template('index.html',params=params)
    return render_template('register.html',params=params)

@app.route("/register",methods=['GET','POST'])
def register_post():
    first_name = request.form.get('fname')
    last_name = request.form.get('lname')
    email = request.form.get('email')
    password= request.form.get('password')
    password2=request.form.get('cpassword')
    if (password!=password2):
        flash('Password must be same','danger')
        return render_template('register.html',params=params)
    users=Users.query.filter_by(email=email).first()
    if users:
        flash('Email address already exists','warning')
        return redirect(url_for('register'))
    new_user=Users(first_name=first_name,last_name=last_name,email=email)
    new_user.set_password(password)
    db.session.add(new_user)
    db.session.commit()
    return redirect(url_for('login'))
    
app.run(debug=True)

我还有一个错误如果我输入了错误的电子邮件ID,则错误为AttributeError: 'NoneType' object has no attribute 'check_password' 这是完整的错误代码

File "C:\Python38\Lib\site-packages\flask\app.py",line 2464,in __call__
return self.wsgi_app(environ,start_response)
File "C:\Python38\Lib\site-packages\flask\app.py",line 2450,in wsgi_app
response = self.handle_exception(e)
File "C:\Python38\Lib\site-packages\flask\app.py",line 1867,in handle_exception
reraise(exc_type,exc_value,tb)
File "C:\Python38\Lib\site-packages\flask\_compat.py",line 39,in reraise
raise value
File "C:\Python38\Lib\site-packages\flask\app.py",line 2447,in wsgi_app
response = self.full_dispatch_request()
File "C:\Python38\Lib\site-packages\flask\app.py",line 1952,in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python38\Lib\site-packages\flask\app.py",line 1821,in handle_user_exception
reraise(exc_type,line 1950,in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python38\Lib\site-packages\flask\app.py",line 1936,in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\tuts\PythonFlask\ThirdFlask.py",line 134,in login
user.check_password(form.password.data)
AttributeError: 'NoneType' object has no attribute 'check_password'

这是login.html的代码

{% extends "layout.html" %}
{% block body %}
  
<form method="POST" action="/login">
<div class="overlay"></div>
<div class="container">
  <div class="row">
    <div class="card" style="margin: auto; margin-top: 100px; width: 25rem;">
        <!--message flashing started here-->
  {% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages%}
  {% for category,message in messages%}
  <div class="alert alert-{{category}} alert-dismissible fade show" role="alert">
  {{message}}
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  {% endfor %}
  {% endif %}
  {% endwith %}
      <div class="card-body">
        <form class="form" method="POST" action="/login">
          {{ form.csrf_token }}
          {{ form.name }}
          <label>Email</label><br>
          <input type="email" class="form-control" name="email" placeholder="email" required><br>
          <label>Password</label><br>
          <input type="password" class="form-control" name="password" placeholder="password" required><br><br>
          <div class="checkbox mb-3">
            <label>
              <input type="checkbox" value="remember_me"> Remember me
            </label>
          </div>
          <input type="submit" class="btn btn-primary btn-block btn-lg" value="login">
        </form>
        <p>Not a member? <a href="/register">Create Account</a></p>
      </div>
    </div>
  </div>
</div>

<!-- Main Content -->

{% endblock %}

帮我解决这个问题,在此先感谢:)

解决方法

您需要重新排列:

@app.route("/login",methods=['POST','GET'])
def login():
    if current_user.is_authenticated:
        return render_template('index.html',params=params)
    form=LoginForm()
    if form.validate_on_submit():
        user=Users.query.filter_by(email=form.email.data).first()
        # dont check password if user with that email does not exist
        if not user:
            flash('Please check login details and try again','danger')
            return redirect(url_for('login'))

        if user.check_password(form.password.data):
            flash('Successfully logged in','success')
            login_user(user,remember=form.remember_me.data)
            next=flask.request.args.get('next')
            if not is_safe_url(next):
                return flask.abort(400)
            return flask.redirect(next or flask.url_for('home'))
        else:
            flash('incorrect password','fail')

    return render_template("login.html",params=params,form=form)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-