Python django.conf.settings.INTERNAL_IPS Examples

The following are 23 code examples of django.conf.settings.INTERNAL_IPS(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: errorpages.py    From zing with GNU General Public License v3.0 7 votes vote down vote up
def log_exception(request, exception, tb):
    if sentry_sdk is not None:
        sentry_sdk.capture_exception(exception)
        return

    # Send email to admins with details about exception
    ip_type = (
        request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS
        and "internal"
        or "EXTERNAL"
    )
    msg_args = {
        "ip_type": ip_type,
        "path": request.path,
    }
    subject = "Error (%(ip_type)s IP): %(path)s" % msg_args

    try:
        request_repr = repr(request)
    except:
        request_repr = "Request repr() unavailable"

    msg_args = (str(exception.args[0]), tb, request_repr)
    message = "%s\n\n%s\n\n%s" % msg_args
    mail_admins(subject, message, fail_silently=True) 
Example #2
Source File: middleware.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def process_view(self, request, view_func, view_args, view_kwargs):
        """
        If the request method is HEAD and either the IP is internal or the
        user is a logged-in staff member, quickly return with an x-header
        indicating the view function.  This is used by the documentation module
        to lookup the view function for an arbitrary page.
        """
        assert hasattr(request, 'user'), (
            "The XView middleware requires authentication middleware to be "
            "installed. Edit your MIDDLEWARE_CLASSES setting to insert "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'.")
        if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or
                                         (request.user.is_active and request.user.is_staff)):
            response = http.HttpResponse()
            response['X-View'] = "%s.%s" % (view_func.__module__, view_func.__name__)
            return response 
Example #3
Source File: middleware.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def process_view(self, request, view_func, view_args, view_kwargs):
        """
        If the request method is HEAD and either the IP is internal or the
        user is a logged-in staff member, quickly return with an x-header
        indicating the view function.  This is used by the documentation module
        to lookup the view function for an arbitrary page.
        """
        assert hasattr(request, 'user'), (
            "The XView middleware requires authentication middleware to be "
            "installed. Edit your MIDDLEWARE_CLASSES setting to insert "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'.")
        if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or
                                         (request.user.is_active and request.user.is_staff)):
            response = http.HttpResponse()
            response['X-View'] = "%s.%s" % (view_func.__module__, view_func.__name__)
            return response 
Example #4
Source File: doc.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def process_view(self, request, view_func, view_args, view_kwargs):
        """
        If the request method is HEAD and either the IP is internal or the
        user is a logged-in staff member, quickly return with an x-header
        indicating the view function.  This is used by the documentation module
        to lookup the view function for an arbitrary page.
        """
        assert hasattr(request, 'user'), (
            "The XView middleware requires authentication middleware to be "
            "installed. Edit your MIDDLEWARE_CLASSES setting to insert "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'.")
        if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or
                                         (request.user.is_active and request.user.is_staff)):
            response = http.HttpResponse()
            response['X-View'] = "%s.%s" % (view_func.__module__, view_func.__name__)
            return response 
Example #5
Source File: context_processors.py    From python with Apache License 2.0 5 votes vote down vote up
def debug(request):
    """
    Returns context variables helpful for debugging.
    """
    context_extras = {}
    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
        context_extras['debug'] = True
        from django.db import connections
        # Return a lazy reference that computes connection.queries on access,
        # to ensure it contains queries triggered after this function runs.
        context_extras['sql_queries'] = lazy(
            lambda: list(itertools.chain(*[connections[x].queries for x in connections])),
            list
        )
    return context_extras 
Example #6
Source File: middleware.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _show_toolbar(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', None)
        if x_forwarded_for:
            remote_addr = x_forwarded_for.split(',')[0].strip()
        else:
            remote_addr = request.META.get('REMOTE_ADDR', None)
        if not remote_addr in settings.INTERNAL_IPS \
            or (request.is_ajax() and \
                not debug_toolbar.urls._PREFIX in request.path) \
                    or not settings.DEBUG:
            return False
        return True 
Example #7
Source File: context_processors.py    From python2017 with MIT License 5 votes vote down vote up
def debug(request):
    """
    Returns context variables helpful for debugging.
    """
    context_extras = {}
    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
        context_extras['debug'] = True
        from django.db import connections
        # Return a lazy reference that computes connection.queries on access,
        # to ensure it contains queries triggered after this function runs.
        context_extras['sql_queries'] = lazy(
            lambda: list(itertools.chain(*[connections[x].queries for x in connections])),
            list
        )
    return context_extras 
Example #8
Source File: log.py    From python2017 with MIT License 5 votes vote down vote up
def emit(self, record):
        try:
            request = record.request
            subject = '%s (%s IP): %s' % (
                record.levelname,
                ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
                 else 'EXTERNAL'),
                record.getMessage()
            )
        except Exception:
            subject = '%s: %s' % (
                record.levelname,
                record.getMessage()
            )
            request = None
        subject = self.format_subject(subject)

        # Since we add a nicely formatted traceback on our own, create a copy
        # of the log record without the exception data.
        no_exc_record = copy(record)
        no_exc_record.exc_info = None
        no_exc_record.exc_text = None

        if record.exc_info:
            exc_info = record.exc_info
        else:
            exc_info = (None, record.getMessage(), None)

        reporter = ExceptionReporter(request, is_email=True, *exc_info)
        message = "%s\n\n%s" % (self.format(no_exc_record), reporter.get_traceback_text())
        html_message = reporter.get_traceback_html() if self.include_html else None
        self.send_mail(subject, message, fail_silently=True, html_message=html_message) 
Example #9
Source File: request_history.py    From django-debug-toolbar-request-history with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def allow_ajax(request):
    """
    Default function to determine whether to show the toolbar on a given page.
    """
    if request.META.get('REMOTE_ADDR', None) not in settings.INTERNAL_IPS:
        return False
    return bool(settings.DEBUG) 
Example #10
Source File: context_processors.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def debug(request):
    """
    Returns context variables helpful for debugging.
    """
    context_extras = {}
    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
        context_extras['debug'] = True
        from django.db import connection
        # Return a lazy reference that computes connection.queries on access,
        # to ensure it contains queries triggered after this function runs.
        context_extras['sql_queries'] = lazy(lambda: connection.queries, list)
    return context_extras 
Example #11
Source File: log.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def emit(self, record):
        try:
            request = record.request
            subject = '%s (%s IP): %s' % (
                record.levelname,
                ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
                 else 'EXTERNAL'),
                record.getMessage()
            )
        except Exception:
            subject = '%s: %s' % (
                record.levelname,
                record.getMessage()
            )
            request = None
        subject = self.format_subject(subject)

        # Since we add a nicely formatted traceback on our own, create a copy
        # of the log record without the exception data.
        no_exc_record = copy(record)
        no_exc_record.exc_info = None
        no_exc_record.exc_text = None

        if record.exc_info:
            exc_info = record.exc_info
        else:
            exc_info = (None, record.getMessage(), None)

        reporter = ExceptionReporter(request, is_email=True, *exc_info)
        message = "%s\n\n%s" % (self.format(no_exc_record), reporter.get_traceback_text())
        html_message = reporter.get_traceback_html() if self.include_html else None
        self.send_mail(subject, message, fail_silently=True, html_message=html_message) 
