Blog

Blog

PHODAL

Django & Mezzanine Sitemap 扩展

在查看寻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

在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中重新修改他们。。

Mezzanine Sitemap

原始Mezzanine Sitemap

在查看代码的时候发现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示例一比,果然没有优先级,没有更新频率

Mezzanine Sitemap Extend

新建了一个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: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签