Django(23)Django限制请求装饰器

前言

有时候,我们想要限制访问的请求方法,比如我们希望用户只能通过get方式请求,post不允许,那么我们可以采用装饰器的方式,django已经为我们提供了内置的装饰器
 

限制请求装饰器

Django内置的视图装饰器可以给视图提供一些限制。比如这个视图只能通过GETmethod访问等。
django.http.decorators.http.require_http_methods装饰器方法的路径,接下来我们看下它的源码

def require_http_methods(request_method_list):
    """
    Decorator to make a view only accept particular request methods.  Usage::

        @require_http_methods(["GET", "POST"])
        def my_view(request):
            # I can assume now that only GET or POST requests make it this far
            # ...

    Note that request methods should be in uppercase.
    """
    def decorator(func):
        @wraps(func)
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                response = HttpResponseNotAllowed(request_method_list)
                log_response(
                    'Method Not Allowed (%s): %s', request.method, request.path,
                    response=response,
                    request=request,
                )
                return response
            return func(request, *args, **kwargs)
        return inner
    return decorator

上述装饰器的含义是如果请求方法不在request_method_list这个列表中,那么就返回HttpResponseNotAllowed405方法不允许
 
在源码中django又定义了3个属性

require_GET = require_http_methods(["GET"])
require_GET.__doc__ = "Decorator to require that a view only accepts the GET method."

require_POST = require_http_methods(["POST"])
require_POST.__doc__ = "Decorator to require that a view only accepts the POST method."

require_safe = require_http_methods(["GET", "HEAD"])
require_safe.__doc__ = "Decorator to require that a view only accepts safe methods: GET and HEAD."

上述代码django又帮助我们定义好了只允许GET方法,只允许POST方法,只允许GET和HEAD方法,了解完源码后,我们就可以开始实操了
 

实战案例

我们创建一个视图,导入装饰器,定义一个index函数,在函数上加上一个require_GET装饰器,代码如下

from django.views.decorators.http import require_http_methods, require_GET, require_POST
from django.http import HttpResponse


@require_POST  
def index(request):
    return HttpResponse('success')

接下来我们访问这个视图,可以从PyCharm的控制台清楚的看到,返回的是405

Method Not Allowed (GET): /
[21/May/2021 02:08:05] "GET / HTTP/1.1" 405 0

接下来我们使用require_http_methods方法来给大家演示,代码如下

require_http_methods(['GET'])
def index1(request):
    return HttpResponse('success')

接下来我们通过网页访问,可以看到是可以正常访问的

[21/May/2021 02:20:59] "GET / HTTP/1.1" 200 7
上一篇:filter的简洁写法


下一篇:翻译:《实用的Python编程》04_03_Special_methods