Python django.conf.settings.DEBUG Examples

The following are 30 code examples for showing how to use django.conf.settings.DEBUG(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: raveberry   Author: raveberry   File: music_provider.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def enqueue(self) -> None:
        for index, external_url in enumerate(self.urls):
            if index == self.musiq.base.settings.basic.max_playlist_items:
                break
            # request every url in the playlist as their own url
            song_provider = SongProvider.create(self.musiq, external_url=external_url)

            try:
                song_provider.request("", archive=False, manually_requested=False)
            except ProviderError:
                continue

            if settings.DEBUG:
                # the sqlite database has problems if songs are pushed very fast
                # while a new song is taken from the queue. Add a delay to mitigate.
                time.sleep(1) 
Example 2
Project: donation-tracker   Author: GamesDoneQuick   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def index(request, **kwargs):
    bundle = webpack_manifest.load(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__), '../ui-tracker.manifest.json')
        ),
        settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None,
    )

    return render(
        request,
        'ui/index.html',
        {
            'event': Event.objects.latest(),
            'events': Event.objects.all(),
            'bundle': bundle.tracker,
            'CONSTANTS': mark_safe(json.dumps(constants())),
            'ROOT_PATH': reverse('tracker:ui:index'),
            'app': 'TrackerApp',
            'form_errors': {},
            'props': '{}',
        },
    ) 
Example 3
Project: coursys   Author: sfu-fas   File: testcase.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _pre_setup(self):
        """Disable transaction methods, and clear some globals."""
        # Repeat stuff from TransactionTestCase, because I'm not calling its
        # _pre_setup, because that would load fixtures again.
        cache.cache.clear()
        settings.TEMPLATE_DEBUG = settings.DEBUG = False


        self.client = self.client_class()
        #self._fixture_setup()
        self._urlconf_setup()
        mail.outbox = []

        # Clear site cache in case somebody's mutated Site objects and then
        # cached the mutated stuff:
        from django.contrib.sites.models import Site
        Site.objects.clear_cache() 
Example 4
Project: coursys   Author: sfu-fas   File: csp.py    License: GNU General Public License v3.0 6 votes vote down vote up
def csp_report_view(request):
    global generic_related
    report_json = request.body.decode('utf8')
    report = json.loads(report_json)
    resp = HttpResponse()

    if ('script-sample' in report['csp-report']
            and 'var t=0,e=function(t,e){ret' in report['csp-report']['script-sample']) or \
            ('script-sample' in report['csp-report'] and report['csp-report']['script-sample'] == ';undefined'):
        # firefox browser plugin injection?
        return resp

    if generic_related is None:
        generic_related = Unit.objects.get(slug='univ')
    userid = request.user.username if request.user.is_authenticated else '_anon'
    l = LogEntry(userid=userid, description='CSP violation', comment=report_json, related_object=generic_related)
    l.save()

    if settings.DEBUG:
        print(json.dumps(report, indent=2))

    return resp 
Example 5
Project: ideascube   Author: ideascube   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def validate_url(request):
    assert request.method == "GET"
    assert request.is_ajax()
    url = request.GET.get('url')
    assert url
    try:
        URLValidator(url)
    except ValidationError:
        raise AssertionError()
    assert 'HTTP_REFERER' in request.META
    toproxy = urlparse(url)
    assert toproxy.hostname
    if settings.DEBUG:
        return url
    referer = urlparse(request.META.get('HTTP_REFERER'))
    assert referer.hostname == request.META.get('SERVER_NAME')
    assert toproxy.hostname != "localhost"
    try:
        # clean this when in python 3.4
        ipaddress = socket.gethostbyname(toproxy.hostname)
    except:
        raise AssertionError()
    assert not ipaddress.startswith('127.')
    assert not ipaddress.startswith('192.168.')
    return url 
Example 6
Project: django-herald   Author: worthwhile   File: base.py    License: MIT License 6 votes vote down vote up
def render(self, render_type, context):
        """
        Renders the template

        :param render_type: the content type to render
        :param context: context data dictionary
        :return: the rendered content
        """

        assert render_type in self.render_types, 'Invalid Render Type'

        try:
            content = render_to_string('herald/{}/{}.{}'.format(
                render_type,
                self.template_name,
                'txt' if render_type == 'text' else render_type
            ), context)
        except TemplateDoesNotExist:
            content = None

            if settings.DEBUG:
                raise

        return content 
