Search code examples
pythonviewconfigpyramid

How to have Pyramid invoke_subrequest to go through view_config context routing for error handling


We are using request.invoke_subrequest() to run a view from Python code.

We would like the subrequests responses to go through the views defined for errors (context routing).

For example, if we define several error views like this one:

@view_config(context=requests.exceptions.HTTPError)
def response_error(context, request):
    if context.response.status_code == 412:
        return httpexceptions.HTTPPreconditionFailed()
    # [...]

How do you execute it when using subrequests for each kind of context without having to add an except close for each kind?

Ideally, we'd like to obtain something like that (e.g. imaginary view_lookup() function):

try:
    subresp = request.invoke_subrequest(subrequest)
except Exception as e:
    subresp = view_lookup(e)(subrequest)

Using use_tweens=True in invoke_subrequest() doesn't seem to execute the error views either.

Is there a way to explicitly call a view lookup so that we obtain the subresponse as if it would have gone through view_config errors handlers?


Solution

  • What you are looking for is probably: pyramid.view.render_view_to_response

    from pyramid.view import render_view_to_response
    
    try:
        subresp = request.invoke_subrequest(subrequest)
    except Exception as e:
        subresp = render_view_to_response(e, subrequest)