有时候,我们想要限制访问的请求方法,比如我们希望用户只能通过get
方式请求,post
不允许,那么我们可以采用装饰器的方式,django已经为我们提供了内置的装饰器
Django内置的视图装饰器可以给视图提供一些限制。比如这个视图只能通过GET
的method
访问等。
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
这个列表中,那么就返回HttpResponseNotAllowed
405方法不允许
在源码中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