Django Sitemap 站点地图的实现方法
作者:zx 发布时间:2023-05-27 07:40:17
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 below
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR,'templates').replace('\\', '/'),
],
'APP_DIRS': True,
},
]
然后在 urls.py 中如下配置:
from django.conf.urls import url
from django.contrib.sitemaps import GenericSitemap
from 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 url
from django.contrib.sitemaps import GenericSitemap
from django.contrib.sitemaps.views import sitemap
from blog.models import Entry
from django.contrib.sitemaps import views as sitemaps_views
from 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 warnings
from functools import wraps
from django.contrib.sites.models import get_current_site
from django.core import urlresolvers
from django.core.paginator import EmptyPage, PageNotAnInteger
from django.http import Http404
from django.template.response import TemplateResponse
from 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_tag
def 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_tag
def 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/
来源:https://code.ziqiangxuetang.com/django/django-sitemap.html
猜你喜欢
- HTML5,被传为Flash 的杀手,是一种用于web 应用程序开发、具有变革意义的网络技术。HTML 5提供了一些新的元素和属性,其中有些
- 前言损失函数在机器学习中用于表示预测值与真实值之间的差距。一般而言,大多数机器学习模型都会通过一定的优化器来减小损失函数从而达到优化预测机器
- 本文实例介绍了使用javascript来经验表单数据的方法,如:校验是否为英文,校验是否为数字及校验IP地址等: &l
- 我的工作内容可以说是五花八门,策划、文案、设计(包括平面设计、网站设计、VIS设计)、前端代码、交互、测试、摄影、项目管理等。所有这些工作最
- <SCRIPT language="JavaScript"><!-- Beginfunction mo
- 压测时,图片太少,想着下载网页中的图片,然后过滤指定分辨率,但网页中指定分辨率的图片太少了(见下) 后使用格式工厂转换图片import ur
- 前言:WebDriver提供了两个关闭浏览器的方法,一个是前边使用quit()方法,另一个是close()方法close():关闭当前窗口q
- 安装包网盘下载链接:链接: https://pan.baidu.com/s/1TLLeCnNkHtuTiAxHBl39hg 提取码: 9yg
- 大家好,我叫斑马纹列表中使用两种相同的样式但颜色不同的背景,来间隔显示的内容。当然这个释义我是借鉴《designing interfaces
- 在html 5增加了新元素header、footer,测试过发现IE不能解析html 5新增的元素。代码如下:<!DOCTYPE ht
- 本文实例讲述了Python实现的求解最小公倍数算法。分享给大家供大家参考,具体如下:简单分析了一下,前面介绍的最大公约数的求解方法跟最小公倍
- MySQL有多种存储引擎:MyISAM、InnoDB、MERGE、MEMORY(HEAP)、BDB(BerkeleyDB)、EXAMPLE、
- 本文实例讲述了Python简单计算文件MD5值的方法。分享给大家供大家参考,具体如下:一 代码import sysimport hashli
- 本文将介绍在InterDev中实现网上商店购物车功能的方法,具体步骤如下:一、 数据库结构:产品数据表(Products): 存放产品信息产
- 一、设计说明设计这个自动化的目的是想要交替、重复地使用固定的几个分区(分区编号01~05)来保存数据,当最后一个分区就是快满的时候,我们会把
- 由于系统自带的MySQL默认字符集不是gbk,因此给数据库的推广应用以及中文程序的开发带来极大的不便,在没完没了的GBK和UTF8的转换过程
- 微信小程序与php 实现微信支付的简单实例小程序访问地址:payfee.PHP:include 'WeixinPay.php'
- 原理1.使用python中的mtplotlib库。2.立体爱心面公式点画法(实心)代码import matplotlib.pyplot as
- 作者:Roland Smart原文链接:http://www.adaptivepath.com/ideas/newsletter/archi
- 简单的显示记录已经掌握,现在需要的就是通过ASP将信息内容插入到数据库中。一、拥有数据库cnbruce.mdb本数据库的作用就是用来 * 入数