コード例 #1
0
 def content(self):
     context = self.context.copy()
     context.update({
         'settings': get_safe_settings(),
     })
     return render_to_string('debug_toolbar/panels/settings_vars.html',
                             context)
コード例 #2
0
ファイル: views.py プロジェクト: disisid/fun-apps
def selftest_index(request):
    if not request.user.is_superuser:
        raise Http404

    emailform = EmailForm(request.POST or None)

    if request.method == 'POST':
        if emailform.is_valid():
            subj = "Test email from FUN server %s %s" % (settings.SERVICE_VARIANT, settings.SITE_NAME)
            msg = emailform.cleaned_data['text']
            to = emailform.cleaned_data['to']
            send_mail(subj, msg, settings.SERVER_EMAIL, [to])
            messages.add_message(request, messages.INFO, 'Mail sent to %s.' % to)
            return HttpResponseRedirect(reverse('self-test-index'))

    misc = {}
    misc['get_language'] = get_language()
    misc['platform_node'] = platform.node()

    revisions = {}
    for repo in repositories:
        os.chdir(settings.BASE_ROOT / repo)
        git.path = settings.BASE_ROOT / repo
        git.init_repo()
        revisions[repo] = mark_safe(git.repo.git('log -1 --format=<strong>%h</strong>&nbsp;%aD<br><strong>%s</strong>&nbsp;%ae'))
    return render(request, 'selftest/index.html', {
        'emailform': emailform,
        'misc': misc,
        'settings': get_safe_settings(),
        'environ': os.environ,
        'revisions': revisions,

    })
コード例 #3
0
def handle404(request):
    # This code is modified from views/debug.py in Django, as we want to display
    # a debug style view, just modified slightly.
    exc_info = sys.exc_info()
    exception = exc_info[1]

    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []

    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    if isinstance(urlconf, types.ModuleType):
        urlconf = urlconf.__name__

    c = Context({
        'urlconf': urlconf,
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': request.path_info[1:],  # Trim leading slash
        'urlpatterns': tried,
        'reason': force_bytes(exception, errors='replace'),
        'request': request,
        'settings': get_safe_settings(),
    })

    return HttpResponseNotFound(
        render_to_string('splunkdj:404.html', context_instance=c))
コード例 #4
0
ファイル: resources.py プロジェクト: mstriemer/solitude
def settings_view(request, setting):
    if not getattr(settings, 'CLEANSED_SETTINGS_ACCESS', False):
        raise PermissionDenied
    return Response({
        'key': setting,
        'value': debug.get_safe_settings()[setting]
    })
コード例 #5
0
ファイル: views.py プロジェクト: grefly/splunk-apps
def handle404(request):    
    # This code is modified from views/debug.py in Django, as we want to display
    # a debug style view, just modified slightly.
    exc_info = sys.exc_info()
    exception = exc_info[1]
    
    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []

    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    if isinstance(urlconf, types.ModuleType):
        urlconf = urlconf.__name__

    c = Context({
        'urlconf': urlconf,
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': request.path_info[1:], # Trim leading slash
        'urlpatterns': tried,
        'reason': force_bytes(exception, errors='replace'),
        'request': request,
        'settings': get_safe_settings(),
    })
    
    return HttpResponseNotFound(render_to_string('splunkdj:404.html', context_instance=c))
コード例 #6
0
ファイル: settings.py プロジェクト: Liu0330/zufang
 def generate_stats(self, request, response):
     self.record_stats(
         {
             "settings": OrderedDict(
                 sorted(get_safe_settings().items(), key=lambda s: s[0])
             )
         }
     )
コード例 #7
0
 def get_context(self):
     """
     Override this to change context
     """
     return {
         'settings': get_safe_settings(),
         'bundles': get_bundles(),
         }
コード例 #8
0
 def get_context(self):
     """
     Override this to change context
     """
     return {
         'settings': get_safe_settings(),
         'bundles': get_bundles(),
     }
コード例 #9
0
ファイル: common.py プロジェクト: Lispython/jobboard
 def __getattr__(self, name):
     if self._settings is None:
         self._settings = get_safe_settings()
     name = name.upper()
     try:
         return self._settings[name]
     except KeyError:
         raise AttributeError
コード例 #10
0
 def generate_stats(self, request, response):
     self.record_stats(
         {
             "settings": OrderedDict(
                 sorted(get_safe_settings().items(), key=lambda s: s[0])
             )
         }
     )
