コード例 #1
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,

    })
コード例 #2
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))
コード例 #3
0
 def get_context(self):
     """
     Override this to change context
     """
     return {
         'settings': get_safe_settings(),
         'bundles': get_bundles(),
         }
コード例 #4
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
コード例 #5
0
 def generate_stats(self, request, response):
     self.record_stats(
         {
             "settings": OrderedDict(
                 sorted(get_safe_settings().items(), key=lambda s: s[0])
             )
         }
     )
コード例 #6
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
コード例 #7
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, {}))
コード例 #8
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
コード例 #9
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
コード例 #10
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, {}),
    )
コード例 #11
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'
            })
コード例 #12
0
ファイル: admin.py プロジェクト: codeadict/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, {}))
コード例 #13
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
コード例 #14
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})
コード例 #15
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
コード例 #16
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!'})
コード例 #17
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})
コード例 #18
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})
コード例 #19
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})
コード例 #20
0
ファイル: views.py プロジェクト: LittleForker/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})
コード例 #21
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
コード例 #22
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
コード例 #23
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
コード例 #24
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})
コード例 #25
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})
コード例 #26
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)
コード例 #27
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')
コード例 #28
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,
    }))
コード例 #29
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())
                          ),
            )
        )
コード例 #30
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')