Example #12
Source File: context_processors.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def debug(request):
    "Returns context variables helpful for debugging."
    context_extras = {}
    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
        context_extras['debug'] = True
        from django.db import connection
        context_extras['sql_queries'] = connection.queries
    return context_extras 
Example #13
Source File: xheaders.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def populate_xheaders(request, response, model, object_id):
    """
    Adds the "X-Object-Type" and "X-Object-Id" headers to the given
    HttpResponse according to the given model and object_id -- but only if the
    given HttpRequest object has an IP address within the INTERNAL_IPS setting
    or if the request is from a logged in staff member.
    """
    from django.conf import settings
    if (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
            or (hasattr(request, 'user') and request.user.is_active
                and request.user.is_staff)):
        response['X-Object-Type'] = "%s.%s" % (model._meta.app_label, model._meta.object_name.lower())
        response['X-Object-Id'] = str(object_id) 
Example #14
Source File: log.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def emit(self, record):
        try:
            request = record.request
            subject = '%s (%s IP): %s' % (
                record.levelname,
                (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
                 and 'internal' or 'EXTERNAL'),
                record.getMessage()
            )
            filter = get_exception_reporter_filter(request)
            request_repr = filter.get_request_repr(request)
        except Exception:
            subject = '%s: %s' % (
                record.levelname,
                record.getMessage()
            )
            request = None
            request_repr = "Request repr() unavailable."
        subject = self.format_subject(subject)

        if record.exc_info:
            exc_info = record.exc_info
            stack_trace = '\n'.join(traceback.format_exception(*record.exc_info))
        else:
            exc_info = (None, record.getMessage(), None)
            stack_trace = 'No stack trace available'

        message = "%s\n\n%s" % (stack_trace, request_repr)
        reporter = ExceptionReporter(request, is_email=True, *exc_info)
        html_message = self.include_html and reporter.get_traceback_html() or None
        mail.mail_admins(subject, message, fail_silently=True, html_message=html_message) 
