Question

I'm looking for something like Django's csrf_ignore decorator.

I have defined my csrf validation in the usual way, via subscriber:

@subscriber(NewRequest)
def csrf_validation(event):
    ...

Then I have another view which accepts POST images for upload:

@view_config(route_name="upload_images", request_method="POST", renderer="json")
def upload_images(request):
    ...

But how do I ignore csrf validation for the upload_images view? I'm using Pyramid 1.3, if that helps.

Was it helpful?

Solution

Pyramid 1.4 comes with support for a check_csrf predicate on view_config itself. Before that, you would have to implement your own custom predicate that does the checking and apply it to your views.

A NewRequest subscriber happens very early in the request pipeline and many properties are not available to you at this point. For example, it has not yet computed which route matches. Thus you can only really do if not request.path_info.startswith('/upload_image_path'):.

You could defer your check until a ContextFound subscriber, in which case you could check if request.matched_route.name ~= 'upload_images'.

Your best option, however, is to apply the csrf check to individual views explicitly, and this can be done using a custom predicate.

def csrf_check(context, request):
    # do check, return True if passes, or raise some exception if fails

@view_config(..., custom_predicates=[csrf_check])
def not_upload_images(request):
    # ....
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top