mercredi 23 octobre 2019

Request method mapping is happening after permission check

So, this issue(may not be as issue and error from my side) is something that i faced while testing of my class based views. I had a view that creates and updates user as shown below.

class UserViewSet(ViewSet):
    def check_permissions(self, request):
        print("Action = ", self.action)
        if self.action == 'create_user':
            return True
        return super().check_permissions(request)

    def create_user(self, request):
    # user creation code

    def update(self, request):    
    #user update code

And create_user was mapped with POST method and update was mapped with PUT method. So, my need was that for create_user action no permission is required and for update, user should be authenticated. Overriding check_permssion did the job. Now, when i was testing the create_user end point. I wrote a test that tries to create user using some method other than POST. I expected that the response should be HTTP_405_METHOD_NOT_ALLOWED.

def test_create_user_with_invalid_method(self):
    data = self.user_data
    response = self.client.put(self.url, data)
    self.assertEqual(response.status_code, HTTP_405_METHOD_NOT_ALLOWED)

But the response was HTTP_401_UNAUTHORIZED. And the action variable was set as None. My url mapping is like this:

url(r'^account/register/$', UserViewSet.as_view({"post": "create_user"}),name="account_register_view"),
url(r'^account/update/$', UserViewSet.as_view({"put": "update"}), name="account_update_vew"),

So looking at this, i thought djago is either doing the mapping of request(method, url) to action either after checking permission or doing it before but setting action as None when it fails to find the proper mapping

So my concern is that whether this is the correct behaviour and the test i wrote and what i was expecting is wrong or is there something strange going on here.

PS: Please ignore my grammatical mistaks.

Thanks

Aucun commentaire:

Enregistrer un commentaire