【问题标题】:How to raise an exception if json parameter is not having value (empty string)?如果 json 参数没有值(空字符串),如何引发异常?
【发布时间】:2019-11-04 11:17:56
【问题描述】:

如果我的输入 json 看起来像这样,我想引发一个异常:

{
"username":"user",
"password": ""
}

如果我将密码作为 null 传递,那么我想引发异常。我可以知道棉花糖是怎么处理的吗? 我不想像下面这样明确检查:

request_jsn = request.get_json()
if 'password' in request_jsn.keys() :
   if request_jsn['password'] :
     password = request_jsn['password']
from marshmallow import Schema, fields
class UserSchema(Schema):
username = fields.String(required=True)
password = fields.String(required=True)
--------------
def post(self):

    if not request.json:
        return jsonify( {'msg':"Unsupported media type,Requests must be JSON",'code': 415})
    try:
       request_jsn =  Schema().load(request.get_json())
    except ValidationError as e:
        return jsonify(error_dict(current_request_id(), str(e), 400))

【问题讨论】:

  • 我有办法使用它。 username = fields.String(required=True, validate=validate.Length(min=1, error="Field should not be empty.")) password = fields.String(required=True, validate=validate.Length(min= 1、error="字段不能为空。"))
  • 这确实是要走的路。你应该把它写成答案并接受它。

标签: python python-3.x flask json-schema-validator marshmallow


【解决方案1】:

我有办法使用它。

username = fields.String(required=True, validate=validate.Length(min=1, error="Field should not be empty.")) 
password = fields.String(required=True, validate=validate.Length(min=1, error="Field should not be empty.")

【讨论】:

    猜你喜欢
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多