Example 7
Project: GTDWeb   Author: lanbing510   File: debug.py    License: GNU General Public License v2.0 6 votes vote down vote up
def default_urlconf(request):
    "Create an empty URLconf 404 error response."
    t = DEBUG_ENGINE.from_string(DEFAULT_URLCONF_TEMPLATE)
    c = Context({
        "title": _("Welcome to Django"),
        "heading": _("It worked!"),
        "subheading": _("Congratulations on your first Django-powered page."),
        "instructions": _("Of course, you haven't actually done any work yet. "
            "Next, start your first app by running <code>python manage.py startapp [app_label]</code>."),
        "explanation": _("You're seeing this message because you have <code>DEBUG = True</code> in your "
            "Django settings file and you haven't configured any URLs. Get to work!"),
    })

    return HttpResponse(t.render(c), content_type='text/html')

#
# Templates are embedded in the file so that we know the error handler will
# always work even if the template loader is broken.
# 
Example 8
Project: GTDWeb   Author: lanbing510   File: common.py    License: GNU General Public License v2.0 6 votes vote down vote up
def process_response(self, request, response):
        """
        Send broken link emails for relevant 404 NOT FOUND responses.
        """
        if response.status_code == 404 and not settings.DEBUG:
            domain = request.get_host()
            path = request.get_full_path()
            referer = force_text(request.META.get('HTTP_REFERER', ''), errors='replace')

            if not self.is_ignorable_request(request, path, domain, referer):
                ua = request.META.get('HTTP_USER_AGENT', '<none>')
                ip = request.META.get('REMOTE_ADDR', '<none>')
                mail_managers(
                    "Broken %slink on %s" % (
                        ('INTERNAL ' if self.is_internal_request(domain, referer) else ''),
                        domain
                    ),
                    "Referrer: %s\nRequested URL: %s\nUser agent: %s\n"
                    "IP address: %s\n" % (referer, path, ua, ip),
                    fail_silently=True)
        return response 
Example 9
Project: GTDWeb   Author: lanbing510   File: defaulttags.py    License: GNU General Public License v2.0 6 votes vote down vote up
def render(self, context):
        csrf_token = context.get('csrf_token', None)
        if csrf_token:
            if csrf_token == 'NOTPROVIDED':
                return format_html("")
            else:
                return format_html("<input type='hidden' name='csrfmiddlewaretoken' value='{}' />", csrf_token)
        else:
            # It's very probable that the token is missing because of
            # misconfiguration, so we raise a warning
            if settings.DEBUG:
                warnings.warn(
                    "A {% csrf_token %} was used in a template, but the context "
                    "did not provide the value.  This is usually caused by not "
                    "using RequestContext."
                )
            return '' 
Example 10
Project: GTDWeb   Author: lanbing510   File: defaulttags.py    License: GNU General Public License v2.0 6 votes vote down vote up
def render(self, context):
        filepath = self.filepath.resolve(context)

        if not include_is_allowed(filepath, context.template.engine.allowed_include_roots):
            if settings.DEBUG:
                return "[Didn't have permission to include file]"
            else:
                return ''  # Fail silently for invalid includes.
        try:
            with open(filepath, 'r') as fp:
                output = fp.read()
        except IOError:
            output = ''
        if self.parsed:
            try:
                t = Template(output, name=filepath, engine=context.template.engine)
                return t.render(context)
            except TemplateSyntaxError as e:
                if settings.DEBUG:
                    return "[Included template had syntax error: %s]" % e
                else:
                    return ''  # Fail silently for invalid included templates.
        return output 
Example 11
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 12
Project: peering-manager   Author: respawner   File: middleware.py    License: Apache License 2.0 6 votes vote down vote up
def process_exception(self, request, exception):
        # Ignore exception catching if debug mode is on
        if settings.DEBUG:
            return

        # Lets Django handling 404
        if isinstance(exception, Http404):
            return

        template = None
        if isinstance(exception, ProgrammingError):
            template = "errors/programming_error.html"
        elif isinstance(exception, ImportError):
            template = "errors/import_error.html"

        if template:
            return ServerError(request, template_name=template) 
