如何在分配之前解决局部变量“密码”引用

时间:2019-02-01 13:32:47

标签: python flask

我正在使用发布请求存储数据,但是每当我单击“提交”时,我的代码中都会显示此错误,提示“分配前本地变量“密码”引用”。我已经检查了所有缩进。

@app.route('/admin/new_nurse', methods=['GET','POST'])
@login_required
def create_nurse(): 
    form=NurseForm()
    x=time.strftime("%H:%M:%S")
    if (x>=('00:00:00')and x<=('11:59:59')):
        x=(str('Good Morning'))
    elif x>=('12:00:00')and x<=('15:59:59'):
        x=(str('Good Afternoon'))
    elif x>=('16:00:00')and x<=('23:59:59'):
        x=(str('Good Evening'))

    if form.validate_on_submit():
        if form.picture.data:
            picture_file = save_picture(form.picture.data)
            firstname=request.form['fname']
            surname=request.form['sname']
            date_of_birth=request.form['dob']
            age_of_nurse=request.form['age']
            sex_option=request.form['sexoption']
            nurse_telephone=request.form['telnumber']
            educational_status=request.form['educationalstatus']
            Postal_Address=request.form['postaladdress']
            House_No=request.form['houseno']
            locality=request.form['locality']
            dept=request.form['dpt']
            username=form.username.data
            email=form.email.data
            password=form.password.data
            relative_info=request.form['relative']
        hashed_password= bcrypt.generate_password_hash(password).decode('utf-8')
        Nurse=User(username=form.username.data,email=email,password=hashed_password,date_created=datetime.datetime.now(),image_file=picture_file,first_name=firstname,Sur_name=surname,date_of_birth=date_of_birth,age=age_of_nurse,sex=sex_option,telephone=nurse_telephone,educational_status=educational_status,postal_address=Postal_Address,home_address=House_No,locality=locality,relative_name=relative_info,profile='')
        assign_Dept=Department.query.filter_by(name=dept).first()
        assign_role=Role.query.filter_by(id=3).first()
        assign_role.main_role.append(Nurse)
        assign_Dept.main_dept.append(Nurse)
        db.session.add(Nurse)
        db.session.commit()
        flash(f'Account created for {form.username.data}', 'success')
    data=[{'sex':'Male'}, {'sex':'Female'}]
    result=Department.query.with_entities(Department.name)
    return render_template('addnurse.html',x=x,title="New_Nurse",li="New_Nurse",form=form,data=data,result=result)

2 个答案:

答案 0 :(得分:0)

如果

if form.picture.data:

为False,您的密码变量将不会初始化,这将导致该行出现错误

hashed_password= bcrypt.generate_password_hash(password).decode('utf-8')

答案 1 :(得分:0)

也许您已经检查过了,但是如果form.validate_on_submit()返回True且form.picture.data为None,则最终将使用“ password”的值,但是,至少在您发布的代码中,您会没有为其分配任何值。