コード例 #11
0
ファイル: htv1.py プロジェクト: jsa/gae-django-hoptoad
def _parse_environment(request):
    """Return an environment mapping for a notification from the given request."""
    env = dict( (str(k), str(v)) for (k, v) in get_safe_settings().items() )
    env.update( dict( (str(k), str(v)) for (k, v) in request.META.items() ) )
    
    env['REQUEST_URI'] = request.build_absolute_uri()
    
    return env
コード例 #12
0
ファイル: views.py プロジェクト: zzdjk6/kuma
def settings(request):
    """Admin view that displays the django settings."""
    settings = debug.get_safe_settings()
    sorted_settings = [{'key': key, 'value': settings[key]} for
                       key in sorted(settings.keys())]

    return render_to_response('kadmin/settings.html',
                              {'settings': sorted_settings},
                              RequestContext(request, {}))
コード例 #13
0
ファイル: views.py プロジェクト: chowse/kitsune
def settings(request):
    """Admin view that displays the django settings."""
    settings = debug.get_safe_settings()
    sorted_settings = [{'key': key, 'value': settings[key]}
                       for key in sorted(settings.keys())]

    return render_to_response('kadmin/settings.html',
                              {'settings': sorted_settings},
                              RequestContext(request, {}))
コード例 #14
0
    def process_response(self, request, response):
        if settings.DEBUG:
            # Request report.
            req_report = {
                'path': request.path_info,
                'get': [(k, request.GET.getlist(k)) for k in request.GET],
                'post': [(k, request.POST.getlist(k)) for k in request.POST],
                'cookies': [(k, request.COOKIES.get(k)) for k in request.COOKIES],
                'view': {
                    'func': '<no view>',
                    'args': 'None',
                    'kwargs': 'None',
                    'url': 'None',
                },
                'headers': dict(
                    [(k, request.META[k]) for k in self.HEADER_FILTER if k in request.META]
                ),
                'settings': SortedDict(sorted(get_safe_settings().items(), key=lambda s: s[0])),
            }

            try:
                match = resolve(request.path)
                func, args, kwargs = match
                req_report['view']['func'] = self._get_name_from_obj(func)
                req_report['view']['args'] = args
                req_report['view']['kwargs'] = kwargs
                req_report['view']['url'] = getattr(match, 'url_name', '<unavailable>')
            except Http404:
                req_report['view']['func'] = request.path
                pass

            if hasattr(request, 'session'):
                req_report['session'] = [
                    (k, request.session.get(k))
                    for k in request.session.iterkeys()
                ]

            # MySQL report.
            mysql_report = {
                'time': sum([float(q['time']) for q in connection.queries]),
                'log': [{'time': q['time'], 'sql': q['sql']} for q in connection.queries],
            }

            # Log.
            context = Context({'req': req_report, 'mysql': mysql_report})
            if settings.DEBUG:
                logging.\
                    getLogger('vbm').\
                    debug(loader.get_template('varnish-bans-manager/partials/_debug.txt').render(context))
            report = loader.get_template('varnish-bans-manager/partials/_debug.html').render(context)
            if isinstance(response, HttpResponseAjax):
                response.add_command(commands.debug(report))
            elif _can_append_script(response):
                script = '<script type="text/javascript">(function ($) { vbm.ready(function(context) { vbm.commands.debug(%s); });})(jQuery);</script>' % (json.dumps(report))
                _append_script(response, script)

        return response
コード例 #15
0
ファイル: admin_views.py プロジェクト: daqing15/PyLucid
def show_internals(request):
    apps_info = []
    for app in get_apps():
        model_info = []
        for model in get_models(app):
            model_info.append({
                "name":model._meta.object_name,
            })
        apps_info.append({
            "app_name": app.__name__,
            "app_models": model_info,
        })

    # from http://www.djangosnippets.org/snippets/1434/
    # generate a list of (pattern-name, pattern) tuples
    resolver = urlresolvers.get_resolver(None)
    urlpatterns = sorted([
        (key, value[0][0][0])
        for key, value in resolver.reverse_dict.items()
        if isinstance(key, basestring)
    ])

    context = {
        "title": "Show internals",

        "pid": os.getpid(),
        "cache_information": LocalSyncCache.get_cache_information(),

        "permissions": Permission.objects.all(),

        "urlpatterns": urlpatterns,
        "settings": hightlighter.make_html(
            pformat(get_safe_settings()), source_type="py", django_escape=True
        ),

        "db_backend_name": backend.Database.__name__,
        "db_backend_module": backend.Database.__file__,
        "db_backend_version": getattr(backend.Database, "version", "?"),

        "apps_info": apps_info,

        "db_table_names": sorted(connection.introspection.table_names()),
        "django_tables": sorted(connection.introspection.django_table_names()),

        "request_meta": hightlighter.make_html(
            pformat(request.META), source_type="py", django_escape=True
        ),

        "request_session": hightlighter.make_html(
            pformat(dict(request.session)), source_type="py", django_escape=True
        ),

        "sys_path": sys.path,
        "os_environ": os.environ,
    }
    return context