Example 13
Project: django-sitemessage   Author: idlesign   File: sitemessage.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render(self, context):
        resolve = lambda arg: arg.resolve(context) if isinstance(arg, FilterExpression) else arg

        prefs_obj = resolve(self.prefs_obj)
        if not isinstance(prefs_obj, tuple):
            if settings.DEBUG:
                raise SiteMessageConfigurationError(
                    '`sitemessage_prefs_table` template tag expects a tuple generated '
                    'by `get_user_preferences_for_ui` but `%s` is given.' % type(prefs_obj))
            return ''  # Silent fall.

        context.push()
        context['sitemessage_user_prefs'] = prefs_obj
        contents = get_template(
            resolve(self.use_template or 'sitemessage/user_prefs_table.html')
        ).render(context.flatten() if _CONTEXT_FLATTEN else context)
        context.pop()

        return contents 
Example 14
Project: ariadne   Author: mirumee   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def execute_query(self, request: HttpRequest, data: dict) -> GraphQLResult:
        context_value = self.get_context_for_request(request)
        extensions = self.get_extensions_for_request(request, context_value)

        return graphql_sync(
            cast(GraphQLSchema, self.schema),
            data,
            context_value=context_value,
            root_value=self.root_value,
            validation_rules=self.validation_rules,
            debug=settings.DEBUG,
            introspection=self.introspection,
            logger=self.logger,
            error_formatter=self.error_formatter or format_error,
            extensions=extensions,
            middleware=self.middleware,
        ) 
Example 15
Project: bioforum   Author: reBiocoder   File: common.py    License: MIT License 6 votes vote down vote up
def get_full_path_with_slash(self, request):
        """
        Return the full path of the request with a trailing slash appended.

        Raise a RuntimeError if settings.DEBUG is True and request.method is
        POST, PUT, or PATCH.
        """
        new_path = request.get_full_path(force_append_slash=True)
        if settings.DEBUG and request.method in ('POST', 'PUT', 'PATCH'):
            raise RuntimeError(
                "You called this URL via %(method)s, but the URL doesn't end "
                "in a slash and you have APPEND_SLASH set. Django can't "
                "redirect to the slash URL while maintaining %(method)s data. "
                "Change your form to point to %(url)s (note the trailing "
                "slash), or set APPEND_SLASH=False in your Django settings." % {
                    'method': request.method,
                    'url': request.get_host() + new_path,
                }
            )
        return new_path 
Example 16
Project: bioforum   Author: reBiocoder   File: common.py    License: MIT License 6 votes vote down vote up
def process_response(self, request, response):
        """Send broken link emails for relevant 404 NOT FOUND responses."""
        if response.status_code == 404 and not settings.DEBUG:
            domain = request.get_host()
            path = request.get_full_path()
            referer = request.META.get('HTTP_REFERER', '')

            if not self.is_ignorable_request(request, path, domain, referer):
                ua = request.META.get('HTTP_USER_AGENT', '<none>')
                ip = request.META.get('REMOTE_ADDR', '<none>')
                mail_managers(
                    "Broken %slink on %s" % (
                        ('INTERNAL ' if self.is_internal_request(domain, referer) else ''),
                        domain
                    ),
                    "Referrer: %s\nRequested URL: %s\nUser agent: %s\n"
                    "IP address: %s\n" % (referer, path, ua, ip),
                    fail_silently=True)
        return response 
Example 17
Project: bioforum   Author: reBiocoder   File: request.py    License: MIT License 6 votes vote down vote up
def get_host(self):
        """Return the HTTP host using the environment or request headers."""
        host = self._get_raw_host()

        # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
        allowed_hosts = settings.ALLOWED_HOSTS
        if settings.DEBUG and not allowed_hosts:
            allowed_hosts = ['localhost', '127.0.0.1', '[::1]']

        domain, port = split_domain_port(host)
        if domain and validate_host(domain, allowed_hosts):
            return host
        else:
            msg = "Invalid HTTP_HOST header: %r." % host
            if domain:
                msg += " You may need to add %r to ALLOWED_HOSTS." % domain
            else:
                msg += " The domain name provided is not valid according to RFC 1034/1035."
            raise DisallowedHost(msg) 
