how to discriminate based on HTTP method in django urlpatterns

前端 未结 2 779
小鲜肉
小鲜肉 2020-12-29 22:02

I\'m having some difficulties finding information about this, probably it\'s not the right approach. I\'d like to route a request to two different view functions based on th

2条回答
  •  时光说笑
    2020-12-29 22:45

    Because Django allows you to use callables in url config, you can do it with a helper function.

    def method_dispatch(**table):
        def invalid_method(request, *args, **kwargs):
            logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
                extra={
                    'status_code': 405,
                    'request': request
                }
            )
            return HttpResponseNotAllowed(table.keys())
    
        def d(request, *args, **kwargs):
            handler = table.get(request.method, invalid_method)
            return handler(request, *args, **kwargs)
        return d
    

    To use it:

    url(r'^foo',
        method_dispatch(POST = post_handler,
                        GET = get_handler)),
    

提交回复
热议问题