def handle_uncaught_exception(request, resolver, exc_info):
"""
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
"""
if settings.DEBUG_PROPAGATE_EXCEPTIONS:
raise
logger.error(
'Internal Server Error: %s', request.path,
exc_info=exc_info,
extra={'status_code': 500, 'request': request},
)
if settings.DEBUG:
return debug.technical_500_response(request, *exc_info)
# Return an HttpResponse that displays a friendly error message.
callback, param_dict = resolver.resolve_error_handler(500)
return callback(request, **param_dict)
python类DEBUG的实例源码
def serve(request, path, insecure=False, **kwargs):
"""
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders.
To use, put a URL pattern such as::
from django.contrib.staticfiles import views
url(r'^(?P<path>.*)$', views.serve)
in your URLconf.
It uses the django.views.static.serve() view to serve the found files.
"""
if not settings.DEBUG and not insecure:
raise Http404
normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
absolute_path = finders.find(normalized_path)
if not absolute_path:
if path.endswith('/') or path == '':
raise Http404("Directory indexes are not allowed here.")
raise Http404("'%s' could not be found" % path)
document_root, path = os.path.split(absolute_path)
return static.serve(request, path, document_root=document_root, **kwargs)
def dispatch(self, request, *args, **kwargs):
"""Override to check settings"""
if django.VERSION < (1, 10):
is_auth = request.user.is_authenticated()
else:
is_auth = request.user.is_authenticated
if not ADMIN_SHELL_ENABLE:
return HttpResponseNotFound("Not found: Django admin shell is not enabled")
elif is_auth is False or request.user.is_staff is False:
return HttpResponseForbidden("Forbidden: To access Django admin shell you must have access the admin site")
elif ADMIN_SHELL_ONLY_DEBUG_MODE and settings.DEBUG is False:
return HttpResponseForbidden("Forbidden :Django admin shell require DEBUG mode")
elif ADMIN_SHELL_ONLY_FOR_SUPERUSER and request.user.is_superuser is False:
return HttpResponseForbidden("Forbidden: To access Django admin shell you must be superuser")
return super(Shell, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs):
"""Override to check settings"""
if django.VERSION < (1, 10):
is_auth = request.user.is_authenticated()
else:
is_auth = request.user.is_authenticated
if not ADMIN_SHELL_ENABLE:
return HttpResponseNotFound("Not found: Django admin shell is not enabled")
elif is_auth is False or request.user.is_staff is False:
return HttpResponseForbidden("Forbidden: To access Django admin shell you must have access the admin site")
elif ADMIN_SHELL_ONLY_DEBUG_MODE and settings.DEBUG is False:
return HttpResponseForbidden("Forbidden :Django admin shell require DEBUG mode")
elif ADMIN_SHELL_ONLY_FOR_SUPERUSER and request.user.is_superuser is False:
return HttpResponseForbidden("Forbidden: To access Django admin shell you must be superuser")
return super(Shell, self).dispatch(request, *args, **kwargs)
def validate_school_email(email, request=None, site_id=None):
email_domain = email.rsplit('@', 1)[-1].lower()
school_email_domain = TenantApi.site_settings(
'SCHOOL_EMAIL_DOMAIN',
request=request,
site_id=site_id,
)
allowed = [_domain.strip() for _domain in school_email_domain.split(',')]
allowed.append('projectcallisto.org')
if email_domain not in allowed and not settings.DEBUG:
logger.warning(
"non school email used with domain {}".format(email_domain))
raise forms.ValidationError(non_school_email_error(
request=request,
site_id=site_id,
))
def exception_handler(client, request=None, **kwargs):
def actually_do_stuff(request=None, **kwargs):
exc_info = sys.exc_info()
try:
if (django_settings.DEBUG and not client.config.debug) or getattr(exc_info[1], 'skip_elasticapm', False):
return
client.capture('Exception', exc_info=exc_info, request=request)
except Exception as exc:
try:
client.error_logger.exception(u'Unable to process log entry: %s' % (exc,))
except Exception as exc:
warnings.warn(u'Unable to process log entry: %s' % (exc,))
finally:
try:
del exc_info
except Exception as e:
client.error_logger.exception(e)
return actually_do_stuff(request, **kwargs)
def process_response(self, request, response):
if (response.status_code != 404 or
_is_ignorable_404(request.get_full_path())):
return response
if django_settings.DEBUG and not self.client.config.debug:
return response
data = {
'level': logging.INFO,
'logger': 'http404',
}
result = self.client.capture(
'Message',
request=request,
param_message={
'message': 'Page Not Found: %s',
'params': [request.build_absolute_uri()]
}, logger_name='http404', level=logging.INFO
)
request._elasticapm = {
'service_name': data.get('service_name', self.client.config.service_name),
'id': result,
}
return response
def show_up_sense(context, sense=''):
"""Show AdSense for SENSE_UP"""
request = context['request']
if sense == 'user':
user = request.user
if user.profile.sense_client and user.profile.sense_slot:
sense_client = user.profile.sense_client
sense_slot = user.profile.sense_slot
else:
sense_client = settings.SENSE_UP_CLIENT
sense_slot = settings.SENSE_UP_SLOT
else:
sense_client = settings.SENSE_UP_CLIENT
sense_slot = settings.SENSE_UP_SLOT
sense_enabled = settings.ENABLE_ADSENSE
if settings.DEBUG:
sense_enabled = False
return {
'sense_enabled': sense_enabled,
'sense_native': False,
'sense_client': sense_client,
'sense_slot': sense_slot,
}
def show_up_sense_native(context, sense=''):
"""Show AdSense Native for SENSE_UP"""
request = context['request']
if sense == 'user':
user = request.user
if user.profile.sense_client and user.profile.sense_slot:
sense_client = user.profile.sense_client
sense_slot = user.profile.sense_slot
else:
sense_client = settings.SENSE_UP_CLIENT
sense_slot = settings.SENSE_UP_SLOT
else:
sense_client = settings.SENSE_UP_CLIENT
sense_slot = settings.SENSE_UP_SLOT
sense_enabled = settings.ENABLE_ADSENSE
if settings.DEBUG:
sense_enabled = False
return {
'sense_enabled': sense_enabled,
'sense_native': True,
'sense_client': sense_client,
'sense_slot': sense_slot,
}
def show_down_sense(context, sense=''):
"""Show AdSense for SENSE_DOWN"""
request = context['request']
if sense == 'user':
user = request.user
if user.profile.sense_client and user.profile.sense_slot:
sense_client = user.profile.sense_client
sense_slot = user.profile.sense_slot
else:
sense_client = settings.SENSE_DOWN_CLIENT
sense_slot = settings.SENSE_DOWN_SLOT
else:
sense_client = settings.SENSE_DOWN_CLIENT
sense_slot = settings.SENSE_DOWN_SLOT
sense_enabled = settings.ENABLE_ADSENSE
if settings.DEBUG:
sense_enabled = False
return {
'sense_enabled': sense_enabled,
'sense_native': False,
'sense_client': sense_client,
'sense_slot': sense_slot,
}
def show_down_sense_native(context, sense=''):
"""Show AdSense Native for SENSE_DOWN"""
request = context['request']
if sense == 'user':
user = request.user
if user.profile.sense_client and user.profile.sense_slot:
sense_client = user.profile.sense_client
sense_slot = user.profile.sense_slot
else:
sense_client = settings.SENSE_DOWN_CLIENT
sense_slot = settings.SENSE_DOWN_SLOT
else:
sense_client = settings.SENSE_DOWN_CLIENT
sense_slot = settings.SENSE_DOWN_SLOT
sense_enabled = settings.ENABLE_ADSENSE
if settings.DEBUG:
sense_enabled = False
return {
'sense_enabled': sense_enabled,
'sense_native': True,
'sense_client': sense_client,
'sense_slot': sense_slot,
}
def __init__(self, *args, **kwargs):
self.username = getattr(settings,
'ALWAYS_AUTHENTICATED_USERNAME',
'user')
self.defaults = getattr(settings,
'ALWAYS_AUTHENTICATED_USER_DEFAULTS',
{})
if (not settings.DEBUG and
getattr(settings,'ALWAYS_AUTHENTICATED_DEBUG_ONLY', True)):
raise ImproperlyConfigured(
'DEBUG=%s, but AlwaysAuthenticatedMiddleware is configured to '
'only run in debug mode.\n'
'Remove AlwaysAuthenticatedMiddleware from '
'MIDDLEWARE/MIDDLEWARE_CLASSES or set '
'ALWAYS_AUTHENTICATED_DEBUG_ONLY to False.' % settings.DEBUG)
super(AlwaysAuthenticatedMiddleware, self).__init__(*args, **kwargs)
def run_check(id, request=None, fail_silently=True, fail_status=500):
status = 200
try:
v = config.checks[id]
if isinstance(v, six.string_types):
c = import_string(v)
ret, status = c(request)
elif callable(v):
ret, status = v(request)
else:
ret = v
except Exception as e:
ret = "ERROR"
status = fail_status
logger.exception(e)
if settings.DEBUG:
ret = str(e)
if not fail_silently:
raise
return ret, status
def get_extra(config, request=None):
extras = {}
for k, v in config.extra.items():
try:
if isinstance(v, six.string_types):
c = import_string(v)
extras[k] = c(request)
elif callable(v):
extras[k] = v(request)
else:
extras[k] = v
except Exception as e:
logger.exception(e)
if settings.DEBUG:
extras[k] = str(e)
return extras
def add_arguments(self, parser):
parser.add_argument("--verbose",
action="store_true",
default=False,
help="Be very chatty and run logging at DEBUG")
parser.add_argument("--chunk-size",
dest="chunk_size",
default=DEFAULT_CHUNK_SIZE,
type=int,
help="The number of records to batch process at once")
parser.add_argument("--num-iterations",
dest="num_iterations",
default=DEFAULT_NUM_ITERATIONS,
type=int,
help="The number of times to loop through `chunk_size` records")
parser.add_argument("--num-threads",
dest="num_threads",
default=DEFAULT_NUM_THREADS,
type=int,
help="The number of threads to start up at once")
def setup_logging(debug=False):
"""
Configures logging in cases where a Django environment is not supposed
to be configured.
TODO: This is really confusing, importing django settings is allowed to
fail when debug=False, but if it's true it can fail?
"""
try:
from django.conf.settings import LOGGING
except ImportError:
from kolibri.deployment.default.settings.base import LOGGING
if debug:
from django.conf import settings
settings.DEBUG = True
LOGGING['handlers']['console']['level'] = 'DEBUG'
LOGGING['loggers']['kolibri']['level'] = 'DEBUG'
logger.debug("Debug mode is on!")
logging.config.dictConfig(LOGGING)
def handle_uncaught_exception(request, resolver, exc_info):
"""
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
"""
if settings.DEBUG_PROPAGATE_EXCEPTIONS:
raise
logger.error(
'Internal Server Error: %s', request.path,
exc_info=exc_info,
extra={'status_code': 500, 'request': request},
)
if settings.DEBUG:
return debug.technical_500_response(request, *exc_info)
# If Http500 handler is not installed, reraise the last exception.
if resolver.urlconf_module is None:
six.reraise(*exc_info)
# Return an HttpResponse that displays a friendly error message.
callback, param_dict = resolver.resolve_error_handler(500)
return callback(request, **param_dict)
def serve(request, path, insecure=False, **kwargs):
"""
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders.
To use, put a URL pattern such as::
from django.contrib.staticfiles import views
url(r'^(?P<path>.*)$', views.serve)
in your URLconf.
It uses the django.views.static.serve() view to serve the found files.
"""
if not settings.DEBUG and not insecure:
raise Http404
normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
absolute_path = finders.find(normalized_path)
if not absolute_path:
if path.endswith('/') or path == '':
raise Http404("Directory indexes are not allowed here.")
raise Http404("'%s' could not be found" % path)
document_root, path = os.path.split(absolute_path)
return static.serve(request, path, document_root=document_root, **kwargs)
def send_reply(content_id):
"""Handle sending a Content object that is a reply out via the federation layer.
Currently we only deliver public content.
"""
try:
content = Content.objects.get(id=content_id, visibility=Visibility.PUBLIC, content_type=ContentType.REPLY,
local=True)
except Content.DoesNotExist:
logger.warning("No content found with id %s", content_id)
return
entity = make_federable_content(content)
if not entity:
logger.warning("send_reply - No entity for %s", content)
if settings.DEBUG:
# Don't send in development mode
return
# Send directly (remote parent) or as a relayable (local parent)
if content.parent.local:
forward_entity(entity, content.parent.id)
else:
# We only need to send to the original author
recipients = [
(content.parent.author.handle, None),
]
handle_send(entity, content.author, recipients)