コード例 #16
0
ファイル: admin.py プロジェクト: gitter-badger/IGPython
def settings(request):
    """Admin view that displays the django settings."""
    settings = debug.get_safe_settings()
    sorted_settings = [{'key': key, 'value': settings[key]} for
                       key in sorted(settings.keys())]

    return render('base/settings.html',
                              {'settings': sorted_settings,
                               'title': 'Settings'},
                              RequestContext(request, {}))
コード例 #17
0
    def process_response(self, request, response):
        if getattr(settings, 'DEBUG_LOGGING_CONFIG', {}).get('ENABLED', False):
            # Logging is enabled, so log the settings
            safe_settings = get_safe_settings()
            log_settings = {}
            for k, v in safe_settings.items():
                if self.logged_settings_re.search(k):
                    log_settings[k] = v

            request.debug_logging_stats['settings'] = log_settings
コード例 #18
0
ファイル: views.py プロジェクト: Dreadchild/zamboni
def show_settings(request):
    settings_dict = debug.get_safe_settings()

    for i in ['GOOGLE_ANALYTICS_CREDENTIALS']:
        settings_dict[i] = debug.cleanse_setting(i, getattr(settings, i, {}))

    settings_dict['WEBAPPS_RECEIPT_KEY'] = '********************'

    return render(request, 'zadmin/settings.html',
                  {'settings_dict': settings_dict})
コード例 #19
0
ファイル: admin.py プロジェクト: B-Rich/fjord
def settings_view(request):
    """Admin view that displays the django settings."""
    settings = debug.get_safe_settings()
    sorted_settings = [{'key': key, 'value': settings[key]}
                       for key in sorted(settings.keys())]

    return render(request, 'admin/settings_view.html', {
            'settings': sorted_settings,
            'title': 'App Settings'
            })
コード例 #20
0
ファイル: admin.py プロジェクト: tobbi/kitsune
def settings(request):
    """Admin view that displays the django settings."""
    settings = debug.get_safe_settings()
    sorted_settings = [{"key": key, "value": settings[key]} for key in sorted(settings.keys())]

    return render_to_response(
        "kadmin/settings.html",
        {"pythonpath": sys.path, "settings": sorted_settings, "title": "Settings"},
        RequestContext(request, {}),
    )
コード例 #21
0
def settings_view(request):
    """Admin view that displays the django settings."""
    settings = debug.get_safe_settings()
    sorted_settings = [{'key': key, 'value': settings[key]}
                       for key in sorted(settings.keys())]

    return render(request, 'admin/settings_view.html', {
        'settings': sorted_settings,
        'title': 'App Settings'
    })
コード例 #22
0
ファイル: views.py プロジェクト: exezaid/zamboni
def settings(request):
    settings_dict = debug.get_safe_settings()

    # sigh
    settings_dict['HERA'] = []
    for i in site_settings.HERA:
        settings_dict['HERA'].append(debug.cleanse_setting('HERA', i))

    return jingo.render(request, 'zadmin/settings.html',
                        {'settings_dict': settings_dict})
コード例 #23
0
    def process_response(self, request, response):
        if getattr(request, 'debug_logging', {}).get('ENABLED', False):
            # Logging is enabled, so log the settings

            safe_settings = get_safe_settings()
            log_settings = {}
            for k, v in safe_settings.items():
                if request.debug_logging['LOGGED_SETTINGS_RE'].search(k):
                    log_settings[k] = v

            request.debug_logging_stats['settings'] = log_settings
コード例 #24
0
    def process_response(self, request, response):
        if getattr(request, 'debug_logging', {}).get('ENABLED', False):
            # Logging is enabled, so log the settings

            safe_settings = get_safe_settings()
            log_settings = {}
            for k, v in safe_settings.items():
                if request.debug_logging['LOGGED_SETTINGS_RE'].search(k):
                    log_settings[k] = v

            request.debug_logging_stats['settings'] = log_settings
