[英]How to set charset header in Django 1.11
we are using Django1.11 and we are having some problems because our header Content-Type
does not contain the charset
part set to UTF-8.我们正在使用 Django1.11 并且我们遇到了一些问题,因为我们的标头Content-Type
不包含设置为 UTF-8 的charset
部分。 Something like this:像这样的东西:
Content-Type: application/json; charset=UTF-8
I want to fix that for all endpoints, so I have thought to include a middleware to run after all midlewares have been run.我想为所有端点修复这个问题,所以我想在所有中间件运行后包含一个要运行的中间件。 The problem is that I do not know if that's possible.问题是我不知道这是否可能。 Any ideas?有任何想法吗? Or alternative solutions?或者替代解决方案?
You can write a custom middleware like this:您可以像这样编写自定义中间件:
from django.utils.deprecation import MiddlewareMixin
class AllIsJsonMiddleware(MiddlewareMixin):
def process_response(self, request, response):
response['Content-Type'] = 'application/json; charset=UTF-8'
return response
But I don't recommend this.但我不推荐这个。 This converts all responses to JSON.这会将所有响应转换为 JSON。 Best use a framework like https://www.django-rest-framework.org/ .最好使用像https://www.django-rest-framework.org/这样的框架。
However, can use a standard view respone...但是,可以使用标准视图响应...
return HttpResponse(data, content_type='application/json; charset=UTF-8')
... or a custom decorator: ...或自定义装饰器:
from functools import wraps
def json_response(function):
@wraps(function)
def wrap(request, *args, **kwargs):
response = function(request, *args, **kwargs)
response['Content-Type'] = 'application/json; charset=UTF-8'
return response
return wrap
@json_response
def my_view(request):
# ....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.