解決Flask和Django的錯誤“TypeError: 'bool' object is not callable”


跟着歡迎進入Flask大型教程項目!的教程學習Flask,到了重構用戶模型的時候,運行腳本后報錯:

TypeError: 'bool' object is not callable

這是用戶模型:

class User(db.Model): id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic')  @property def is_authenticated(self): return True  @property def is_active(self): return True  @property def is_anonymous(self): return False def get_id(self): try: return unicode(self.id) # python 2 except NameError: return str(self.id) # python 3 def __repr__(self): return '<User %r>' % (self.nickname) 

這是調用的時候的代碼:

from flask import render_template, flash, redirect, session, url_for, request, g from flask.ext.login import login_user, logout_user, current_user, login_required from app import app, db, lm, oid from .forms import LoginForm from .models import User @app.route('/login', methods=['GET', 'POST']) @oid.loginhandler def login(): if g.user is not None and g.user.is_authenticated(): # 這一句報錯 return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): session['remember_me'] = form.remember_me.data return oid.try_login(form.openid.data, ask_for=['nickname', 'email']) return render_template('login.html', title='Sign In', form=form, providers=app.config['OPENID_PROVIDERS']) 

解決方法:

按照參考資料里面的說法:
is_authenticated是屬性而不是方法,把括號去掉就可以了。書里這一段有兩處印刷錯誤,請參照git源碼。

把出錯的地方:
if g.user is not None and g.user.is_authenticated():
修改為
if g.user is not None and g.user.is_authenticated:
然后就不報錯了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM