当它返回以下错误时,尝试在Heroku上部署我的Flask应用程序:
2019-11-29T09:07:28.456446+00:00 app[web.1]: File "/app/saltchat.py", line 55, in chatRoom
2019-11-29T09:07:28.456448+00:00 app[web.1]: onlineUsers.append(user.username)
2019-11-29T09:07:28.456454+00:00 app[web.1]: AttributeError: 'NoneType' object has no attribute 'username'
2019-11-29T09:07:28.458151+00:00 app[web.1]: 10.183.68.6 - - [29/Nov/2019:09:07:28 +0000] "GET /chat HTTP/1.1" 500 290 "https://salt-chat-v2.herokuapp.com/login" "Mozilla/5.0 (Windows NT 10
.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
当我在本地计算机上部署应用程序时,它可以按预期工作,并且仅在通过/ chat路由时遇到问题:
@app.route('/chat', methods=['POST', 'GET'])
def chatRoom():
username = session.get('username')
user = Users.query.filter_by(username=username).first()
if request.referrer is None:
return render_template('login.html')
else:
onlineUsers.append(user.username)
onlineUserAvatars.append(user.avatar)
return render_template('chat.html')
下面是我使用的数据库模型:
class Users(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(32), nullable=False)
password = db.Column(db.String, nullable=False)
avatar = db.Column(db.Integer)
答案 0 :(得分:2)
我认为问题出在您的会话用户身上。 请按如下所示修改您的代码:
@app.route('/chat', methods=['POST', 'GET'])
def chatRoom():
username = session.get('username', '')
try:
user = Users.query.filter_by(username=username).first()
except:
print("Something wrong")
if request.referrer is None:
return render_template('login.html')
else:
onlineUsers.append(user.username)
onlineUserAvatars.append(user.avatar)
return render_template('chat.html')