コード例 #25
0
ファイル: views.py プロジェクト: tsl143/addons-server
def show_settings(request):
    settings_dict = debug.get_safe_settings()

    # Retain this so that GOOGLE_ANALYTICS_CREDENTIALS variables in local
    # settings are not exposed.
    google_cred = 'GOOGLE_ANALYTICS_CREDENTIALS'
    settings_dict[google_cred] = debug.cleanse_setting(
        google_cred, getattr(settings, google_cred, {}))

    return render(request, 'zadmin/settings.html',
                  {'settings_dict': settings_dict, 'title': 'Settings!'})
コード例 #26
0
ファイル: views.py プロジェクト: Witia1/zamboni
def show_settings(request):
    settings_dict = debug.get_safe_settings()

    for i in ['GOOGLE_ANALYTICS_CREDENTIALS']:
        settings_dict[i] = debug.cleanse_setting(i,
                                                 getattr(settings, i, {}))

    settings_dict['WEBAPPS_RECEIPT_KEY'] = '********************'

    return render(request, 'zadmin/settings.html',
                  {'settings_dict': settings_dict})
コード例 #27
0
def settings(request):
    """Admin view that displays the django settings."""
    settings = debug.get_safe_settings()
    sorted_settings = [
        {"key": key, "value": settings[key]} for key in sorted(settings.keys())
    ]

    return render_to_response(
        "kadmin/settings.html",
        {"pythonpath": sys.path, "settings": sorted_settings, "title": "Settings"},
        RequestContext(request, {}),
    )
コード例 #28
0
ファイル: htv1.py プロジェクト: greghball/django-hoptoad
def _parse_environment(request):
    """Return an environment mapping for a notification
    from the given request.

    """

    env = dict((str(k), str(v)) for (k, v) in get_safe_settings().items())
    env.update(dict((str(k), str(v)) for (k, v) in request.META.items()))

    env['REQUEST_URI'] = request.build_absolute_uri()

    return env
コード例 #29
0
ファイル: views.py プロジェクト: MechanisM/zamboni
def settings(request):
    settings_dict = debug.get_safe_settings()

    # sigh
    settings_dict["HERA"] = []
    for i in site_settings.HERA:
        settings_dict["HERA"].append(debug.cleanse_setting("HERA", i))

    for i in ["PAYPAL_EMBEDDED_AUTH", "PAYPAL_CGI_AUTH"]:
        settings_dict[i] = debug.cleanse_setting(i, getattr(site_settings, i))

    return jingo.render(request, "zadmin/settings.html", {"settings_dict": settings_dict})
コード例 #30
0
ファイル: views.py プロジェクト: psionikangel/addons-server
def show_settings(request):
    settings_dict = debug.get_safe_settings()

    # Retain this so that legacy PAYPAL_CGI_AUTH variables in local settings
    # are not exposed.
    for i in ['PAYPAL_EMBEDDED_AUTH', 'PAYPAL_CGI_AUTH',
              'GOOGLE_ANALYTICS_CREDENTIALS']:
        settings_dict[i] = debug.cleanse_setting(i,
                                                 getattr(settings, i, {}))

    return render(request, 'zadmin/settings.html',
                  {'settings_dict': settings_dict})
コード例 #31
0
def show_settings(request):
    settings_dict = debug.get_safe_settings()

    # Retain this so that legacy PAYPAL_CGI_AUTH variables in local settings
    # are not exposed.
    for i in ['PAYPAL_EMBEDDED_AUTH', 'PAYPAL_CGI_AUTH',
              'GOOGLE_ANALYTICS_CREDENTIALS']:
        settings_dict[i] = debug.cleanse_setting(i,
                                                 getattr(settings, i, {}))

    return render(request, 'zadmin/settings.html',
                  {'settings_dict': settings_dict})
コード例 #32
0
ファイル: middleware.py プロジェクト: oomora/CRM
def debug_payload(request, response, view_data):

    current_session = {}

    if 'django.contrib.sessions' in settings.INSTALLED_APPS:
        if request.session.items():
            for k,v in request.session.items():
                current_session[k] = v

    if request.user.is_anonymous:
        user_data = "[\"Anonymous User\"]"
    else:
        user_data = serializers.serialize("json", [request.user])

    resolved_url = resolve(request.path)

    view = {
        'view_name': resolved_url._func_path,
        'view_args': resolved_url.args,
        'view_kwargs': resolved_url.kwargs,
        'view_methods': VIEW_METHOD_DATA,
        'cbv': view_data.get('cbv', False),
        'bases': view_data.get('bases', []),
    }

    checks = {}
    raw_checks = run_checks(include_deployment_checks=True)

    for check in raw_checks:
        checks[check.id] = check.msg

    json_friendly_settings = OrderedDict()
    s = get_safe_settings()
    for key in sorted(s.keys()):
        json_friendly_settings[key] = str(s[key])

    payload = {
        'version': django.VERSION,
        'current_user': json.loads(user_data)[0],
        'db_queries': connection.queries,
        'session': current_session,
        'view_data': view,
        'url_name': resolved_url.url_name,
        'url_namespaces': resolved_url.namespaces,
        'checks': checks,
        'settings': json_friendly_settings
    }

    payload_script = "<script>var dj_chrome = {};</script>".format(json.dumps(payload,
                                                                              cls=LazyEncoder))

    return payload_script
