添加烧瓶脚本任务时出现TypeError

时间:2016-02-02 21:14:22

标签: python flask sqlalchemy flask-sqlalchemy flask-script

我正在努力修改cookiecutter Flask应用。

在基于flask-script的manage.py管理模块中,我正在尝试创建一个添加管理员用户的新任务'create_admin'。

@manager.command
def create_admin():
    """Creates the admin user."""
    db.session.add(User(
        email="ad@min.com",
        password="admin",
        admin=True,
        confirmed=True,
        confirmed_on=datetime.datetime.now()
    )
    )
    db.session.commit()

我已将其添加到列表末尾,您可以看到:

manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
manager.add_command("urls", ShowUrls())
manager.add_command("clean", Clean())
manager.add_command("create_admin", create_admin())

我有一个'用户'模型,如下所示:

class User(UserMixin, SurrogatePK, Model):

    __tablename__ = 'users'
    username = Column(db.String(80), unique=True, nullable=True)
    email = Column(db.String(80), unique=True, nullable=False)
    #: The hashed password
    password = Column(db.String(128), nullable=True)
    created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
    first_name = Column(db.String(30), nullable=True)
    last_name = Column(db.String(30), nullable=True)
    active = Column(db.Boolean(), default=False)
    is_admin = Column(db.Boolean(), default=False)
    confirmed = db.Column(db.Boolean, default=False)
    confirmed_on = db.Column(db.DateTime, nullable=True)


    def __init__(self, username, email, password=None, **kwargs):
        db.Model.__init__(self, username, email=email, **kwargs)
        if password:
            self.set_password(password)
        else:
            self.password = None

当我尝试运行新功能时:

$ python manage.py create_admin                        
Traceback (most recent call last):
  File "manage.py", line 57, in <module>
    manager.add_command("create_admin", create_admin())
  File "manage.py", line 46, in create_admin
    confirmed_on=datetime.datetime.now()
TypeError: __init__() takes at least 3 arguments (3 given)
(flask_mini)

我做错了什么?

编辑:

 File "C:\envs\r2\myflaskapp\myflaskapp\models\user.py", line 31, in __init__
    db.Model.__init__(self, username=username, email=email, **kwargs)
  File "c:\envs\virtalenvs\flask_mini\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 525, in _declarative_constructor
    (k, cls_.__name__))
TypeError: 'admin' is an invalid keyword argument for User

1 个答案:

答案 0 :(得分:1)

您的drawableSize课程采用User()位置参数:

username

但你没有通过:

def __init__(self, username, email, password=None, **kwargs):

作为第一个参数传递一个:

db.session.add(User(
    email="ad@min.com",
    password="admin",
    admin=True,
    confirmed=True,
    confirmed_on=datetime.datetime.now()
)
)

我将db.session.add(User( 'admin', email="ad@min.com", password="admin", is_admin=True, confirmed=True, confirmed_on=datetime.datetime.now() ) ) 更正为admin;您只有一个is_admin字段。

请注意,您只能将字段值作为关键字参数传递给SQLAlchemy基类:

is_admin