mirror of
https://github.com/django/django.git
synced 2025-10-27 15:46:10 +00:00
Reverted "Fixed #27818 -- Replaced try/except/pass with contextlib.suppress()."
This reverts commit 550cb3a365
because try/except performs better.
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
import json
|
||||
from contextlib import suppress
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.admin.utils import quote
|
||||
@@ -138,6 +137,8 @@ class LogEntry(models.Model):
|
||||
"""
|
||||
if self.content_type and self.object_id:
|
||||
url_name = 'admin:%s_%s_change' % (self.content_type.app_label, self.content_type.model)
|
||||
with suppress(NoReverseMatch):
|
||||
try:
|
||||
return reverse(url_name, args=(quote(self.object_id),))
|
||||
except NoReverseMatch:
|
||||
pass
|
||||
return None
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from contextlib import suppress
|
||||
from functools import update_wrapper
|
||||
from weakref import WeakSet
|
||||
|
||||
@@ -428,11 +427,15 @@ class AdminSite:
|
||||
'perms': perms,
|
||||
}
|
||||
if perms.get('change'):
|
||||
with suppress(NoReverseMatch):
|
||||
try:
|
||||
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
|
||||
except NoReverseMatch:
|
||||
pass
|
||||
if perms.get('add'):
|
||||
with suppress(NoReverseMatch):
|
||||
try:
|
||||
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)
|
||||
except NoReverseMatch:
|
||||
pass
|
||||
|
||||
if app_label in app_dict:
|
||||
app_dict[app_label]['models'].append(model_dict)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
from contextlib import suppress
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib import auth
|
||||
from django.contrib.auth import load_backend
|
||||
@@ -91,8 +89,10 @@ class RemoteUserMiddleware(MiddlewareMixin):
|
||||
"""
|
||||
backend_str = request.session[auth.BACKEND_SESSION_KEY]
|
||||
backend = auth.load_backend(backend_str)
|
||||
with suppress(AttributeError): # Backend has no clean_username method.
|
||||
try:
|
||||
username = backend.clean_username(username)
|
||||
except AttributeError: # Backend has no clean_username method.
|
||||
pass
|
||||
return username
|
||||
|
||||
def _remove_invalid_user(self, request):
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from collections import defaultdict
|
||||
from contextlib import suppress
|
||||
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.core import checks
|
||||
@@ -237,8 +236,10 @@ class GenericForeignKey(FieldCacheMixin):
|
||||
rel_obj = None
|
||||
if ct_id is not None:
|
||||
ct = self.get_content_type(id=ct_id, using=instance._state.db)
|
||||
with suppress(ObjectDoesNotExist):
|
||||
try:
|
||||
rel_obj = ct.get_object_for_this_type(pk=pk_val)
|
||||
except ObjectDoesNotExist:
|
||||
pass
|
||||
self.set_cached_value(instance, rel_obj)
|
||||
return rel_obj
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from collections import defaultdict
|
||||
from contextlib import suppress
|
||||
|
||||
from django.apps import apps
|
||||
from django.db import models
|
||||
@@ -39,8 +38,10 @@ class ContentTypeManager(models.Manager):
|
||||
for the same model don't hit the database.
|
||||
"""
|
||||
opts = self._get_opts(model, for_concrete_model)
|
||||
with suppress(KeyError):
|
||||
try:
|
||||
return self._get_from_cache(opts)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
# The ContentType entry was not found in the cache, therefore we
|
||||
# proceed to load or create it.
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
from contextlib import suppress
|
||||
|
||||
from django.apps import apps
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.contrib.sites.requests import RequestSite
|
||||
@@ -55,10 +53,12 @@ def shortcut(request, content_type_id, object_id):
|
||||
# First, look for an many-to-many relationship to Site.
|
||||
for field in opts.many_to_many:
|
||||
if field.remote_field.model is Site:
|
||||
with suppress(IndexError):
|
||||
try:
|
||||
# Caveat: In the case of multiple related Sites, this just
|
||||
# selects the *first* one, which is arbitrary.
|
||||
object_domain = getattr(obj, field.name).all()[0].domain
|
||||
except IndexError:
|
||||
pass
|
||||
if object_domain is not None:
|
||||
break
|
||||
|
||||
@@ -77,8 +77,10 @@ def shortcut(request, content_type_id, object_id):
|
||||
|
||||
# Fall back to the current site (if possible).
|
||||
if object_domain is None:
|
||||
with suppress(Site.DoesNotExist):
|
||||
try:
|
||||
object_domain = Site.objects.get_current(request).domain
|
||||
except Site.DoesNotExist:
|
||||
pass
|
||||
|
||||
else:
|
||||
# Fall back to the current request's site.
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
from contextlib import suppress
|
||||
|
||||
from django.db.backends.sqlite3.schema import DatabaseSchemaEditor
|
||||
from django.db.utils import DatabaseError
|
||||
|
||||
@@ -91,13 +89,15 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor):
|
||||
self.remove_geometry_metadata(model, field)
|
||||
# Make sure all geom stuff is gone
|
||||
for geom_table in self.geometry_tables:
|
||||
with suppress(DatabaseError):
|
||||
try:
|
||||
self.execute(
|
||||
self.sql_discard_geometry_columns % {
|
||||
"geom_table": geom_table,
|
||||
"table": self.quote_name(model._meta.db_table),
|
||||
}
|
||||
)
|
||||
except DatabaseError:
|
||||
pass
|
||||
super().delete_model(model, **kwargs)
|
||||
|
||||
def add_field(self, model, field):
|
||||
@@ -138,7 +138,7 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor):
|
||||
super().alter_db_table(model, old_db_table, new_db_table)
|
||||
# Repoint any straggler names
|
||||
for geom_table in self.geometry_tables:
|
||||
with suppress(DatabaseError):
|
||||
try:
|
||||
self.execute(
|
||||
self.sql_update_geometry_columns % {
|
||||
"geom_table": geom_table,
|
||||
@@ -146,6 +146,8 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor):
|
||||
"new_table": self.quote_name(new_db_table),
|
||||
}
|
||||
)
|
||||
except DatabaseError:
|
||||
pass
|
||||
# Re-add geometry-ness and rename spatial index tables
|
||||
for field in model._meta.local_fields:
|
||||
if isinstance(field, GeometryField):
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from collections import defaultdict, namedtuple
|
||||
from contextlib import suppress
|
||||
|
||||
from django.contrib.gis import forms, gdal
|
||||
from django.contrib.gis.db.models.proxy import SpatialProxy
|
||||
@@ -157,8 +156,10 @@ class BaseSpatialField(Field):
|
||||
if isinstance(value, gdal.GDALRaster):
|
||||
return value
|
||||
elif is_candidate:
|
||||
with suppress(GDALException):
|
||||
try:
|
||||
return gdal.GDALRaster(value)
|
||||
except GDALException:
|
||||
pass
|
||||
elif isinstance(value, dict):
|
||||
try:
|
||||
return gdal.GDALRaster(value)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from contextlib import suppress
|
||||
from ctypes import byref, c_double
|
||||
|
||||
from django.contrib.gis.gdal.base import GDALBase
|
||||
@@ -77,8 +76,10 @@ class Layer(GDALBase):
|
||||
"""
|
||||
if self._random_read:
|
||||
# If the Layer supports random reading, return.
|
||||
with suppress(GDALException):
|
||||
try:
|
||||
return Feature(capi.get_feature(self.ptr, feat_id), self)
|
||||
except GDALException:
|
||||
pass
|
||||
else:
|
||||
# Random access isn't supported, have to increment through
|
||||
# each feature until the given feature ID is encountered.
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
"""
|
||||
This module contains useful utilities for GeoDjango.
|
||||
"""
|
||||
from contextlib import suppress
|
||||
|
||||
from django.contrib.gis.utils.ogrinfo import ogrinfo # NOQA
|
||||
from django.contrib.gis.utils.ogrinspect import mapping, ogrinspect # NOQA
|
||||
from django.contrib.gis.utils.srs import add_srs_entry # NOQA
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
|
||||
with suppress(ImproperlyConfigured):
|
||||
try:
|
||||
# LayerMapping requires DJANGO_SETTINGS_MODULE to be set,
|
||||
# and ImproperlyConfigured is raised if that's not the case.
|
||||
from django.contrib.gis.utils.layermapping import LayerMapping, LayerMapError # NOQA
|
||||
except ImproperlyConfigured:
|
||||
pass
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import json
|
||||
from contextlib import suppress
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.messages.storage.base import BaseStorage, Message
|
||||
@@ -154,10 +153,12 @@ class CookieStorage(BaseStorage):
|
||||
if len(bits) == 2:
|
||||
hash, value = bits
|
||||
if constant_time_compare(hash, self._hash(value)):
|
||||
with suppress(ValueError):
|
||||
try:
|
||||
# If we get here (and the JSON decode works), everything is
|
||||
# good. In any other case, drop back and return None.
|
||||
return json.loads(value, cls=MessageDecoder)
|
||||
except ValueError:
|
||||
pass
|
||||
# Mark the data as used (so it gets removed) since something was wrong
|
||||
# with the data.
|
||||
self.used = True
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import base64
|
||||
import logging
|
||||
import string
|
||||
from contextlib import suppress
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from django.conf import settings
|
||||
@@ -263,8 +262,10 @@ class SessionBase:
|
||||
"""
|
||||
if value is None:
|
||||
# Remove any custom expiration for this session.
|
||||
with suppress(KeyError):
|
||||
try:
|
||||
del self['_session_expiry']
|
||||
except KeyError:
|
||||
pass
|
||||
return
|
||||
if isinstance(value, timedelta):
|
||||
value = timezone.now() + value
|
||||
|
||||
@@ -3,7 +3,6 @@ import logging
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from contextlib import suppress
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.sessions.backends.base import (
|
||||
@@ -156,7 +155,7 @@ class SessionStore(SessionBase):
|
||||
# See ticket #8616.
|
||||
dir, prefix = os.path.split(session_file_name)
|
||||
|
||||
with suppress(OSError, IOError, EOFError):
|
||||
try:
|
||||
output_file_fd, output_file_name = tempfile.mkstemp(dir=dir, prefix=prefix + '_out_')
|
||||
renamed = False
|
||||
try:
|
||||
@@ -173,6 +172,8 @@ class SessionStore(SessionBase):
|
||||
finally:
|
||||
if not renamed:
|
||||
os.unlink(output_file_name)
|
||||
except (OSError, IOError, EOFError):
|
||||
pass
|
||||
|
||||
def exists(self, session_key):
|
||||
return os.path.exists(self._key_to_file(session_key))
|
||||
@@ -182,8 +183,10 @@ class SessionStore(SessionBase):
|
||||
if self.session_key is None:
|
||||
return
|
||||
session_key = self.session_key
|
||||
with suppress(OSError):
|
||||
try:
|
||||
os.unlink(self._key_to_file(session_key))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def clean(self):
|
||||
pass
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from contextlib import suppress
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import urlopen
|
||||
|
||||
@@ -37,9 +36,11 @@ def _get_sitemap_full_url(sitemap_url):
|
||||
# First, try to get the "index" sitemap URL.
|
||||
sitemap_url = reverse('django.contrib.sitemaps.views.index')
|
||||
except NoReverseMatch:
|
||||
with suppress(NoReverseMatch):
|
||||
try:
|
||||
# Next, try for the "global" sitemap URL.
|
||||
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.")
|
||||
@@ -88,8 +89,10 @@ class Sitemap:
|
||||
if site is None:
|
||||
if django_apps.is_installed('django.contrib.sites'):
|
||||
Site = django_apps.get_model('sites.Site')
|
||||
with suppress(Site.DoesNotExist):
|
||||
try:
|
||||
site = Site.objects.get_current()
|
||||
except Site.DoesNotExist:
|
||||
pass
|
||||
if site is None:
|
||||
raise ImproperlyConfigured(
|
||||
"To use sitemaps, either enable the sites framework or pass "
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import string
|
||||
from contextlib import suppress
|
||||
|
||||
from django.core.exceptions import ImproperlyConfigured, ValidationError
|
||||
from django.db import models
|
||||
@@ -108,11 +107,14 @@ def clear_site_cache(sender, **kwargs):
|
||||
"""
|
||||
instance = kwargs['instance']
|
||||
using = kwargs['using']
|
||||
with suppress(KeyError):
|
||||
try:
|
||||
del SITE_CACHE[instance.pk]
|
||||
|
||||
with suppress(KeyError, Site.DoesNotExist):
|
||||
except KeyError:
|
||||
pass
|
||||
try:
|
||||
del SITE_CACHE[Site.objects.using(using).get(pk=instance.pk).domain]
|
||||
except (KeyError, Site.DoesNotExist):
|
||||
pass
|
||||
|
||||
|
||||
pre_save.connect(clear_site_cache, sender=Site)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import os
|
||||
from collections import OrderedDict
|
||||
from contextlib import suppress
|
||||
|
||||
from django.apps import apps
|
||||
from django.contrib.staticfiles.finders import get_finders
|
||||
@@ -313,8 +312,10 @@ class Command(BaseCommand):
|
||||
else:
|
||||
self.log("Linking '%s'" % source_path, level=1)
|
||||
full_path = self.storage.path(prefixed_path)
|
||||
with suppress(OSError):
|
||||
try:
|
||||
os.makedirs(os.path.dirname(full_path))
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
if os.path.lexists(full_path):
|
||||
os.unlink(full_path)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from calendar import timegm
|
||||
from contextlib import suppress
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.sites.shortcuts import get_current_site
|
||||
@@ -153,13 +152,17 @@ class Feed:
|
||||
|
||||
title_tmp = None
|
||||
if self.title_template is not None:
|
||||
with suppress(TemplateDoesNotExist):
|
||||
try:
|
||||
title_tmp = loader.get_template(self.title_template)
|
||||
except TemplateDoesNotExist:
|
||||
pass
|
||||
|
||||
description_tmp = None
|
||||
if self.description_template is not None:
|
||||
with suppress(TemplateDoesNotExist):
|
||||
try:
|
||||
description_tmp = loader.get_template(self.description_template)
|
||||
except TemplateDoesNotExist:
|
||||
pass
|
||||
|
||||
for item in self._get_dynamic_attr('items', obj):
|
||||
context = self.get_context_data(item=item, site=current_site,
|
||||
|
||||
Reference in New Issue
Block a user