0

我被写了一些代码

SQLAlcemy 的用户类

##############models.py
class User(Base,UserMixin):
    __tablename__ = 'users'
    id = Column(Integer, Sequence('seq_user_id'), primary_key=True)
    name = Column(String(50), unique=True, index = True, nullable = False)
    email = Column(String(120), unique=True, index = True, nullable = False)
    password = Column(String(128), nullable = False)
    registerdate = Column(Date, nullable = False)

    def __init__(self, name, email, password, registerdate):
        self.name = name
        self.email = email
        self.password = password
        self.registerdate = datetime.datetime.now()

    def __repr__(self):
        return '<User %r>' % (self.name)

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.id)

然后我写了一些代码来创建测试用户

############## frontend.py
@app.route('/createuser')
def createuser():
    user_jacky = User(name='jacky',email='jacky@test.com',password=md5.new('123').hexdigest())
    db_session.add(user_jacky)
    db_session.commit()
    return redirect(url_for('index'))

当我访问http://test.com/createuser时,系统告诉我“TypeError: init () 至少需要 5 个非关键字参数(给定 4 个)”。我又看了一遍SQLALchemy的文档,和我的代码一样,不需要给自己传值。发生了什么事?

4

1 回答 1

0

问题是__init__希望您传入 a ,但是当通过此行调用registerdate时您没有提供一个:__init__

User(name='jacky',email='jacky@test.com',password=md5.new('123').hexdigest())

如果registerdate应该始终是now(),则可以省略参数:

def __init__(self, name, email, password):
    self.name = name
    self.email = email
    self.password = password
    self.registerdate = datetime.datetime.now()

如果您希望能够提供registerdate,但它应该默认为now(),您可以这样做:

def __init__(self, name, email, password, registerdate=None):
    self.name = name
    self.email = email
    self.password = password
    self.registerdate = registerdate or datetime.datetime.now()
于 2013-08-26T09:37:26.770 回答