【问题标题】:Django: filtering expected content type?Django:过滤预期的内容类型?
【发布时间】:2016-09-09 09:50:22
【问题描述】:

Django 提供了一种使用 @request_http_method 装饰器来限制接受方法的方法,因此如果特定视图只能响应 GET 请求,我们可以这样做:

@require_http_methods(['GET'])
def only_get(request):
    pass

否则我们会收到 403(禁止)响应。

不过,我也想接受一个Content-Type 的json。如果不是 json,它也应该拒绝请求(我猜 403 响应也是合适的)。

Django 是否有任何类似于 require_http_methods 装饰器的东西,但对于内容类型?如果没有,我还能如何处理这种情况?

【问题讨论】:

    标签: python django


    【解决方案1】:

    我不认为 Django 对 Content-Type 有类似的东西,但是您可以轻松编写中间件,这会丢弃带有错误 Content-Type 的请求,然后使用 decorator_from_middleware 选项。

    如果你使用 Django 1.10:

    class AllowedContentTypes(object):
    
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request, *args, **kwargs):
            types = kwargs.pop('types') or ['application/json']
            if request.content_type in types:
                response = self.get_response(request)
    
            else:
                response = HttpResponse() # your response for wrong content type
            return response 
    

    并将其应用于您的视图,例如:

    @decorator_from_middleware_with_args(AllowedContentTypes)(types=['application/json'])
    def your_view(request):
        ...
    

    此外,您可以使用 Django REST 框架,在那里您可以使用解析器过滤 Content-Type,JSONParser 将只允许 application/json 内容类型的请求。为您的应用实现 REST API 也会更有用。

    【讨论】:

    • 我并没有完全那样做,而是类似的事情,所以我会接受这个答案:)
    猜你喜欢
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 2014-03-11
    • 2015-04-21
    • 1970-01-01
    相关资源
    最近更新 更多