Python kwargs方法的无名位置参数

时间:2017-08-22 06:50:25

标签: python python-3.x flask-restful

我在REST中构造错误响应时使用Flask-RESTful abort()方法。给出的示例具有命名参数message

def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

输出

{
    "message": "Todo asd doesn't exist. You have requested this URI [/todos/asd] but did you mean /todos/<todo_id> or /todos ?"
}

在我的场景中,我已经有了一个自定义异常类型

class InvalidParameter(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, resource=None,
                field=None, code=None, stack_trace=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.resource = resource
        self.field = field
        self.code = code
        self.stack_trace = stack_trace

    def to_dict(self):
        rv = {}
        error = {}
        rv['message'] = self.message
        error['resource'] = self.resource
        error['field'] = self.field
        error['code'] = self.code
        error['stack_trace'] = self.stack_trace
        rv['error'] = error
        return rv

以及错误的JSON响应的特定结构:

{
    "message": "Project name 'GGO' already exist.",
    "error": {
        "resource": "Project",
        "field": "project_name",
        "code": "already_exists",
        "stack_trace": "(psycopg2.IntegrityError) duplicate key value violates unique ..."
    }
}

问题代码

我必须使用两个命名参数

except InvalidParameter as err:
    abort(err.status_code, 
                message=err.to_dict()['message'], 
                error=err.to_dict()['error'])

当我使用它时     除了InvalidParameter为错误:         中止(err.status_code,err.to_dict())

我收到错误

TypeError: abort() takes 1 positional argument but 2 were given // Werkzeug Debugger

如何将整个err dict作为参数传递?

0 个答案:

没有答案