Example #15
Source File: log.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def emit(self, record):
        try:
            request = record.request
            subject = '%s (%s IP): %s' % (
                record.levelname,
                ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
                 else 'EXTERNAL'),
                record.getMessage()
            )
            filter = get_exception_reporter_filter(request)
            request_repr = '\n{}'.format(force_text(filter.get_request_repr(request)))
        except Exception:
            subject = '%s: %s' % (
                record.levelname,
                record.getMessage()
            )
            request = None
            request_repr = "unavailable"
        subject = self.format_subject(subject)

        if record.exc_info:
            exc_info = record.exc_info
        else:
            exc_info = (None, record.getMessage(), None)

        message = "%s\n\nRequest repr(): %s" % (self.format(record), request_repr)
        reporter = ExceptionReporter(request, is_email=True, *exc_info)
        html_message = reporter.get_traceback_html() if self.include_html else None
        self.send_mail(subject, message, fail_silently=True, html_message=html_message) 
Example #16
Source File: log.py    From python with Apache License 2.0 5 votes vote down vote up
def emit(self, record):
        try:
            request = record.request
            subject = '%s (%s IP): %s' % (
                record.levelname,
                ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
                 else 'EXTERNAL'),
                record.getMessage()
            )
        except Exception:
            subject = '%s: %s' % (
                record.levelname,
                record.getMessage()
            )
            request = None
        subject = self.format_subject(subject)

        # Since we add a nicely formatted traceback on our own, create a copy
        # of the log record without the exception data.
        no_exc_record = copy(record)
        no_exc_record.exc_info = None
        no_exc_record.exc_text = None

        if record.exc_info:
            exc_info = record.exc_info
        else:
            exc_info = (None, record.getMessage(), None)

        reporter = ExceptionReporter(request, is_email=True, *exc_info)
        message = "%s\n\n%s" % (self.format(no_exc_record), reporter.get_traceback_text())
        html_message = reporter.get_traceback_html() if self.include_html else None
        self.send_mail(subject, message, fail_silently=True, html_message=html_message) 
Example #17
Source File: context_processors.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def debug(request):
    """
    Return context variables helpful for debugging.
    """
    context_extras = {}
    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
        context_extras['debug'] = True
        from django.db import connections
        # Return a lazy reference that computes connection.queries on access,
        # to ensure it contains queries triggered after this function runs.
        context_extras['sql_queries'] = lazy(
            lambda: list(itertools.chain.from_iterable(connections[x].queries for x in connections)),
            list
        )
    return context_extras 
Example #18
Source File: log.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def emit(self, record):
        try:
            request = record.request
            subject = '%s (%s IP): %s' % (
                record.levelname,
                ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
                 else 'EXTERNAL'),
                record.getMessage()
            )
        except Exception:
            subject = '%s: %s' % (
                record.levelname,
                record.getMessage()
            )
            request = None
        subject = self.format_subject(subject)

        # Since we add a nicely formatted traceback on our own, create a copy
        # of the log record without the exception data.
        no_exc_record = copy(record)
        no_exc_record.exc_info = None
        no_exc_record.exc_text = None

        if record.exc_info:
            exc_info = record.exc_info
        else:
            exc_info = (None, record.getMessage(), None)

        reporter = ExceptionReporter(request, is_email=True, *exc_info)
        message = "%s\n\n%s" % (self.format(no_exc_record), reporter.get_traceback_text())
        html_message = reporter.get_traceback_html() if self.include_html else None
        self.send_mail(subject, message, fail_silently=True, html_message=html_message) 
