Return 405 or 404 for OPTIONS http requests

1k Views Asked by At

Example:

  • We provide a URL http://.../foo/download.csv
  • web client (MS office) opens above URL and tries to access (for reasons I really don't know) http://.../foo/ with an http OPTIONS request.
  • Up to now or app returns 404 since the above URL does not exist (even for GET requests).

I think All OPTIONS requests should get a 405. It should not matter if the URL would be accessible via GET or POST.

Does this match the http spec?

Here is my explanation why I think 405 fits better: If there is an OPTIONS request, I don't want to look at the path. I don't care what the path looks like, there should always be the same answer: Not allowed.

Up to now it depends: if there is a GET-view registered, then we return 405. Otherwise a 404 gets returned.

Update: 404 vs 405

HTTP-Spec 405 Method Not Allowed

The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.

Source: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6

1

There are 1 best solutions below

0
Withnail On

It's not really clear why you want it to return a 405, to be honest. It'll never get as far as checking the method, because the 404 handler will be invoked first - there's no view logic for it to get, that's what the 404 is. This is the default, and correct, behaviour.

I suspect, if you don't want to write custom middleware for it, and you insist on implementing it, that overriding the 404 handler would be the way forward - if a 404 Handler is invoked, check the method and return that accordingly - this is messy though, and the custom middleware would be more pythonic.

def handler404(request): 
    if request.method == 'OPTION': 
        #return your custom 405 response
    else: 
        #go on and do your regular 404.