在查看寻ta驿站在谷歌的结果时,发现其有着良好的目录结构,再看看现在的博客,看上去有点乱。或者说现在的sitemap做得很烂:
打开Mezzanine的github,里面有关于这的issues,结果上面写着
While these would be useful, I actually think most people aren't concerned with them and they'd contribute to cluttering the admin, even only slightly.
作者认为这东西不是很重要,或者说优先级不高。。
在Django中,我们添加一个新的Sitemap只需要这样子。
from django.contrib.sitemaps import Sitemap
from blog.models import Entry
class BlogSitemap(Sitemap):
changefreq = "never"
priority = 0.5
def items(self):
return Entry.objects.filter(is_draft=False)
def lastmod(self, obj):
return obj.pub_date
看上去似乎很简单,然而我们需要在Mezzanine中重新修改他们。。
在查看代码的时候发现sitemap.xml
是在urls.py
在是这样配置的
sitemaps = {"sitemaps": {"all": DisplayableSitemap}}
urlpatterns += patterns("django.contrib.sitemaps.views",
("^sitemap\.xml$", "sitemap", sitemaps)
)
最后调用了DisplayableSitemap
,而DisplayableSitemap
函数的代码如下所示
class DisplayableSitemap(Sitemap):
def items(self):
return list(Displayable.objects.url_map(in_sitemap=True).values())
def lastmod(self, obj):
if blog_installed and isinstance(obj, BlogPost):
return obj.updated or obj.publish_date
def get_urls(self, **kwargs):
kwargs["site"] = Site.objects.get(id=current_site_id())
return super(DisplayableSitemap, self).get_urls(**kwargs)
和Django的Sitemap示例一比,果然没有优先级,没有更新频率
新建了一个Django App
.
|______init__.py
|____sitemaps.py
和大多数app一样__init__.py
是空的,而sitemaps.py是从DisplayableSitemap
复制过来的:
添加了一个changefreq
,当对象是不同类型的时候返回不同的值:
def changefreq(obj):
if isinstance(obj, BlogPost):
return "Monthly"
if isinstance(obj, BlogCategory):
return "Weekly"
if isinstance(obj, Page):
return "Weekly"
return "Daily"
以及一个priority
,最高自然是homepage
:
def priority(obj):
if isinstance(obj, BlogPost):
return "0.2"
if isinstance(obj, BlogCategory):
return "0.3"
if isinstance(obj, Page):
return "0.6"
return "1.0"
修改了items,添加了目录
def items(self):
blogpost_with_page = list(Displayable.objects.url_map(in_sitemap=True).values())
category = list(BlogCategory.objects.all())
return blogpost_with_page + category
这样就大功告成了。
最后效果可见http://www.phodal.com/sitemap.xml
代码见:https://github.com/phodal/phodaldev/blob/master/sitemaps/sitemaps.py
围观我的Github Idea墙, 也许,你会遇到心仪的项目