Example #19
Source File: log.py    From django2-project-template with MIT License 5 votes vote down vote up
def emit(self, record):
        if os.environ.get('SLACK_HOOK', None):
            slack_message = [f'http status: {record.status_code}', f'timestamp: {timezone.now()}']
            try:
                request = record.request
                subject = '%s (%s IP): %s' % (
                    record.levelname,
                    ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS else 'EXTERNAL'),
                    record.getMessage(),
                )
                user_info = f'user_id: {request.user.id or "anonymous (None)"}'
                full_path = f'full path: {record.request.get_full_path()}'
            except Exception:  # pylint: disable=W0703
                subject = '%s: %s' % (record.levelname, record.getMessage())
                request = None
                user_info = None
                full_path = None

            exception_message = f'Exception: {",".join(record.exc_info[1].args)}'

            slack_message.append(subject)
            slack_message.append(exception_message)
            if user_info:
                slack_message.append(user_info)
            if full_path:
                slack_message.append(full_path)

            payload = dict(text='\n'.join(slack_message))
            response = urllib.request.urlopen(  # noqa: S310
                urllib.request.Request(
                    os.environ['SLACK_HOOK'],
                    data=json.dumps(payload).encode('utf8'),
                    headers={'content-type': 'application/json'},
                )
            )
            if response.read().decode('utf8') != 'ok':
                logger.error('Could not post to SLACK!') 
Example #20
Source File: context_processors.py    From bioforum with MIT License 5 votes vote down vote up
def debug(request):
    """
    Return context variables helpful for debugging.
    """
    context_extras = {}
    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
        context_extras['debug'] = True
        from django.db import connections
        # Return a lazy reference that computes connection.queries on access,
        # to ensure it contains queries triggered after this function runs.
        context_extras['sql_queries'] = lazy(
            lambda: list(itertools.chain.from_iterable(connections[x].queries for x in connections)),
            list
        )
    return context_extras 
Example #21
Source File: log.py    From bioforum with MIT License 5 votes vote down vote up
def emit(self, record):
        try:
            request = record.request
            subject = '%s (%s IP): %s' % (
                record.levelname,
                ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
                 else 'EXTERNAL'),
                record.getMessage()
            )
        except Exception:
            subject = '%s: %s' % (
                record.levelname,
                record.getMessage()
            )
            request = None
        subject = self.format_subject(subject)

        # Since we add a nicely formatted traceback on our own, create a copy
        # of the log record without the exception data.
        no_exc_record = copy(record)
        no_exc_record.exc_info = None
        no_exc_record.exc_text = None

        if record.exc_info:
            exc_info = record.exc_info
        else:
            exc_info = (None, record.getMessage(), None)

        reporter = ExceptionReporter(request, is_email=True, *exc_info)
        message = "%s\n\n%s" % (self.format(no_exc_record), reporter.get_traceback_text())
        html_message = reporter.get_traceback_html() if self.include_html else None
        self.send_mail(subject, message, fail_silently=True, html_message=html_message) 
Example #22
Source File: context_processors.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def debug(request):
    """
    Returns context variables helpful for debugging.
    """
    context_extras = {}
    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
        context_extras['debug'] = True
        from django.db import connection
        # Return a lazy reference that computes connection.queries on access,
        # to ensure it contains queries triggered after this function runs.
        context_extras['sql_queries'] = lazy(lambda: connection.queries, list)
    return context_extras 
Example #23
Source File: middleware.py    From django-maintenancemode-2 with Apache License 2.0 4 votes vote down vote up
def process_request(self, request):
        """
        Check if the current site is in maintenance.
        """

        # First check things that don't require a database access:

        # Allow access if remote ip is in INTERNAL_IPS
        if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
            return None

        # Check if the staff the user is allowed
        if hasattr(request, 'user'):
            if request.user.is_superuser:
                return None

            if not MAINTENANCE_BLOCK_STAFF and request.user.is_staff:
                return None

        # ok let's look at the db
        site = Site.objects.get_current()
        try:
            maintenance = Maintenance.objects.get(site=site)
        except Maintenance.DoesNotExist:
            # Allow access if no matching Maintenance object exists
            return None

        # Allow access if maintenance is not being performed
        if not maintenance.is_being_performed:
            return None

        # Check if a path is explicitly excluded from maintenance mode
        ignored_url_list = set(
            maintenance.ignored_url_patterns() + MAINTENANCE_ADMIN_IGNORED_URLS
        )

        ignored_url_patterns = tuple(
            re.compile(r'{}'.format(url)) for url in ignored_url_list
        )

        request_path = request.path_info.lstrip("/")

        for url in ignored_url_patterns:
            if url.match(request_path):
                return None

        # Otherwise show the user the 503 page
        resolver = resolvers.get_resolver(None)

        resolve = resolver.resolve_error_handler
        callback, param_dict = resolve('503')
        return callback(request, **param_dict)