- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
使用 flask_marshmallow 进行输入验证,使用 scheme.load() ,我无法捕获模型中 @validates 装饰器生成的错误
我在资源中捕获了结果和错误,但错误直接发送给用户
```python
from sqlalchemy.orm import validates
from sqlalchemy import Column, ForeignKey, Integer, String, DateTime
from sqlalchemy.orm import relationship, backref
from sqlalchemy import create_engine
from sqlalchemy.sql import func
from flask_marshmallow import Marshmallow
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from sqlalchemy.orm import joinedload
db = SQLAlchemy()
ma = Marshmallow()
class Company(db.Model):
__tablename__ = "company"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(250), nullable=False)
addressLine1 = db.Column(db.String(250), nullable=False)
addressLine2 = db.Column(db.String(250), nullable=True)
city = db.Column(db.String(250), nullable=False)
state = db.Column(db.String(250), nullable=False)
zipCode = db.Column(db.String(10), nullable=False)
logo = db.Column(db.String(250), nullable=True)
website = db.Column(db.String(250), nullable=False)
recognition = db.Column(db.String(250), nullable=True)
vision = db.Column(db.String(250), nullable=True)
history = db.Column(db.String(250), nullable=True)
mission = db.Column(db.String(250), nullable=True)
jobs = relationship("Job", cascade="all, delete-orphan")
def save_to_db(self):
db.session.add(self)
db.session.commit()
@validates('name')
def validate_name(self, key, name):
print("=====inside validate_name=======")
if not name:
raise AssertionError('No Company name provided')
if Company.query.filter(Company.name == name).first():
raise AssertionError('Company name is already in use')
if len(name) < 4 or len(name) > 120:
raise AssertionError('Company name must be between 3 and 120 characters')
return name
```
```python
from ma import ma
from models.model import Company
class CompanySchema(ma.ModelSchema):
class Meta:
model = Company
```
```python
from schemas.company import CompanySchema
company_schema = CompanySchema(exclude='jobs')
COMPANY_ALREADY_EXIST = "A company with the same name already exists"
COMPANY_CREATED_SUCCESSFULLY = "The company was sucessfully created"
@api.route('/company')
class Company(Resource):
def post(self, *args, **kwargs):
""" Creating a new Company """
data = request.get_json(force=True)
schema = CompanySchema()
if data:
logger.info("Data got by /api/test/testId methd %s" % data)
# Validation with schema.load() OPTION_2
company, errors = schema.load(data)
print(company)
print(errors)
if errors:
return {"errors": errors}, 422
company.save_to_db()
return {"message": COMPANY_CREATED_SUCCESSFULLY}, 201
```
这是来自用户的POST请求
{
"name": "123",
"addressLine1": "400 S Royal King Ave",
"addressLine2": "Suite 356",
"city": "Miami",
"state": "FL",
"zipCode": "88377",
"logo": "This is the logo",
"website": "http://www.python.com",
"recognition": "Most innovated company in the USA 2018-2019",
"vision": "We want to change for better all that needs to be changed",
"history": "Created in 2016 with the objective of automate all needed process",
"mission": " Our mission is to find solutions to old problems"
}
====问题描述======
上面的 POST 请求根据 model.py 中的 validate_name 函数生成一个 AssertionError 异常,如下所示:
File "code/models/model.py", line 95, in validate_name
raise AssertionError('Company name must be between 3 and 120 characters')
AssertionError: Company name must be between 3 and 120 characters
127.0.0.1 - - [30/Dec/2018 13:44:58] "POST /api/company HTTP/1.1" 500 -
所以返回给用户的响应就是这个无用的错误信息
{
"message": "Internal Server Error"
}
我的问题是:
我必须做什么才能将引发的 AssertionError 消息发送给用户,而不是这个难看的错误消息?
AssertionError message
{
"message": "Company name must be between 3 and 120 characters"
}
Exception
{
"message": "Internal Server Error"
}
我以为错误会捕获@validates('name') 生成的异常,但看起来并非如此。
最佳答案
我找到了解决问题的办法。我更改了架构如下:
from ma import ma
from models.model import Company
from marshmallow import fields, validate
class CompanySchema(ma.ModelSchema):
name = fields.Str(required=True, validate=[validate.Length(min=4, max=250)])
addressLine1 = fields.Str(required=True, validate=[validate.Length(min=5, max=250)])
addressLine2 = fields.Str(required=False, validate=[validate.Length(max=250)])
city = fields.Str(required=True, validate=[validate.Length(min=5, max=100)])
state = fields.Str(required=True, validate=[validate.Length(min=2, max=10)])
zipCode = fields.Str(required=True, validate=[validate.Length(min=5, max=250)])
logo = fields.Str(required=False, validate=[validate.Length(max=250)])
website = fields.Str(required=True, validate=[validate.Length(min=5, max=250)])
recognition = fields.Str(required=False, validate=[validate.Length(max=250)])
vision = fields.Str(required=False, validate=[validate.Length(max=250)])
history = fields.Str(required=False, validate=[validate.Length(max=250)])
mission = fields.Str(required=False, validate=[validate.Length(max=250)])
class Meta:
model = Company
现在我不验证模型中的任何内容,所以我的模型只是
class Company(db.Model):
__tablename__ = "company"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(250), nullable=False)
addressLine1 = db.Column(db.String(250), nullable=False)
addressLine2 = db.Column(db.String(250), nullable=True)
city = db.Column(db.String(250), nullable=False)
state = db.Column(db.String(250), nullable=False)
zipCode = db.Column(db.String(10), nullable=False)
logo = db.Column(db.String(250), nullable=True)
website = db.Column(db.String(250), nullable=False)
recognition = db.Column(db.String(250), nullable=True)
vision = db.Column(db.String(250), nullable=True)
history = db.Column(db.String(250), nullable=True)
mission = db.Column(db.String(250), nullable=True)
jobs = relationship("Job", cascade="all, delete-orphan")
def save_to_db(self):
print("=====inside save_to_db=======")
db.session.add(self)
db.session.commit()
所以在资源( View )端点中,我有:
@api.route('/company')
class Company(Resource):
def post(self, *args, **kwargs):
""" Creating a new Company """
data = request.get_json(force=True)
schema = CompanySchema()
if data:
logger.info("Data got by /api/test/testId method %s" % data)
# Validation with schema.load() OPTION_2
company, errors = schema.load(data)
print(company)
if errors:
return {"errors": errors}, 422
company.save_to_db()
return {"message": COMPANY_CREATED_SUCCESSFULLY}, 201
因此,现在当用户使用少于 4 个字符的名称发出错误请求时,我能够向用户返回一个漂亮的错误响应,如下所示
{
"errors": {
"name": [
"Length must be between 4 and 250."
]
}
}
但是如果您注意到我这样做的原因以及我使用的“模式”,您将看到以下详细信息
谢谢
关于python - Flask_Marshmallow 的 Flask sqlAlchemy 验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53980885/
我正在尝试创建一个使用 UUID 作为主键的用户模型: from src.db import db # SQLAlchemy instance import sqlalchemy_utils impo
在 sqlalchemy 中,我试图合并表,然后使用 WHERE 和 ORDER_BY 创建别名 有点像 SELECT * FROM ( SELECT [TABLE_ONE].[SOME_ID]
我正在使用 SQL Alchemy(通过 Flask_sqlalchemy)将 Python 字典列表插入到 Postgres 数据库中。 其中一个表是所有唯一项目的列表(表 1),而第二个是与某个项
This source详细说明如何使用关联代理创建具有 ORM 对象值的 View 和对象。 但是,当我附加一个与数据库中现有对象匹配的值(并且所述值是唯一的或主键)时,它会创建一个冲突的对象,因此我
SQLAlchemy Core和SQLAlchemy ORM的目的有什么区别? 最佳答案 顾名思义,ORM是一个对象关系映射器:其目的是将数据库关系表示为Python对象。 核心是查询构建器。其目的是
带有ForeignKey的Column是否自动创建索引? 还是我需要手动添加index=True? some_field = Column(Integer, ForeignKey(SomeModel.
我有一个主数据库,每个客户自己的数据库连接存储在其中。 因此,每个客户端都使用2个db:main和它自己的db,必须确定其连接 对于每个http调用。我如何使用flask-sqlalchemy扩展名执
当我仅对类进行继承时,它才起作用 class User(Base): __tablename__ = ’users’ id = Column(Integer, primary_key=
从用户的角度来看,SQLAlchemy 的查询日志似乎有点过于冗长,有时甚至有点神秘: 2015-10-02 13:51:39,500 INFO sqlalchemy.engine.base.Engi
我正在尝试使用 wtforms.ext.sqlalchemy QuerySelectMultipleField 显示复选框列表,但我无法在 GET 的表单上显示模型数据。 这是我的models.py
我想为查询返回一个中继连接。使用标准的 graphene-sqlalchemy 你可以这样做: class Query(graphene.ObjectType): node = relay.N
我在 centos 7.5 虚拟机上部署了最新的 Airflow ,并将 sql_alchemy_conn 和 result_backend 更新到 postgresql 实例上的 postgres
我想将多个项目插入到一个表中,并在发生冲突时更新该表。这是我想出的以下内容 from sqlalchemy.dialects.postgresql import insert meta = MetaD
我有以下模型: class Item(Base): a = relationship() b = relationship() c = relationship() d
我有 presto 和 superset 设置。 presto 运行良好,可以通过命令访问: ./app/hadoop/setjdk8.sh;bin/presto-cli --server http:
我一直在寻找一种在 sqlalchemy 中使用 tsvector 的方法(就像 INTEGER 等其他方法一样),但到目前为止我还不清楚如何做到这一点。我读过可以使用 UserDefinedType
我正在使用 sqlalchemy(现在使用 sqlite,但稍后可能会改变)来构建一个数据库,其中插入的顺序和 rowids 很重要。我基本上有以下几点: class Message(Base):
给定一个对象,我想知道如何知道它是否是 sqlalchemy 映射模型的实例。 通常,我会使用 isinstance(obj, DeclarativeBase)。但是,在这种情况下,我没有可用的 De
我已经通读了查询文档,如果有办法从查询中获取表名,就看不到任何地方 - 例如如果我有 q = query(Users) ,我可以得到Users从 q 退出? 最佳答案 请注意,像您这样的事件简单查询可
我不确定如何定义create schema foo迁移?我的模型如下所示(我正在使用Flask-Migrate): class MyTable(db.Model): __tablename__
我是一名优秀的程序员,十分优秀!