django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

Make http_method_names overrideable per view instance

Open delinhabit opened this issue 13 years ago • 3 comments

Hello,

I'm wondering if we could make the http_method_names property overrideable at runtime to support some special cases. I'm posting this question here (and not on the Django side) because, so far, I felt the need for such a feature only in the context of DRF.

My use case is pretty simple. I have a resource that can be in one of the two possible states: pending or finalized. Based on the resource state I am allowed or not to do some of the CRUD operations. For example finalized resources can only be read and updated but only within a small period after it was finalized. A pending resource can also be deleted. I would like my detail endpoint to reflect this restrictions in the Allow response header and of course in all the locations this property is used.

Is this feasible? Is this a good practice? Any thoughts? I'm willing to work on the patch, but wanted first to discuss about how this should be tackled.

Thanks!

delinhabit avatar Mar 11 '13 08:03 delinhabit

Probably the best bet would be simply to use a custom permission class to achieve the same effect.

That'd be reflected in the browseable API, but not in the 'Allow' header, although you could also modify the behavior of the Allow header easily enough. (Take a look the the implementation of the View class to see how to do that... https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/views.py#L85)

Sound okay?

lovelydinosaur avatar Mar 11 '13 08:03 lovelydinosaur

Yeah! I took a look at the allowed_methods property, but somehow overlooked that the other side of the problem is actually permission related. I'll give it a try.

Thanks!

delinhabit avatar Mar 11 '13 08:03 delinhabit

I managed to implement the behavior I wanted with a custom Permission class and by overriding allowed_methods on the view.

There is a small semantic issue though. When I do a get on the resource, I see that I'm allowed to do only OPTIONS and GET. If I try to do PUT, PATCH or DELETE, I'm getting 403 Forbidden instead of 405 Method Not Allowed, which I think should be returned in this case.

Anyways, I'm able to prevent the consumers to do operations which are not allowed, so I can live with this behavior.

Thanks for your suggestions!

delinhabit avatar Mar 11 '13 10:03 delinhabit