コード例 #33
0
def task_failure_callback(
    sender,
    task_id=None,
    exception=None,
    args=None,
    kwargs=None,
    traceback=None,
    einfo=None,
    **remaining
):
    tracked_request = TrackedRequest.instance()
    tracked_request.tag("error", "true")

    custom_controller = sender.name
    custom_params = {
        "celery": {
            "task_id": task_id,
            "args": args,
            "kwargs": kwargs,
        }
    }

    # Look up the django settings if populated.
    environment = None
    if get_safe_settings:
        try:
            environment = get_safe_settings()
        except django.core.exceptions.ImproperlyConfigured as exc:
            # Django not setup correctly
            logger.debug(
                "Celery integration does not have django configured properly: %r", exc
            )
            pass
        except Exception as exc:
            logger.debug(
                "Celery task_failure callback exception: %r", exc, exc_info=exc
            )
            pass

    # Celery occassionally will send the traceback as a string rather
    # than a Stack trace object as the docs indicate. In that case,
    # fall back to the billiard ExceptionInfo instance
    traceback = (
        traceback if traceback and not isinstance(traceback, string_type) else einfo.tb
    )
    exc_info = (exception.__class__, exception, traceback)
    ErrorMonitor.send(
        exc_info,
        environment=environment,
        custom_params=custom_params,
        custom_controller=custom_controller,
    )
コード例 #34
0
 def __getattr__(self, name):
     # Lazy load of settings.
     if self._settings is None:
         self._settings = get_safe_settings()
     # get_safe_settings only returns upper case settings, so let's not worry
     # about case sensitivity.
     name = name.upper()
     try:
         return self._settings[name]
     except KeyError:
         # This method should return the (computed) attribute value or raise
         # an AttributeError exception.
         raise AttributeError
コード例 #35
0
ファイル: views.py プロジェクト: mishin/addons-server
def show_settings(request):
    settings_dict = debug.get_safe_settings()

    # Retain this so that GOOGLE_ANALYTICS_CREDENTIALS variables in local
    # settings are not exposed.
    google_cred = 'GOOGLE_ANALYTICS_CREDENTIALS'
    settings_dict[google_cred] = debug.cleanse_setting(
        google_cred, getattr(settings, google_cred, {}))

    return render(request, 'zadmin/settings.html', {
        'settings_dict': settings_dict,
        'title': 'Settings!'
    })
コード例 #36
0
 def __getattr__(self, name):
     # Lazy load of settings.
     if self._settings is None:
         self._settings = get_safe_settings()
         # get_safe_settings only returns upper case settings, so let's not worry
     # about case sensitivity.
     name = name.upper()
     try:
         return self._settings[name]
     except KeyError:
         # This method should return the (computed) attribute value or raise
         # an AttributeError exception.
         raise AttributeError
コード例 #37
0
def settings(request):
    settings_dict = debug.get_safe_settings()

    # sigh
    settings_dict['HERA'] = []
    for i in site_settings.HERA:
        settings_dict['HERA'].append(debug.cleanse_setting('HERA', i))

    for i in ['PAYPAL_EMBEDDED_AUTH', 'PAYPAL_CGI_AUTH']:
        settings_dict[i] = debug.cleanse_setting(i, getattr(site_settings, i))

    return jingo.render(request, 'zadmin/settings.html',
                        {'settings_dict': settings_dict})
コード例 #38
0
 def on_got_request_exception(self, request, **kwargs):
     """
     Process this exception with the error monitoring solution.
     """
     ErrorMonitor.send(
         sys.exc_info(),
         request_components=get_request_components(request),
         request_path=request.path,
         request_params=dict(request.GET.lists()),
         session=dict(request.session.items()) if hasattr(
             request, "session") else None,
         environment=get_safe_settings(),
     )
