类NameError:名称未定义

时间:2019-09-10 15:12:26

标签: python flask sqlalchemy pythonanywhere

我正在pythonanywhere.com和MySQL DB上用Flask构建一个小型网站。

数据库为“ ******** $ registeredUser”,第一个表用于用户登录系统(“ registeredUsers”)。 用以下方式创建用户:

usr = User("n@k.com","john","muller","passwordhash")
db.session.add(usr)
db.session.commit()

这有效... 但是我想为某些消息创建一个称为“评论”的第二张表。 我重复此步骤:

com = Comment("this is a test comment")
db.session.add(com)
db.session.commit()

但第一行是错误

r = Comment("this is a test comment")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Comment' is not defined

代码在这里...

from flask import Flask, render_template, request, redirect, url_for, flash
from flask_login import login_user, LoginManager, UserMixin, login_required, logout_user, current_user
from werkzeug.security import check_password_hash, generate_password_hash
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config["DEBUG"] = True
app.secret_key = "cjkm1093f1uomes2oipd98wmfdtwkp"
login_manager = LoginManager()
login_manager.init_app(app)

#Configure DB Connection Settings
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
    username="nilskreie",
    password="12345678",
    hostname="********.mysql.pythonanywhere-services.com",
    databasename="********$registeredUsers",
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)

class User(UserMixin, db.Model):
    __tablename__ = "registeredUsers"
    id = db.Column(db.Integer, primary_key=True)
    mail = db.Column(db.String(128))
    firstName = db.Column(db.String(128))
    lastName = db.Column(db.String(128))
    password_hash = db.Column(db.String(128))
    email_confirmed = db.Column(db.String(128))
    vote = db.Column(db.Integer)
    def __init__(self, mail, firstName, lastName, password_hash):
        self.mail = mail
        self.firstName = firstName
        self.lastName = lastName
        self.password_hash = generate_password_hash(password_hash)
        self.email_confirmed = False
        self.vote = 0
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
    def get_id(self):
        return self.mail

class Comment(db.Model):
    __tablename__ = "comments"
    id = db.Column(db.Integer, primary_key=True)
    mail = db.Column(db.String(128))
    msg = db.Column(db.String(1024))
    def __init__(self, mail, msg):
        self.mail = "place@holder.com"
        self.msg = 0
    def get_id(self):
        return self.mail

可能是什么问题? 提前非常感谢!

1 个答案:

答案 0 :(得分:1)

弄清楚了-问题不是代码。

pythonanywhere具有“ 重新加载”按钮和“ 运行”按钮。
我总是按“ 重新加载”,并按“ 运行”即可!