我写了一些代码
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)
然后我为create test user
编写了一些代码############## 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的文档,这与我的代码相同,不需要将值传递给self。发生了什么事?
答案 0 :(得分:0)
问题在于__init__
希望您传入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()