コード例 #39
0
ファイル: admin_views.py プロジェクト: ckolumbus/PyLucid
def show_internals(request):
    apps_info = []
    for app in get_apps():
        model_info = []
        for model in get_models(app):
            model_info.append({
                "name":model._meta.object_name,
            })
        apps_info.append({
            "app_name": app.__name__,
            "app_models": model_info,
        })


    # Information about the current used url patterns
    urlpatterns = UrlPatternInfo().get_url_info()

    context = {
        "title": "Show internals",

        "pid": os.getpid(),
        "cache_information": LocalSyncCache.get_cache_information(),

        "permissions": Permission.objects.all(),

        "urlpatterns": urlpatterns,
        "settings": hightlighter.make_html(
            pformat(get_safe_settings()), source_type="py", django_escape=True
        ),

        "db_backend_name": backend.Database.__name__,
        "db_backend_module": backend.Database.__file__,
        "db_backend_version": getattr(backend.Database, "version", "?"),

        "apps_info": apps_info,

        "db_table_names": sorted(connection.introspection.table_names()),
        "django_tables": sorted(connection.introspection.django_table_names()),

        "request_meta": hightlighter.make_html(
            pformat(request.META), source_type="py", django_escape=True
        ),

        "request_session": hightlighter.make_html(
            pformat(dict(request.session)), source_type="py", django_escape=True
        ),

        "sys_path": sys.path,
        "os_environ": os.environ,
    }
    return context
コード例 #40
0
    def settings_info(self):
        """
        display current used 'settings.py'
        """
        context = []

        safe_settings = get_safe_settings()
        for key, value in safe_settings.iteritems():
            value = pprint.pformat(value)
            value = escape(value)
            context.append({"attrname": key, "value": value})

        context.sort()

        return context
コード例 #41
0
def status(request):
    def anyfn(fn, iterable):
        for e in iterable:
            if fn(e):
                return True
        return False

    render_data = {
        'request': request,
        'title': 'Admin Status',
        'user': request.user,
        'root_path': webhelpers.url("/"),
        'settings': get_safe_settings(),
    }

    return render(request, 'yabi/admin_status.html', render_data)
コード例 #42
0
ファイル: views.py プロジェクト: pennyfx/zamboni
def settings(request):
    settings_dict = debug.get_safe_settings()

    # sigh
    settings_dict["HERA"] = []
    for i in site_settings.HERA:
        settings_dict["HERA"].append(debug.cleanse_setting("HERA", i))

    # Retain this so that legacy PAYPAL_CGI_AUTH variables in settings_local
    # are not exposed.
    for i in ["PAYPAL_EMBEDDED_AUTH", "PAYPAL_CGI_AUTH"]:
        settings_dict[i] = debug.cleanse_setting(i, getattr(site_settings, i))

    settings_dict["WEBAPPS_RECEIPT_KEY"] = "********************"

    return jingo.render(request, "zadmin/settings.html", {"settings_dict": settings_dict})
コード例 #43
0
ファイル: adminviews.py プロジェクト: muccg/yabi
def status(request):

    def anyfn(fn, iterable):
        for e in iterable:
            if fn(e):
                return True
        return False

    render_data = {
        'request': request,
        'title': 'Admin Status',
        'user': request.user,
        'root_path': webhelpers.url("/"),
        'settings': get_safe_settings(),
    }

    return render(request, 'yabi/admin_status.html', render_data)
コード例 #44
0
def scripts(request):
    """
    Scripts communs:
    """
    context = {}
    for key, value in get_safe_settings().items():
        try:
            json_encode(value)
        except TypeError:
            continue
        context[key] = value

    return {
        'urls': json_encode(get_urls(request).data),
        'user': json_encode(user_infos(request).data),
        'context': json_encode(context),
    }
コード例 #45
0
def admin_site_version(request):
    if request.user.is_superuser:
        from zorna import get_version
        import django
        import sys
        from django.views import debug
        extra_context = {}
        extra_context['zorna_version'] = get_version()
        extra_context['django_version'] = django.get_version()
        extra_context['python_version'] = sys.version
        extra_context['settings'] = debug.get_safe_settings()
        context = RequestContext(request)
        return render_to_response('site/version.html',
                                  extra_context,
                                  context_instance=context)
    else:
        return HttpResponseForbidden()
