小编Alb*_*t E的帖子

在python装饰器中引发异常是一种很好的模式吗?

上下文:我为不同的API端点定义了Flask路由,每个端点使用某些参数(uid,project_id等)调用控制器类.

@app.route('/sample/route', methods=['POST'])
@require_json_payload
@require_fields({
    'pid',
    'params'
})
def route_handler(arg1, arg2):
    #input filtering
    ...

    try:
        proj_cntr.sample_method(
            pid         = pid,
            ...         = ...
        )
    except ProjCntrException:
        #handle error

    #response generation
    ...
Run Code Online (Sandbox Code Playgroud)

The controller (proj_cntr) is responsible for determining, say, if the given PID is valid, wether the given user is allowed to perform the action, and other business logic validation.

I noticed that I am c/pasting a lot of code like this in different controllers:

if not project_object:
    sys_logger.info('...')
    raise …
Run Code Online (Sandbox Code Playgroud)

python error-handling exception flask

7
推荐指数
1
解决办法
1216
查看次数

标签 统计

error-handling ×1

exception ×1

flask ×1

python ×1