如何在python中处理非预期的请求方法?

Jan*_*and 0 django

假设我有一个应该只响应GET请求的视图:

def myview(request, topic_id):
    if request.method == "GET": 
         #do something
         #return  some url 
   else:
         #What should I do here to have the least performance or security issues?
Run Code Online (Sandbox Code Playgroud)

Ben*_*Ben 5

您可以使用Django提供的装饰器来限制允许的方法类型:

from django.views.decorators import require_GET

@require_GET
def myview(request, topic_id):
    # Guaranteed to be GET only
Run Code Online (Sandbox Code Playgroud)

Django将为任何其他方法引发405 Method Not Allowed.

有关更多信息,请参阅文档.