2

我对 SQLAlchemy 比较陌生。

我有一个非常简单的使用 sqlalchemy 装饰器model的自定义函数:@validates

class User(db.Model):
  ...
  email = db.Column(db.String(255)) # don't worry about uniqueness for now

  @validates('email')
  def validate_email(self, key, address):
    assert '@' in address # of course a regex is better, I know
    return address

然后:

try:
  user = User('fidel#cuba.cu')
  db.session.add(user)
  db.session.commit()
except Exception as e:
  print e.message # returns an empty string ''

我想做的事:

...
except Exception as e:
  # json_error is a custom function of my own 
  return json_error(e.message, 400) 

所以问题是:如何将自定义错误消息附加到 SQLAlchemy 中的自定义验证规则?也许我需要创建一个包含消息的自定义异常?

4

1 回答 1

4

断言可以接受第二个参数 - 断言失败时使用的消息:

class User(db.Model):
  # ... snip ...

  @validates('email')
  def validate_email(self, key, address):
    assert '@' in address, "Invalid email"
    return address
于 2012-10-03T13:33:36.327 回答