Python django.conf.settings.DEBUG Examples
The following are 30
code examples of django.conf.settings.DEBUG().
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: music_provider.py From raveberry with GNU Lesser General Public License v3.0 | 7 votes |
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
Source File: common.py From bioforum with MIT License | 6 votes |
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 #3
Source File: common.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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 #4
Source File: middleware.py From peering-manager with Apache License 2.0 | 6 votes |
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 #5
Source File: base.py From django-herald with MIT License | 6 votes |
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 #6
Source File: views.py From ideascube with GNU Affero General Public License v3.0 | 6 votes |
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 #7
Source File: sitemessage.py From django-sitemessage with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #8
Source File: debug.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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 #9
Source File: defaulttags.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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
Source File: defaulttags.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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
Source File: views.py From ariadne with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #12
Source File: common.py From bioforum with MIT License | 6 votes |
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 #13
Source File: csp.py From coursys with GNU General Public License v3.0 | 6 votes |
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 #14
Source File: request.py From bioforum with MIT License | 6 votes |
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 #15
Source File: testcase.py From coursys with GNU General Public License v3.0 | 6 votes |
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 #16
Source File: jinja2.py From bioforum with MIT License | 6 votes |
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 #17
Source File: views.py From donation-tracker with Apache License 2.0 | 6 votes |
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 #18
Source File: defaulttags.py From bioforum with MIT License | 6 votes |
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 #19
Source File: views.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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 #20
Source File: setting.py From DCRM with GNU Affero General Public License v3.0 | 5 votes |
def debug_(self, instance): if settings.DEBUG: return _("Enabled") else: return _("Disabled")
Example #21
Source File: base.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def check_debug(app_configs, **kwargs): passed_check = not settings.DEBUG return [] if passed_check else [W018]
Example #22
Source File: runserver.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def handle(self, *args, **options): from django.conf import settings if not settings.DEBUG and not settings.ALLOWED_HOSTS: raise CommandError('You must set settings.ALLOWED_HOSTS if DEBUG is False.') self.use_ipv6 = options.get('use_ipv6') if self.use_ipv6 and not socket.has_ipv6: raise CommandError('Your Python does not support IPv6.') self._raw_ipv6 = False if not options.get('addrport'): self.addr = '' self.port = DEFAULT_PORT else: m = re.match(naiveip_re, options['addrport']) if m is None: raise CommandError('"%s" is not a valid port number ' 'or address:port pair.' % options['addrport']) self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups() if not self.port.isdigit(): raise CommandError("%r is not a valid port number." % self.port) if self.addr: if _ipv6: self.addr = self.addr[1:-1] self.use_ipv6 = True self._raw_ipv6 = True elif self.use_ipv6 and not _fqdn: raise CommandError('"%s" is not a valid IPv6 address.' % self.addr) if not self.addr: self.addr = '::1' if self.use_ipv6 else '127.0.0.1' self._raw_ipv6 = bool(self.use_ipv6) self.run(**options)
Example #23
Source File: base.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def load_middleware(self): """ Populate middleware lists from settings.MIDDLEWARE_CLASSES. Must be called after the environment is fixed (see __call__ in subclasses). """ self._view_middleware = [] self._template_response_middleware = [] self._response_middleware = [] self._exception_middleware = [] request_middleware = [] for middleware_path in settings.MIDDLEWARE_CLASSES: mw_class = import_string(middleware_path) try: mw_instance = mw_class() except MiddlewareNotUsed as exc: if settings.DEBUG: if six.text_type(exc): logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc) else: logger.debug('MiddlewareNotUsed: %r', middleware_path) continue if hasattr(mw_instance, 'process_request'): request_middleware.append(mw_instance.process_request) if hasattr(mw_instance, 'process_view'): self._view_middleware.append(mw_instance.process_view) if hasattr(mw_instance, 'process_template_response'): self._template_response_middleware.insert(0, mw_instance.process_template_response) if hasattr(mw_instance, 'process_response'): self._response_middleware.insert(0, mw_instance.process_response) if hasattr(mw_instance, 'process_exception'): self._exception_middleware.insert(0, mw_instance.process_exception) # We only assign to this when initialization is complete as it is used # as a flag for initialization being complete. self._request_middleware = request_middleware
Example #24
Source File: options.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def media(self): extra = '' if settings.DEBUG else '.min' js = ['jquery%s.js' % extra, 'jquery.init.js', 'inlines%s.js' % extra] if self.prepopulated_fields: js.extend(['urlify.js', 'prepopulate%s.js' % extra]) if self.filter_vertical or self.filter_horizontal: js.extend(['SelectBox.js', 'SelectFilter2.js']) return forms.Media(js=[static('admin/js/%s' % url) for url in js])
Example #25
Source File: middleware.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def process_response(self, request, response): if response.status_code != 404: return response # No need to check for a flatpage for non-404 responses. try: return flatpage(request, request.path_info) # Return the original response if any errors happened. Because this # is a middleware, we can't assume the errors will be caught elsewhere. except Http404: return response except Exception: if settings.DEBUG: raise return response
Example #26
Source File: runserver.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def get_handler(self, *args, **options): """ Returns the static files serving handler wrapping the default handler, if static files should be served. Otherwise just returns the default handler. """ handler = super(Command, self).get_handler(*args, **options) use_static_handler = options.get('use_static_handler', True) insecure_serving = options.get('insecure_serving', False) if use_static_handler and (settings.DEBUG or insecure_serving): return StaticFilesHandler(handler) return handler
Example #27
Source File: runserver.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument('--nostatic', action="store_false", dest='use_static_handler', default=True, help='Tells Django to NOT automatically serve static files at STATIC_URL.') parser.add_argument('--insecure', action="store_true", dest='insecure_serving', default=False, help='Allows serving static files even if DEBUG is False.')
Example #28
Source File: handlers.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def get_response(self, request): from django.http import Http404 if self._should_handle(request.path): try: return self.serve(request) except Http404 as e: if settings.DEBUG: from django.views import debug return debug.technical_404_response(request, e) return super(StaticFilesHandler, self).get_response(request)
Example #29
Source File: storage.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def url(self, name, force=False): """ Returns the real URL in DEBUG mode. """ if settings.DEBUG and not force: hashed_name, fragment = name, '' else: clean_name, fragment = urldefrag(name) if urlsplit(clean_name).path.endswith('/'): # don't hash paths hashed_name = name else: hashed_name = self.stored_name(clean_name) final_url = super(HashedFilesMixin, self).url(hashed_name) # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax query_fragment = '?#' in name # [sic!] if fragment or query_fragment: urlparts = list(urlsplit(final_url)) if fragment and not urlparts[4]: urlparts[4] = fragment if query_fragment and not urlparts[3]: urlparts[2] += '?' final_url = urlunsplit(urlparts) return unquote(final_url)
Example #30
Source File: runner.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def __init__(self, stream, descriptions, verbosity): self.logger = logging.getLogger('django.db.backends') self.logger.setLevel(logging.DEBUG) super(DebugSQLTextTestResult, self).__init__(stream, descriptions, verbosity)