Example 18
Project: bioforum   Author: reBiocoder   File: jinja2.py    License: MIT License 6 votes vote down vote up
def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        super().__init__(params)

        self.context_processors = options.pop('context_processors', [])

        environment = options.pop('environment', 'jinja2.Environment')
        environment_cls = import_string(environment)

        if 'loader' not in options:
            options['loader'] = jinja2.FileSystemLoader(self.template_dirs)
        options.setdefault('autoescape', True)
        options.setdefault('auto_reload', settings.DEBUG)
        options.setdefault('undefined',
                           jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined)

        self.env = environment_cls(**options) 
Example 19
Project: bioforum   Author: reBiocoder   File: defaulttags.py    License: MIT License 6 votes vote down vote up
def render(self, context):
        csrf_token = context.get('csrf_token')
        if csrf_token:
            if csrf_token == 'NOTPROVIDED':
                return format_html("")
            else:
                return format_html("<input type='hidden' name='csrfmiddlewaretoken' value='{}' />", csrf_token)
        else:
            # It's very probable that the token is missing because of
            # misconfiguration, so we raise a warning
            if settings.DEBUG:
                warnings.warn(
                    "A {% csrf_token %} was used in a template, but the context "
                    "did not provide the value.  This is usually caused by not "
                    "using RequestContext."
                )
            return '' 
Example 20
Project: pythonjobs.ie   Author: kimeraapp   File: models.py    License: GNU General Public License v2.0 5 votes vote down vote up
def mail_post_save(signal, instance, sender, created, **kwargs):
    if created and settings.DEBUG == False:
        send_confirmation_mail(instance)
        tweet.apply_async(args=(instance.get_absolute_url(),),
                          countdown=10, serializer='json') 
Example 21
Project: tracker_project   Author: abarto   File: socketio_runserver.py    License: MIT License 5 votes vote down vote up
def get_handler(self, *args, **options):
        """
        Returns the django.contrib.staticfiles handler.
        """
        handler = WSGIHandler()
        try:
            from django.contrib.staticfiles.handlers import StaticFilesHandler
        except ImportError:
            return handler
        use_static_handler = options.get('use_static_handler')
        insecure_serving = options.get('insecure_serving', False)
        if (settings.DEBUG and use_static_handler or
                (use_static_handler and insecure_serving)):
            handler = StaticFilesHandler(handler)
        return handler 
Example 22
Project: gazetteer   Author: LibraryOfCongress   File: errors.py    License: MIT License 5 votes vote down vote up
def process_exception(self, request, exception):
        if settings.DEBUG: #if in DEBUG mode, throw stack trace exceptions as normal
            return None
        if not request.path.startswith(API_BASE): #if its not an API request, handle exceptions normally
            return None
        error_message = get_exception_error_message(exception)
        status_code = get_exception_status_code(exception)
        return render_to_json_response({'error': error_message}, status=status_code) 
Example 23
Project: normandy   Author: mozilla   File: metrics.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, options):
        super().__init__(options)
        if not settings.DEBUG:
            raise ImproperlyConfigured(
                f"The {self.__class__.__name} can only be used if DEBUG=True"
            ) 
Example 24
Project: donation-tracker   Author: GamesDoneQuick   File: public.py    License: Apache License 2.0 5 votes vote down vote up
def websocket_test(request):
    if not settings.DEBUG:
        raise Http404
    socket_url = (
        request.build_absolute_uri(f'{reverse("tracker:index_all")}ws/ping/')
        .replace('https:', 'wss:')
        .replace('http:', 'ws:')
    )
    return views_common.tracker_response(
        request, 'tracker/websocket.html', {'socket_url': socket_url}
    ) 
