在瓶子中进行DRY验证?

我的Bottle应用程序不是非常干燥,这是一个测试用例:

from uuid import uuid4
from bottle import Bottle, response

foo_app = Bottle()

@foo_app.post('/foo')
def create():
    if not request.json:
        response.status = 400
        return {'error': 'ValidationError', 'error_message': 'Body required'}
    body = request.json
    body.update({'id': uuid4().get_hex())
    # persist to db
    # ORM might set 'id' on the Model layer rather than setting it here
    # ORM will validate, as will db, so wrap this in a try/catch
    response.status = 201
    return body

@foo_app.put('/foo/<id>')
def update(id):
    if not request.json:
        response.status = 400
        return {'error': 'ValidationError', 'error_message': 'Body required'}
    elif 'id' not in request.json:
        response.status = 400
        return {'error': 'ValidationError', 'error_message': '`id` required'}
    db = {} # should be actual db cursor or whatever
    if 'id' not in db:
        response.status = 404
        return {'error': 'Not Found',
                'error_message': 'Foo `id` "{id}" not found'.format(id)}
    body = request.json
    # persist to db, return updated object
    # another try/catch here in case of update error (from ORM and/or db)
    return body

解决此问题的一种方法是拥有全局错误处理程序,并在各处引发错误。

另一个是使用装饰器,它也有开销问题。

有没有更好的方法来进行每条路线的验证?-我在想类似的东西:

foo_app.post('/foo', middleware=[HAS_BODY_F, ID_IN_DB_F])

最终找到了Bottle的内置“中间件”,称为“插件”(参考):

from bottle import Bottle, request, response

app = Bottle()


def has_body(f):
    def inner(*args, **kwargs):
        if request.json:
            return f(*args, **kwargs)

        response.status = 400
        return {'error': 'ValidationError',
                'error_message': 'Body is required (and must be JSON).'}
    return inner


def body_req(required):
    def body_req_middleware(f):
        def inner(*args, **kwargs):
            intersection = required.intersection(set(request.json.keys()))
            if intersection != required:
                response.status = 400
                return {'error': 'ValidationError',
                        'error_message': 'Key(s): {} are not in JSON payload'
                        ''.format(', '.join('{!r}'.format(k)
                                            for k in required - intersection))}
            return f(*args, **kwargs)
        return inner
    return body_req_middleware


@app.post('/foo', apply=(has_body, body_req({'id', 'f'})))
def get_foo():
    return {'foo': 'bar'}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在AngularJS中进行DRY

来自分类Dev

在Rails中进行验证

来自分类Dev

在Spring中进行表单验证

来自分类Dev

在循环中进行验证?

来自分类Dev

在Scala中进行尝试,验证和验证

来自分类Dev

在python和C ++中进行高效的DRY双向查找

来自分类Dev

在ng-repeat中进行验证的表格

来自分类Dev

在Oracle中进行数据验证

来自分类Dev

在redux中的reducer中进行验证

来自分类Dev

如何在$ ionicPopup中进行验证?

来自分类Dev

如何在Android应用中进行验证

来自分类Dev

使用ngRepeat在Angular中进行分组验证

来自分类Dev

使用Java在XPages中进行验证

来自分类Dev

如何在Cakephp中进行表单验证?

来自分类Dev

如何在PowerShell中进行验证过程?

来自分类Dev

如何在React中进行表单验证?

来自分类Dev

如何避免在SaveFileDialog中进行权限验证?

来自分类Dev

如何在InertiaJS中进行表单验证

来自分类Dev

始终无法在Yii中进行验证

来自分类Dev

如何在Android应用中进行验证

来自分类Dev

使用ngRepeat在Angular中进行分组验证

来自分类Dev

在datePicker文本框中进行验证

来自分类Dev

在没有插件的Jquery中进行验证

来自分类Dev

无法在JS中进行表单验证

来自分类Dev

Python:在代码中进行较早的验证

来自分类Dev

在expressJS应用中进行身份验证

来自分类Dev

在域服务的域模型中进行验证?

来自分类Dev

如何在Cakephp中进行表单验证?

来自分类Dev

在symfony 1.4中进行验证