【问题标题】:TypeError: unbound method make_valid_name() must be called with User instance as first argument (got unicode instance instead)类型错误:必须使用用户实例作为第一个参数调用未绑定的方法 make_valid_name()(取而代之的是 unicode 实例)
【发布时间】:2016-07-22 16:41:07
【问题描述】:

我正在从 烧瓶 sqlalchemy

from flask.ext.sqlalchemy import SQLAlchemy

到 sqlalchemy.orm - 会话生成器

from sqlalchemy.orm import sessionmaker

型号

@staticmethod
class User(Base):
    __tablename__ = 'user'
    id          = Column(Integer        , primary_key=True)
    name        = Column(String(20)     , unique=True, nullable=False)
.
.
.
    def make_valid_name(name):
        return re.sub('[^a-zA-Z0-9_\.]', '', name)

表格

def validate(self):
.
.
.    
if self.name.data != User.make_valid_name(self.name.data):
                self.name.errors.append('Please use letters, numbers, dots and underscores only.')
                return False

调用 self.validate() 方法时抛出以下错误

TypeError: unbound method make_valid_name() must be called with User instance as first argument (got unicode instance instead)

我不确定需要修改什么,如何从字段数据验证“self.name.data”

对此的任何帮助都会很棒。

【问题讨论】:

  • @staticmethod 是否出现在您省略的代码中?
  • 是的,它是一个静态方法。

标签: python-2.7 flask sqlalchemy flask-sqlalchemy


【解决方案1】:

该错误意味着User.make_valid_name 是一个实例方法,而不是您所期望的静态方法。如果您想保留现有用法,解决方案是用staticmethod 而不是类来装饰方法

class User(Base):
    ...
    @staticmethod
    def make_valid_name(name):
        return ...

或者,您可以将其改为classmethod

class User(Base):
    ...
    @classmethod
    def make_valid_name(cls, name):
        return ...

【讨论】:

    【解决方案2】:

    唯一的选择是再次创建用户对象并初始化属性,然后将其作为参数而不是直接传递表单对象名称

    user = User(
    name = self.name.data
    )
    
    if self.name.data != User.make_valid_name(user):
    

    在模型中访问相同的方式

    user.name
    

    :@必须重写所有内容。

    任何其他最佳解决方案也将不胜感激。如果其他人将来面临类似的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-07
      • 2017-04-03
      • 2013-12-31
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      相关资源
      最近更新 更多