コード例 #46
0
ファイル: views.py プロジェクト: beenishkhan/zamboni
def settings(request):
    settings_dict = debug.get_safe_settings()

    # sigh
    settings_dict['HERA'] = []
    for i in site_settings.HERA:
        settings_dict['HERA'].append(debug.cleanse_setting('HERA', i))

    # Retain this so that legacy PAYPAL_CGI_AUTH variables in settings_local
    # are not exposed.
    for i in ['PAYPAL_EMBEDDED_AUTH', 'PAYPAL_CGI_AUTH']:
        settings_dict[i] = debug.cleanse_setting(i, getattr(site_settings, i))

    settings_dict['WEBAPPS_RECEIPT_KEY'] = '********************'

    return jingo.render(request, 'zadmin/settings.html',
                        {'settings_dict': settings_dict})
コード例 #47
0
ファイル: views.py プロジェクト: pennyfx/zamboni
def settings(request):
    settings_dict = debug.get_safe_settings()

    # sigh
    settings_dict['HERA'] = []
    for i in site_settings.HERA:
        settings_dict['HERA'].append(debug.cleanse_setting('HERA', i))

    # Retain this so that legacy PAYPAL_CGI_AUTH variables in settings_local
    # are not exposed.
    for i in ['PAYPAL_EMBEDDED_AUTH', 'PAYPAL_CGI_AUTH']:
        settings_dict[i] = debug.cleanse_setting(i, getattr(site_settings, i))

    settings_dict['WEBAPPS_RECEIPT_KEY'] = '********************'

    return jingo.render(request, 'zadmin/settings.html',
                        {'settings_dict': settings_dict})
コード例 #48
0
ファイル: debug.py プロジェクト: mjtorn/dhp
def technical_404_response(request, exception):
    """Create a technical 404 error response. The exception should be the Http404.
    Based on Django.
    """

    fake_url_pattern = FakeUrlPattern(utils.get_path_to_serve(request))

    t = Template(debug.TECHNICAL_404_TEMPLATE, name='Technical 404 template')
    c = Context({
        'urlconf': 'DHP',
        'root_urlconf': 'N/A',
        'request_path': request.path_info[1:], # Trim leading slash
        'urlpatterns': fake_url_pattern,
        'reason': smart_str(exception, errors='replace'),
        'request': request,
        'settings': debug.get_safe_settings(),
    })
    return HttpResponseNotFound(t.render(c), mimetype='text/html')
コード例 #49
0
def environment_settings_view(request,
                              template_name='environment-report.html'):
    """
    Generate a report of the django environment.

    Only Superusers have access to it.
    """
    context = {
        'settings': get_safe_settings(),
        'installed_packages': get_installed_packages(),
        'versions': get_versions(),
        'python_paths': get_python_paths(),
        'db': get_db_info(),
        'migrations': get_migrations(),
        'locales': get_system_locales(),
        'locale_info': get_locale_info(),
    }

    return render(request, template_name, context)
コード例 #50
0
ファイル: views.py プロジェクト: oplarshad/fun-apps
def selftest_index(request):
    if not request.user.is_superuser:
        raise Http404

    emailform = EmailForm(request.POST or None)

    if request.method == 'POST':
        if emailform.is_valid():
            subj = "Test email from FUN server %s %s" % (
                settings.SERVICE_VARIANT, settings.SITE_NAME)
            msg = emailform.cleaned_data['text']
            to = emailform.cleaned_data['to']
            send_mail(subj, msg, settings.SERVER_EMAIL, [to])
            messages.add_message(request, messages.INFO,
                                 'Mail sent to %s.' % to)
            return HttpResponseRedirect(reverse('self-test-index'))

    misc = {}
    misc['get_language'] = get_language()
    misc['platform_node'] = platform.node()

    revisions = {}
    for repo in repositories:
        try:
            os.chdir(settings.BASE_ROOT / repo)
            git.path = settings.BASE_ROOT / repo
            git.init_repo()
            revisions[repo] = mark_safe(
                git.repo.git(
                    'log -1 --decorate --format=<strong>%h</strong>&nbsp;%aD&nbsp;%d<br><strong>%s</strong>&nbsp;%ae'
                ))
        except Exception as e:
            revisions[repo] = mark_safe("<strong>Unknown</strong> %r" % e)

    return render(
        request, 'selftest/index.html', {
            'emailform': emailform,
            'misc': misc,
            'settings': get_safe_settings(),
            'environ': os.environ,
            'revisions': revisions,
        })
コード例 #51
0
def settings_list(request):
    """
    Custom admin view that displays the settings for this Django project.
    """

    if not request.user.is_superuser:
        return HttpResponseRedirect(reverse('admin:index'))

    settings = get_safe_settings()

    for setting in PRIVATE_SETTINGS:
        if setting in settings:
            settings[setting] = '********************'

    sorted_settings = sorted(settings.items())

    return render_to_response('admin/settings_list.html', RequestContext(request, {
        'title': 'Django Settings',
        'sorted_settings': sorted_settings,
    }))