Example 25
Project: donation-tracker   Author: GamesDoneQuick   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def tracker_response(
    request, template='tracker/index.html', qdict=None, status=200, delegate=None
):
    qdict = tracker_context(request, qdict)
    try:
        starttime = time.time()
        if delegate:
            resp = delegate(request, template, context=qdict, status=status)
        else:
            resp = render(request, template, context=qdict, status=status)
        render_time = time.time() - starttime
        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            resp = HttpResponse(
                json.dumps(connection.queries, ensure_ascii=False, indent=1),
                content_type='application/json;charset=utf-8',
            )
        cache_control = {}
        if request.user.is_anonymous:
            cache_control['public'] = True
        else:
            resp['X-Render-Time'] = render_time
            cache_control['private'] = True
            cache_control['max-age'] = 0
        patch_cache_control(resp, **cache_control)
        return resp
    except Exception as e:
        if request.user.is_staff and not settings.DEBUG:
            return HttpResponse(
                str(type(e)) + '\n\n' + str(e), content_type='text/plain', status=500
            )
        raise 
Example 26
Project: donation-tracker   Author: GamesDoneQuick   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def admin(request):
    bundle = webpack_manifest.load(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__), '../ui-tracker.manifest.json')
        ),
        settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None,
    )

    return render(
        request,
        'ui/index.html',
        {
            'event': Event.objects.latest(),
            'events': Event.objects.all(),
            'bundle': bundle.admin,
            'CONSTANTS': mark_safe(json.dumps(constants())),
            'ROOT_PATH': reverse('tracker:ui:admin'),
            'app': 'AdminApp',
            'form_errors': {},
            'props': mark_safe(
                json.dumps(
                    {}, ensure_ascii=False, cls=serializers.json.DjangoJSONEncoder
                )
            ),
        },
    ) 
Example 27
Project: coursys   Author: sfu-fas   File: csp.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, request):
        token = new_token()
        request.csp_nonce = token
        response = self.get_response(request)
        return response

        if settings.DEBUG:
            header = 'Content-Security-Policy'
        else:
            header = 'Content-Security-Policy-Report-Only'
            return response # short-circuit for now

        if header in response:
            # if the view set the Content-Security-Policy, honour it
            return response

        extra_script_src = " 'nonce-%s'" % (token,)
        extra_style_src = ''
        extra_csp = ''
        if hasattr(response, 'allow_gstatic_csp') and response.allow_gstatic_csp:
            # pages that use Google charts need to load/run that code...
            extra_script_src += " https://www.gstatic.com https://www.google.com 'unsafe-eval'"
            extra_style_src = ' https://www.gstatic.com https://ajax.googleapis.com https://www.google.com'

        if hasattr(response, 'has_inline_script') and response.has_inline_script:
            # 'unsafe-inline' is ignored if a nonce value is present in the source list
            extra_script_src = " 'unsafe-inline'"

        if hasattr(response, 'allow_frames_csp') and response.allow_frames_csp:
            extra_csp += " frame-src 'self'"

        value = "default-src 'self' * ; " \
                "style-src 'self' 'unsafe-inline' %s ; " \
                "img-src 'self' www.sfu.ca data: ; " \
                "font-src 'self' www.sfu.ca ; " \
                "script-src 'self' https://cdnjs.cloudflare.com %s ;%s" \
                % (extra_style_src, extra_script_src, extra_csp)
        value += " report-uri /csp-reports ;"

        response[header] = value
        return response 
Example 28
Project: coursys   Author: sfu-fas   File: profiling.py    License: GNU General Public License v3.0 5 votes vote down vote up
def process_request(self, request):
        if (settings.DEBUG or request.user.is_superuser) and 'prof' in request.GET:
            self.tmpfile = tempfile.mktemp()
            self.prof = hotshot.Profile(self.tmpfile) 
Example 29
Project: coursys   Author: sfu-fas   File: profiling.py    License: GNU General Public License v3.0 5 votes vote down vote up
def process_view(self, request, callback, callback_args, callback_kwargs):
        if (settings.DEBUG or request.user.is_superuser) and 'prof' in request.GET:
            return self.prof.runcall(callback, request, *callback_args, **callback_kwargs) 
Example 30
Project: trove-dashboard   Author: openstack   File: trove.py    License: Apache License 2.0 5 votes vote down vote up
def troveclient(request):
    insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)
    cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None)
    trove_url = base.url_for(request, 'database')
    c = client.Client(request.user.username,
                      request.user.token.id,
                      project_id=request.user.project_id,
                      auth_url=trove_url,
                      insecure=insecure,
                      cacert=cacert,
                      http_log_debug=settings.DEBUG)
    c.client.auth_token = request.user.token.id
    c.client.management_url = trove_url
    return c