[英]JsonResponse not setting content-type to application/json using django
[英]Setting Content-Type in Django HttpResponse object for Shopify App
我正在使用Django開發Shopify應用程序,我正在使用nginx和gunicorn在VPS上托管。
我正在嘗試將HttpResponse對象的Content-Type更改為application/liquid
,以便我可以使用Shopify的應用程序代理功能 ,但它似乎不起作用。
以下是我認為是我的代碼的相關部分:
from django.shortcuts import render_to_response, render
from django.http import HttpResponse
from django.template import RequestContext
import shopify
from shopify_app.decorators import shop_login_required
def featured(request):
response = HttpResponse()
response['content_type'] = 'application/liquid; charset=utf-8'
response['content'] = '<html>test123</html>'
response['Content-Length'] = len(response.content)
return response
根據Django文檔 ,我應該設置response[''content_type]
以便在標題中設置Content-Type
。 不幸的是,當我在views.py中找到與此函數對應的URL時,我收到200響應,但Content-Type沒有更改,Content-Length為0.這是我的響應頭:
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 09 Jul 2013 12:26:59 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
X-Request-Id: 2170c81fb16d18fc9dc056780c6d92fd
content: <html>test123</html>
vary: Cookie
content_type: application/liquid; charset=utf-8
P3P: CP="NOI DSP COR NID ADMa OPTa OUR NOR"
如果我將response['content_type']
更改為response['Content-Type']
,我會得到以下標題:
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 09 Jul 2013 12:34:09 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 3097
Connection: keep-alive
X-Request-Id: 76e67e04b753294a3c37c5c160b42bcb
vary: Accept-Encoding
status: 200 OK
x-shopid: 2217942
x-request-id: 6e63ef3a27091c73a9e3fdaa03cc28cb
x-ua-compatible: IE=Edge,chrome=1
p3p: CP="NOI DSP COR NID ADMa OPTa OUR NOR"
content-encoding: gzip
P3P: CP="NOI DSP COR NID ADMa OPTa OUR NOR"
關於如何更改響應的內容類型的任何想法? 這可能是我的nginx或gunicorn配置的問題?
謝謝你的幫助!
請嘗試以下方法:
def featured(request):
content = '<html>test123</html>'
response = HttpResponse(content, content_type='application/liquid')
response['Content-Length'] = len(content)
return response
快速提示,您可以將其添加到NGINX配置的http
或server
塊部分中,這樣您就不必在視圖和其他Django代碼中指定編碼:
charset utf-8;
charset_types text/css application/json text/plain application/liquid;
所以這對我有用:
def featured(request):
response = HttpResponse("", content_type="application/liquid; charset=utf-8")
response['Content-Length'] = len(content)
response.write('<html>test123</html>')
return response
謝謝,大家,求助!
只是為了擴展其他答案,如果HttpResponse
對象已經存在並且在實例化它之后需要設置其MIME類型(例如,在調用父方法時),則可以通過以下方式實現:
response = super(...) # This returns some HttpResponse object
response['Content-Type'] = "application/liquid"
return response
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.