Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 关于金字塔视图异常处理的建议_Python_Exception_Web Applications_Pyramid - Fatal编程技术网

Python 关于金字塔视图异常处理的建议

Python 关于金字塔视图异常处理的建议,python,exception,web-applications,pyramid,Python,Exception,Web Applications,Pyramid,当我需要处理异常时,有三种情况 当数据验证引发异常时 库/模块功能引发异常时(例如数据库连接中止) 当业务逻辑引发异常时,例如500、503、401、403和404 def library_func(): try: ... except HTTPException: raise TwitterServiceException("Twitter is down!") @view_config(route_name="home", renderer=

当我需要处理异常时,有三种情况

当数据验证引发异常时

库/模块功能引发异常时(例如数据库连接中止)

当业务逻辑引发异常时,例如500、503、401、403和404

def library_func():
    try:
        ...
    except HTTPException:
        raise TwitterServiceException("Twitter is down!")

@view_config(route_name="home", renderer="json")
@validator
@authorization
def home_view(request):
        try:
            tweets = library_func()
            return {"tweets": tweets}
        except TwitterServiceException as e:
            LOG.critical(e.msg)
            raise ParnterServcieError(e.msg)  # this is probably a 503 error

def validator(args):
    # I will show the high level of this decorator
    try:
         decode input as JSON
         verify data format
    except ValueError as err:
        error = {'error': "Missing required parameters."}
    except json.JSONDecodeError as err:
        error = {'error': "Failed to decode the incoming JSON payload."}
    if error is not None:
        return HTTPBadRequest(body=json.dumps(error),
                              content_type='application/json')

def authorization(args):
    # very similar to validator except it performs authorization and if failed
    # 401 is raised with some helpful message.
医生建议。在上面的PoC中,我将把
ParnterServcieError
绑定为一个。我甚至可以使用自定义异常来概括
HTTPBadRequest
和所有
praymid.httpexceptions
,这样我就不再需要重复
json.dumps
content\u type
。我可以在返回
request.response
对象之前设置样板文件
error
body

想法:

我可以为所有未捕获、未指定的异常(导致500个内部服务器错误)概括一个名为
500\u Internal\u Server\u Error\u view


这对人们来说是明智和干净的吗?我处理高级别和低级别异常的方法正确吗?是Pythonic吗?

我将此策略应用于ToDoPyramid,并可以将错误处理封装在一个自定义异常视图中,该视图以前在应用程序中重复多次。直到你能改进它,你才有了一个好主意。金字塔岩石

参考资料

@view_config(context=ParnterServcieError)
def 503_service_error_view(e, request):
    request.response.status = 503
    request.response.json_body = {"error": e.msg}
    return request.response