Django Sitemap 站點(diǎn)地圖的實(shí)現(xiàn)方法
Django 中自帶了 sitemap框架,用來(lái)生成 xml 文件
Sitemap(站點(diǎn)地圖)是通知搜索引擎頁(yè)面的地址,頁(yè)面的重要性,幫助站點(diǎn)得到比較好的收錄。 白話文就是:一個(gè)寫了你網(wǎng)站的所有url的xml文件,告訴搜索引擎,請(qǐng)及時(shí)收錄我的這些地址。
sitemap 很重要,可以用來(lái)通知搜索引擎頁(yè)面的地址,頁(yè)面的重要性,幫助站點(diǎn)得到比較好的收錄。
開(kāi)啟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 設(shè)置,其中 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,如果網(wǎng)站內(nèi)容太多就很慢,很耗費(fèi)資源,可以采用分頁(yè)的功能:
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,如果本地測(cè)試訪問(wèn) 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>
查看了下分頁(yè)是實(shí)現(xiàn)了,但是全部顯示成了 ?p=頁(yè)面數(shù),而且在百度站長(zhǎng)平臺(tái)上測(cè)試,發(fā)現(xiàn)這樣的sitemap百度報(bào)錯(cuò),于是看了下 Django的源代碼:
在這里 https://github.com/django/django/blob/1.7.7/django/contrib/sitemaps/views.py
于是對(duì)源代碼作了修改,變成了本站的sitemap的樣子,比 ?p=2 這樣更優(yōu)雅
引入 下面這個(gè) 比如是 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/
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
numpy中的transpose函數(shù)中具體使用方法
本文主要介紹了numpy中的transpose函數(shù)中具體使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
Python如何獲得百度統(tǒng)計(jì)API的數(shù)據(jù)并發(fā)送郵件示例代碼
這篇文章主要給大家介紹了關(guān)于Python如何獲得百度統(tǒng)計(jì)API的數(shù)據(jù)并發(fā)送郵件的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
Python實(shí)現(xiàn)的HTTP并發(fā)測(cè)試完整示例
這篇文章主要介紹了Python實(shí)現(xiàn)的HTTP并發(fā)測(cè)試,涉及Python多線程并發(fā)操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-05-05
pandas刪除某行或某列數(shù)據(jù)的實(shí)現(xiàn)示例
本文主要介紹了pandas刪除某行或某列數(shù)據(jù)的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
用python3讀取python2的pickle數(shù)據(jù)方式
今天小編就為大家分享一篇用python3讀取python2的pickle數(shù)據(jù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
tensorflow-gpu安裝的常見(jiàn)問(wèn)題及解決方案
這篇文章主要介紹了tensorflow-gpu安裝的常見(jiàn)問(wèn)題及解決方案,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧,需要的朋友可以參考下2020-01-01

