侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Django Sitemap 站点地图的实现方法

框架(架构)  /  管理员 发布于 7年前   196

Django 中自带了 sitemap框架,用来生成 xml 文件

Sitemap(站点地图)是通知搜索引擎页面的地址,页面的重要性,帮助站点得到比较好的收录。 白话文就是:一个写了你网站的所有url的xml文件,告诉搜索引擎,请及时收录我的这些地址。

sitemap 很重要,可以用来通知搜索引擎页面的地址,页面的重要性,帮助站点得到比较好的收录。

开启sitemap功能的步骤

settings.py 文件中 django.contrib.sitemaps 和 django.contrib.sites 要在 INSTALL_APPS 中

INSTALLED_APPS = (  'django.contrib.admin',  'django.contrib.auth',  'django.contrib.contenttypes',  'django.contrib.sessions',  'django.contrib.messages',  'django.contrib.staticfiles',  'django.contrib.sites',  'django.contrib.sitemaps',  'django.contrib.redirects',     #####  #othther apps  #####)

Django 1.7 及以前版本:

TEMPLATE_LOADERS 中要加入 'django.template.loaders.app_directories.Loader',像这样:

TEMPLATE_LOADERS = (  'django.template.loaders.filesystem.Loader',  'django.template.loaders.app_directories.Loader', )

Django 1.8 及以上版本新加入了 TEMPLATES 设置,其中 APP_DIRS 要为 True,比如:

# NOTICE: code for Django 1.8, not work on Django 1.7 and belowTEMPLATES = [  {    'BACKEND': 'django.template.backends.django.DjangoTemplates',    'DIRS': [      os.path.join(BASE_DIR,'templates').replace('\\', '/'),    ],    'APP_DIRS': True,  },]

然后在 urls.py 中如下配置:

from django.conf.urls import urlfrom django.contrib.sitemaps import GenericSitemapfrom django.contrib.sitemaps.views import sitemap from blog.models import Entry  sitemaps = {  'blog': GenericSitemap({'queryset': Entry.objects.all(), 'date_field': 'pub_date'}, priority=0.6),  # 如果还要加其它的可以模仿上面的} urlpatterns = [  # some generic view using info_dict  # ...   # the sitemap  url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},    name='django.contrib.sitemaps.views.sitemap'),]

但是这样生成的 sitemap,如果网站内容太多就很慢,很耗费资源,可以采用分页的功能:

from django.conf.urls import urlfrom django.contrib.sitemaps import GenericSitemapfrom django.contrib.sitemaps.views import sitemap from blog.models import Entry from django.contrib.sitemaps import views as sitemaps_viewsfrom django.views.decorators.cache import cache_page  sitemaps = {  'blog': GenericSitemap({'queryset': Entry.objects.all(), 'date_field': 'pub_date'}, priority=0.6),  # 如果还要加其它的可以模仿上面的} urlpatterns = [  url(r'^sitemap\.xml$',    cache_page(86400)(sitemaps_views.index),    {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),  url(r'^sitemap-(?P<section>.+)\.xml$',    cache_page(86400)(sitemaps_views.sitemap),    {'sitemaps': sitemaps}, name='sitemaps'),]

这样就可以看到类似如下的 sitemap,如果本地测试访问 http://localhost:8000/sitemap.xml

<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml</loc></sitemap><sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=2</loc></sitemap><sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=3</loc></sitemap><sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=4</loc></sitemap><sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=5</loc></sitemap><sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=6</loc></sitemap><sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=7</loc></sitemap><sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=8</loc></sitemap><sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=9</loc></sitemap></sitemapindex>

查看了下分页是实现了,但是全部显示成了 ?p=页面数,而且在百度站长平台上测试,发现这样的sitemap百度报错,于是看了下 Django的源代码:

在这里 https://github.com/django/django/blob/1.7.7/django/contrib/sitemaps/views.py

于是对源代码作了修改,变成了本站的sitemap的样子,比 ?p=2 这样更优雅

引入 下面这个 比如是 sitemap_views.py

import warningsfrom functools import wraps from django.contrib.sites.models import get_current_sitefrom django.core import urlresolversfrom django.core.paginator import EmptyPage, PageNotAnIntegerfrom django.http import Http404from django.template.response import TemplateResponsefrom django.utils import six def x_robots_tag(func):  @wraps(func)  def inner(request, *args, **kwargs):    response = func(request, *args, **kwargs)    response['X-Robots-Tag'] = 'noindex, noodp, noarchive'    return response  return inner @x_robots_tagdef index(request, sitemaps,     template_name='sitemap_index.xml', content_type='application/xml',     sitemap_url_name='django.contrib.sitemaps.views.sitemap',     mimetype=None):   if mimetype:    warnings.warn("The mimetype keyword argument is deprecated, use "      "content_type instead", DeprecationWarning, stacklevel=2)    content_type = mimetype   req_protocol = 'https' if request.is_secure() else 'http'  req_site = get_current_site(request)   sites = []  for section, site in sitemaps.items():    if callable(site):      site = site()    protocol = req_protocol if site.protocol is None else site.protocol    for page in range(1, site.paginator.num_pages + 1):      sitemap_url = urlresolvers.reverse(          sitemap_url_name, kwargs={'section': section, 'page': page})      absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url)      sites.append(absolute_url)   return TemplateResponse(request, template_name, {'sitemaps': sites},  content_type=content_type) @x_robots_tagdef sitemap(request, sitemaps, section=None, page=1,      template_name='sitemap.xml', content_type='application/xml',      mimetype=None):   if mimetype:    warnings.warn("The mimetype keyword argument is deprecated, use "      "content_type instead", DeprecationWarning, stacklevel=2)    content_type = mimetype   req_protocol = 'https' if request.is_secure() else 'http'  req_site = get_current_site(request)   if section is not None:    if section not in sitemaps:      raise Http404("No sitemap available for section: %r" % section)    maps = [sitemaps[section]]  else:    maps = list(six.itervalues(sitemaps))       urls = []  for site in maps:    try:      if callable(site):        site = site()      urls.extend(site.get_urls(page=page, site=req_site,       protocol=req_protocol))    except EmptyPage:      raise Http404("Page %s empty" % page)    except PageNotAnInteger:      raise Http404("No page '%s'" % page)  return TemplateResponse(request, template_name, {'urlset': urls},  content_type=content_type)

如果还是不懂,可以下载附件查看:zqxt_sitemap.zip

更多参考:

官方文档:https://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Django学习笔记之为Model添加Action
    下一条:
    Django保护敏感信息的方法示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Filament v3.1版本发布(0个评论)
    • docker + gitea搭建一个git服务器流程步骤(0个评论)
    • websocket的三种架构方式使用优缺点浅析(0个评论)
    • ubuntu20.4系统中宿主机安装nginx服务,docker容器中安装php8.2实现运行laravel10框架网站(0个评论)
    • phpstudy_pro(小皮面板)中安装最新php8.2.9版本流程步骤(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2018-05
    • 2020-02
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-11
    • 2021-03
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-08
    • 2023-08
    • 2023-10
    • 2023-12
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客