测试gitnore
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
import warnings
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import urlopen
|
||||
|
||||
@@ -8,7 +7,6 @@ from django.core import paginator
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.urls import NoReverseMatch, reverse
|
||||
from django.utils import translation
|
||||
from django.utils.deprecation import RemovedInDjango50Warning
|
||||
|
||||
PING_URL = "https://www.google.com/webmasters/tools/ping"
|
||||
|
||||
@@ -25,37 +23,32 @@ def ping_google(sitemap_url=None, ping_url=PING_URL, sitemap_uses_https=True):
|
||||
function will attempt to deduce it by using urls.reverse().
|
||||
"""
|
||||
sitemap_full_url = _get_sitemap_full_url(sitemap_url, sitemap_uses_https)
|
||||
params = urlencode({"sitemap": sitemap_full_url})
|
||||
urlopen("%s?%s" % (ping_url, params))
|
||||
params = urlencode({'sitemap': sitemap_full_url})
|
||||
urlopen('%s?%s' % (ping_url, params))
|
||||
|
||||
|
||||
def _get_sitemap_full_url(sitemap_url, sitemap_uses_https=True):
|
||||
if not django_apps.is_installed("django.contrib.sites"):
|
||||
raise ImproperlyConfigured(
|
||||
"ping_google requires django.contrib.sites, which isn't installed."
|
||||
)
|
||||
if not django_apps.is_installed('django.contrib.sites'):
|
||||
raise ImproperlyConfigured("ping_google requires django.contrib.sites, which isn't installed.")
|
||||
|
||||
if sitemap_url is None:
|
||||
try:
|
||||
# First, try to get the "index" sitemap URL.
|
||||
sitemap_url = reverse("django.contrib.sitemaps.views.index")
|
||||
sitemap_url = reverse('django.contrib.sitemaps.views.index')
|
||||
except NoReverseMatch:
|
||||
try:
|
||||
# Next, try for the "global" sitemap URL.
|
||||
sitemap_url = reverse("django.contrib.sitemaps.views.sitemap")
|
||||
sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
|
||||
except NoReverseMatch:
|
||||
pass
|
||||
|
||||
if sitemap_url is None:
|
||||
raise SitemapNotFound(
|
||||
"You didn't provide a sitemap_url, and the sitemap URL couldn't be "
|
||||
"auto-detected."
|
||||
)
|
||||
raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.")
|
||||
|
||||
Site = django_apps.get_model("sites.Site")
|
||||
Site = django_apps.get_model('sites.Site')
|
||||
current_site = Site.objects.get_current()
|
||||
scheme = "https" if sitemap_uses_https else "http"
|
||||
return "%s://%s%s" % (scheme, current_site.domain, sitemap_url)
|
||||
scheme = 'https' if sitemap_uses_https else 'http'
|
||||
return '%s://%s%s' % (scheme, current_site.domain, sitemap_url)
|
||||
|
||||
|
||||
class Sitemap:
|
||||
@@ -114,8 +107,8 @@ class Sitemap:
|
||||
obj, lang_code = item
|
||||
# Activate language from item-tuple or forced one before calling location.
|
||||
with translation.override(force_lang_code or lang_code):
|
||||
return self._get("location", item)
|
||||
return self._get("location", item)
|
||||
return self._get('location', item)
|
||||
return self._get('location', item)
|
||||
|
||||
@property
|
||||
def paginator(self):
|
||||
@@ -129,23 +122,13 @@ class Sitemap:
|
||||
|
||||
def get_protocol(self, protocol=None):
|
||||
# Determine protocol
|
||||
if self.protocol is None and protocol is None:
|
||||
warnings.warn(
|
||||
"The default sitemap protocol will be changed from 'http' to "
|
||||
"'https' in Django 5.0. Set Sitemap.protocol to silence this "
|
||||
"warning.",
|
||||
category=RemovedInDjango50Warning,
|
||||
stacklevel=2,
|
||||
)
|
||||
# RemovedInDjango50Warning: when the deprecation ends, replace 'http'
|
||||
# with 'https'.
|
||||
return self.protocol or protocol or "http"
|
||||
return self.protocol or protocol or 'http'
|
||||
|
||||
def get_domain(self, site=None):
|
||||
# Determine domain
|
||||
if site is None:
|
||||
if django_apps.is_installed("django.contrib.sites"):
|
||||
Site = django_apps.get_model("sites.Site")
|
||||
if django_apps.is_installed('django.contrib.sites'):
|
||||
Site = django_apps.get_model('sites.Site')
|
||||
try:
|
||||
site = Site.objects.get_current()
|
||||
except Site.DoesNotExist:
|
||||
@@ -169,45 +152,40 @@ class Sitemap:
|
||||
|
||||
paginator_page = self.paginator.page(page)
|
||||
for item in paginator_page.object_list:
|
||||
loc = f"{protocol}://{domain}{self._location(item)}"
|
||||
priority = self._get("priority", item)
|
||||
lastmod = self._get("lastmod", item)
|
||||
loc = f'{protocol}://{domain}{self._location(item)}'
|
||||
priority = self._get('priority', item)
|
||||
lastmod = self._get('lastmod', item)
|
||||
|
||||
if all_items_lastmod:
|
||||
all_items_lastmod = lastmod is not None
|
||||
if all_items_lastmod and (
|
||||
latest_lastmod is None or lastmod > latest_lastmod
|
||||
):
|
||||
if (all_items_lastmod and
|
||||
(latest_lastmod is None or lastmod > latest_lastmod)):
|
||||
latest_lastmod = lastmod
|
||||
|
||||
url_info = {
|
||||
"item": item,
|
||||
"location": loc,
|
||||
"lastmod": lastmod,
|
||||
"changefreq": self._get("changefreq", item),
|
||||
"priority": str(priority if priority is not None else ""),
|
||||
"alternates": [],
|
||||
'item': item,
|
||||
'location': loc,
|
||||
'lastmod': lastmod,
|
||||
'changefreq': self._get('changefreq', item),
|
||||
'priority': str(priority if priority is not None else ''),
|
||||
'alternates': [],
|
||||
}
|
||||
|
||||
if self.i18n and self.alternates:
|
||||
for lang_code in self._languages():
|
||||
loc = f"{protocol}://{domain}{self._location(item, lang_code)}"
|
||||
url_info["alternates"].append(
|
||||
{
|
||||
"location": loc,
|
||||
"lang_code": lang_code,
|
||||
}
|
||||
)
|
||||
loc = f'{protocol}://{domain}{self._location(item, lang_code)}'
|
||||
url_info['alternates'].append({
|
||||
'location': loc,
|
||||
'lang_code': lang_code,
|
||||
})
|
||||
if self.x_default:
|
||||
lang_code = settings.LANGUAGE_CODE
|
||||
loc = f"{protocol}://{domain}{self._location(item, lang_code)}"
|
||||
loc = loc.replace(f"/{lang_code}/", "/", 1)
|
||||
url_info["alternates"].append(
|
||||
{
|
||||
"location": loc,
|
||||
"lang_code": "x-default",
|
||||
}
|
||||
)
|
||||
loc = f'{protocol}://{domain}{self._location(item, lang_code)}'
|
||||
loc = loc.replace(f'/{lang_code}/', '/', 1)
|
||||
url_info['alternates'].append({
|
||||
'location': loc,
|
||||
'lang_code': 'x-default',
|
||||
})
|
||||
|
||||
urls.append(url_info)
|
||||
|
||||
@@ -222,8 +200,8 @@ class GenericSitemap(Sitemap):
|
||||
changefreq = None
|
||||
|
||||
def __init__(self, info_dict, priority=None, changefreq=None, protocol=None):
|
||||
self.queryset = info_dict["queryset"]
|
||||
self.date_field = info_dict.get("date_field")
|
||||
self.queryset = info_dict['queryset']
|
||||
self.date_field = info_dict.get('date_field')
|
||||
self.priority = self.priority or priority
|
||||
self.changefreq = self.changefreq or changefreq
|
||||
self.protocol = self.protocol or protocol
|
||||
|
||||
@@ -3,6 +3,6 @@ from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
||||
class SiteMapsConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.AutoField"
|
||||
name = "django.contrib.sitemaps"
|
||||
default_auto_field = 'django.db.models.AutoField'
|
||||
name = 'django.contrib.sitemaps'
|
||||
verbose_name = _("Site Maps")
|
||||
|
||||
@@ -6,11 +6,11 @@ class Command(BaseCommand):
|
||||
help = "Ping Google with an updated sitemap, pass optional url of sitemap"
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument("sitemap_url", nargs="?")
|
||||
parser.add_argument("--sitemap-uses-http", action="store_true")
|
||||
parser.add_argument('sitemap_url', nargs='?')
|
||||
parser.add_argument('--sitemap-uses-http', action='store_true')
|
||||
|
||||
def handle(self, *args, **options):
|
||||
ping_google(
|
||||
sitemap_url=options["sitemap_url"],
|
||||
sitemap_uses_https=not options["sitemap_uses_http"],
|
||||
sitemap_url=options['sitemap_url'],
|
||||
sitemap_uses_https=not options['sitemap_uses_http'],
|
||||
)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import datetime
|
||||
from calendar import timegm
|
||||
from functools import wraps
|
||||
|
||||
from django.contrib.sites.shortcuts import get_current_site
|
||||
@@ -6,7 +7,6 @@ from django.core.paginator import EmptyPage, PageNotAnInteger
|
||||
from django.http import Http404
|
||||
from django.template.response import TemplateResponse
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
from django.utils.http import http_date
|
||||
|
||||
|
||||
@@ -14,20 +14,15 @@ def x_robots_tag(func):
|
||||
@wraps(func)
|
||||
def inner(request, *args, **kwargs):
|
||||
response = func(request, *args, **kwargs)
|
||||
response.headers["X-Robots-Tag"] = "noindex, noodp, noarchive"
|
||||
response.headers['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",
|
||||
):
|
||||
def index(request, sitemaps,
|
||||
template_name='sitemap_index.xml', content_type='application/xml',
|
||||
sitemap_url_name='django.contrib.sitemaps.views.sitemap'):
|
||||
|
||||
req_protocol = request.scheme
|
||||
req_site = get_current_site(request)
|
||||
@@ -39,26 +34,20 @@ def index(
|
||||
if callable(site):
|
||||
site = site()
|
||||
protocol = req_protocol if site.protocol is None else site.protocol
|
||||
sitemap_url = reverse(sitemap_url_name, kwargs={"section": section})
|
||||
absolute_url = "%s://%s%s" % (protocol, req_site.domain, sitemap_url)
|
||||
sitemap_url = reverse(sitemap_url_name, kwargs={'section': section})
|
||||
absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url)
|
||||
sites.append(absolute_url)
|
||||
# Add links to all pages of the sitemap.
|
||||
for page in range(2, site.paginator.num_pages + 1):
|
||||
sites.append("%s?p=%s" % (absolute_url, page))
|
||||
sites.append('%s?p=%s' % (absolute_url, page))
|
||||
|
||||
return TemplateResponse(
|
||||
request, template_name, {"sitemaps": sites}, content_type=content_type
|
||||
)
|
||||
return TemplateResponse(request, template_name, {'sitemaps': sites},
|
||||
content_type=content_type)
|
||||
|
||||
|
||||
@x_robots_tag
|
||||
def sitemap(
|
||||
request,
|
||||
sitemaps,
|
||||
section=None,
|
||||
template_name="sitemap.xml",
|
||||
content_type="application/xml",
|
||||
):
|
||||
def sitemap(request, sitemaps, section=None,
|
||||
template_name='sitemap.xml', content_type='application/xml'):
|
||||
|
||||
req_protocol = request.scheme
|
||||
req_site = get_current_site(request)
|
||||
@@ -78,30 +67,26 @@ def sitemap(
|
||||
try:
|
||||
if callable(site):
|
||||
site = site()
|
||||
urls.extend(site.get_urls(page=page, site=req_site, protocol=req_protocol))
|
||||
urls.extend(site.get_urls(page=page, site=req_site,
|
||||
protocol=req_protocol))
|
||||
if all_sites_lastmod:
|
||||
site_lastmod = getattr(site, "latest_lastmod", None)
|
||||
site_lastmod = getattr(site, 'latest_lastmod', None)
|
||||
if site_lastmod is not None:
|
||||
if not isinstance(site_lastmod, datetime.datetime):
|
||||
site_lastmod = datetime.datetime.combine(
|
||||
site_lastmod, datetime.time.min
|
||||
)
|
||||
if timezone.is_naive(site_lastmod):
|
||||
site_lastmod = timezone.make_aware(site_lastmod, timezone.utc)
|
||||
lastmod = (
|
||||
site_lastmod if lastmod is None else max(lastmod, site_lastmod)
|
||||
site_lastmod = (
|
||||
site_lastmod.utctimetuple() if isinstance(site_lastmod, datetime.datetime)
|
||||
else site_lastmod.timetuple()
|
||||
)
|
||||
lastmod = site_lastmod if lastmod is None else max(lastmod, site_lastmod)
|
||||
else:
|
||||
all_sites_lastmod = False
|
||||
except EmptyPage:
|
||||
raise Http404("Page %s empty" % page)
|
||||
except PageNotAnInteger:
|
||||
raise Http404("No page '%s'" % page)
|
||||
response = TemplateResponse(
|
||||
request, template_name, {"urlset": urls}, content_type=content_type
|
||||
)
|
||||
response = TemplateResponse(request, template_name, {'urlset': urls},
|
||||
content_type=content_type)
|
||||
if all_sites_lastmod and lastmod is not None:
|
||||
# if lastmod is defined for all sites, set header so as
|
||||
# ConditionalGetMiddleware is able to send 304 NOT MODIFIED
|
||||
response.headers["Last-Modified"] = http_date(lastmod.timestamp())
|
||||
response.headers['Last-Modified'] = http_date(timegm(lastmod))
|
||||
return response
|
||||
|
||||
Reference in New Issue
Block a user