コード例 #52
0
    def __init__(self, *args, **kwargs):
        request = kwargs.pop('request', None)
        super(InfoForm, self).__init__(*args, **kwargs)

        _settings = [{'key': k, 'value': v}
                     for k, v in six.iteritems(get_safe_settings())]

        table = SettingsTable(request, data=_settings)

        leonardo_table = LeonardoTable(request, data=leonardo.get_modules_as_list())

        self.helper.layout = forms.Layout(
            forms.TabHolder(
                forms.Tab('Leonardo modules',
                          forms.HTML(leonardo_table.render())
                          ),
                forms.Tab('Settings',
                          forms.HTML(table.render())
                          ),
            )
        )
コード例 #53
0
def technical_404_response(request, exception):
    "Create a technical 404 error response. The exception should be the Http404."
    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError):
        tried = []
    else:
        if not tried:
            # tried exists but is an empty list. The URLconf must've been empty.
            return empty_urlconf(request)

    t = Template(TECHNICAL_404_TEMPLATE, name='Technical 404 template')
    c = Context({
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': request.path_info[1:], # Trim leading slash
        'urlpatterns': tried,
        'reason': smart_str(exception, errors='replace'),
        'request': request,
        'request_protocol': request.is_secure() and "https" or "http",
        'settings': get_safe_settings(),
    })
    return HttpResponseNotFound(t.render(c), mimetype='text/html')
コード例 #54
0
 def __init__(self):
     self._settings = get_safe_settings()
コード例 #55
0
def technical_404_response(request, exception):
    "Create a technical 404 error response. The exception should be the Http404."
    try:
        error_url = exception.args[0]['path']
    except (IndexError, TypeError, KeyError):
        error_url = request.path_info[1:]  # Trim leading slash

    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []
    else:
        if (not tried  # empty URLconf
                or
            (request.path == '/' and len(tried) == 1  # default URLconf
             and len(tried[0]) == 1 and getattr(tried[0][0], 'app_name', '') ==
             getattr(tried[0][0], 'namespace', '') == 'admin')):
            return default_urlconf(request)

    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    if isinstance(urlconf, types.ModuleType):
        urlconf = urlconf.__name__

    caller = ''
    try:
        resolver_match = resolve(request.path)
    except Resolver404:
        pass
    else:
        obj = resolver_match.func

        if hasattr(obj, '__name__'):
            caller = obj.__name__
        elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
            caller = obj.__class__.__name__

        if hasattr(obj, '__module__'):
            module = obj.__module__
            caller = '%s.%s' % (module, caller)

    try:
        from leonardo.module.web.models import Page
        feincms_page = Page.objects.for_request(request, best_match=True)
        template = feincms_page.theme.template
    except:
        feincms_page = Page.objects.filter(parent=None).first()
        template = feincms_page.theme.template
    else:
        # nested path is not allowed for this time
        try:
            slug = request.path_info.split("/")[-2:-1][0]
        except KeyError:
            raise Exception("Nested path is not allowed !")

    c = RequestContext(
        request, {
            'urlconf': urlconf,
            'root_urlconf': settings.ROOT_URLCONF,
            'request_path': error_url,
            'urlpatterns': tried,
            'reason': force_bytes(exception, errors='replace'),
            'request': request,
            'settings': get_safe_settings(),
            'raising_view_name': caller,
            'feincms_page': feincms_page,
            'template': template or 'base.html',
            'standalone': True,
            'slug': slug,
        })

    try:
        t = render_to_string('404_technical.html', c)
    except:
        from django.views.debug import TECHNICAL_404_TEMPLATE
        t = Template(TECHNICAL_404_TEMPLATE).render(c)
    return HttpResponseNotFound(t, content_type='text/html')
コード例 #56
0
ファイル: resources.py プロジェクト: mstriemer/solitude
def settings_list(request):
    if not getattr(settings, 'CLEANSED_SETTINGS_ACCESS', False):
        raise PermissionDenied
    return Response(sorted(debug.get_safe_settings().keys()))
コード例 #57
0
 def process_response(self, request, response):
     self.record_stats({
         'settings': SortedDict(sorted(get_safe_settings().items(), key=lambda s: s[0])),
     })
コード例 #58
0
 def get_original_settings_without_onthefly(self):
     all_settings = get_safe_settings().keys()
     original_settings_without_onthefly = set(all_settings).difference(
         self.backend.get_fields())
     return list(original_settings_without_onthefly)