gpt4 book ai didi

python - Flask_Marshmallow 的 Flask sqlAlchemy 验证问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:23:29 25 4
gpt4 key购买 nike

使用 flask_marshmallow 进行输入验证,使用 scheme.load() ,我无法捕获模型中 @validates 装饰器生成的错误

我在资源中捕获了结果和错误,但错误直接发送给用户

==========model.py==========

```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

```

==========schemas_company.py==============

```python
from ma import ma
from models.model import Company


class CompanySchema(ma.ModelSchema):

class Meta:
model = Company
```

=============resources_company.py

```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."
]
}
}

但是如果您注意到我这样做的原因以及我使用的“模式”,您将看到以下详细信息

  1. -使用 flask_marshmallow 进行序列化和反序列化。
  2. -在我的模型中,我使用棉花糖(不是 flask_marshmallow)进行验证
  3. -验证与 schema.load() 一起工作
  4. -我想知道如何才能向输入添加比我使用的验证更复杂的验证?
  5. -这是一个值得遵循的好模式吗,可以做哪些改进?

谢谢

关于python - Flask_Marshmallow 的 Flask sqlAlchemy 验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53980885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com