![](/img/trans.png)
[英]Python/Django REST Framework POST based on Content-Type header
[英]Django: RSS and ATOM feeds Content-Type header?
我遵循了本教程的django的RSS和ATOM提要,並使其正常工作。
但是,測試開發服務器會繼續讓瀏覽器將提要下載為文件,而不是瀏覽器將提要檢測為xml文檔。
我對HTTP的經驗告訴我,Content-Type標頭中缺少mime類型。
如何在Django中指定呢?
Everyblock源代碼中對此有一個注釋。
他們定義了一個類來替換標准Django feed的mime類型,如下所示:
# RSS feeds powered by Django's syndication framework use MIME type
# 'application/rss+xml'. That's unacceptable to us, because that MIME type
# prompts users to download the feed in some browsers, which is confusing.
# Here, we set the MIME type so that it doesn't do that prompt.
class CorrectMimeTypeFeed(Rss201rev2Feed):
mime_type = 'application/xml'
# This is a django.contrib.syndication.feeds.Feed subclass whose feed_type
# is set to our preferred MIME type.
class EbpubFeed(Feed):
feed_type = CorrectMimeTypeFeed
您是否正在使用RSS的可用視圖? 這是我在urls.py中擁有的內容-我沒有對mimetypes進行任何設置:
urlpatterns += patterns('',
(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': published_feeds}, 'view_name')`,
)
哪里發布_提要是這樣的
class LatestNewsFeed(Feed):
def get_object(self, bits):
pass
def title(self, obj):
return "Feed title"
def link(self, obj):
if not obj:
return FeedDoesNotExist
return slugify(obj[0])
def description(self, obj):
return "Feed description"
def items(self, obj):
return obj[1]
published_feeds = {'mlist': LatestNewsFeed}
創建HTTPReponse對象時,可以指定其內容類型:
HttpResponse(content_type='application/xml')
或實際上是什么內容類型。
參見http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponse.__init__
我想問題出在OS X上的Camino瀏覽器,而不是HTTP標頭和mime類型。
當我嘗試使用Safari時,它起作用了。
9年后的Firefox和Django 2.1,我仍然遇到此問題。
上面的解決方案並沒有解決它,所以我最終使用了這個:
class XMLFeed(Feed):
def get_feed(self, obj, request):
feedgen = super().get_feed(obj, request)
feedgen.content_type = 'application/rss+xml; charset=utf-8' # New standard
# feedgen.content_type = 'application/xml; charset=utf-8' # Old standard, left here for reference
return feedgen
使用此類而不是Feed
將mime類型設置為'application / rss + xml'。
更新資料
引起我注意的是,MIME類型的“ application / xml”已過時,應改為使用“ application / rss + xml”。 上面的代碼已相應更新,但尚未經過測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.