예제 #1
0
 def __init__(self, request):
     self.request = request
     self.config = dt_settings.CONFIG.copy()
     self._panels = OrderedDict()
     for panel_class in self.get_panel_classes():
         panel_instance = panel_class(self)
         self._panels[panel_instance.panel_id] = panel_instance
     self.stats = {}
     self.store_id = None
예제 #2
0
 def process_request(self, request):
     wsgi_env = list(sorted(request.META.items()))
     self.request_headers = OrderedDict(
         (unmangle(k), v) for (k, v) in wsgi_env if is_http_header(k))
     if 'Cookie' in self.request_headers:
         self.request_headers['Cookie'] = '=> see Request panel'
     self.environ = OrderedDict(
         (k, v) for (k, v) in wsgi_env if k in self.ENVIRON_FILTER)
     self.record_stats({
         'request_headers': self.request_headers,
         'environ': self.environ,
     })
예제 #3
0
파일: headers.py 프로젝트: zvrr/sentry
 def process_request(self, request):
     wsgi_env = list(sorted(request.META.items()))
     self.request_headers = OrderedDict(
         (unmangle(k), v) for (k, v) in wsgi_env if is_http_header(k))
     if "Cookie" in self.request_headers:
         self.request_headers["Cookie"] = "=> see Request panel"
     self.environ = OrderedDict(
         (k, v) for (k, v) in wsgi_env if k in self.ENVIRON_FILTER)
     self.record_stats({
         "request_headers": self.request_headers,
         "environ": self.environ
     })
예제 #4
0
파일: toolbar.py 프로젝트: AayushU/osqa
 def __init__(self, request):
     self.request = request
     self.config = dt_settings.CONFIG.copy()
     self._panels = OrderedDict()
     for panel_class in self.get_panel_classes():
         panel_instance = panel_class(self)
         self._panels[panel_instance.panel_id] = panel_instance
     self.stats = {}
     self.store_id = None
예제 #5
0
 def get_staticfiles_finders(self):
     """
     Returns a sorted mapping between the finder path and the list
     of relative and file system paths which that finder was able
     to find.
     """
     finders_mapping = OrderedDict()
     for finder in finders.get_finders():
         for path, finder_storage in finder.list([]):
             if getattr(finder_storage, 'prefix', None):
                 prefixed_path = join(finder_storage.prefix, path)
             else:
                 prefixed_path = path
             finder_cls = finder.__class__
             finder_path = '.'.join([finder_cls.__module__, finder_cls.__name__])
             real_path = finder_storage.path(path)
             payload = (prefixed_path, real_path)
             finders_mapping.setdefault(finder_path, []).append(payload)
             self.num_found += 1
     return finders_mapping
예제 #6
0
 def get_staticfiles_finders(self):
     """
     Returns a sorted mapping between the finder path and the list
     of relative and file system paths which that finder was able
     to find.
     """
     finders_mapping = OrderedDict()
     for finder in finders.get_finders():
         for path, finder_storage in finder.list([]):
             if getattr(finder_storage, 'prefix', None):
                 prefixed_path = join(finder_storage.prefix, path)
             else:
                 prefixed_path = path
             finder_cls = finder.__class__
             finder_path = '.'.join(
                 [finder_cls.__module__, finder_cls.__name__])
             real_path = finder_storage.path(path)
             payload = (prefixed_path, real_path)
             finders_mapping.setdefault(finder_path, []).append(payload)
             self.num_found += 1
     return finders_mapping
예제 #7
0
 def generate_stats(self, request, response):
     versions = [
         ('Python', '%d.%d.%d' % sys.version_info[:3]),
         ('Django', self.get_app_version(django)),
     ]
     if django.VERSION[:2] >= (1, 7):
         versions += list(self.gen_app_versions_1_7())
     else:
         versions += list(self.gen_app_versions_1_6())
     self.record_stats({
         'versions': OrderedDict(sorted(versions, key=lambda v: v[0])),
         'paths': sys.path,
     })
예제 #8
0
파일: versions.py 프로젝트: zvrr/sentry
 def process_response(self, request, response):
     versions = [
         ("Python", "%d.%d.%d" % sys.version_info[:3]),
         ("Django", self.get_app_version(django)),
     ]
     if django.VERSION[:2] >= (1, 7):
         versions += list(self.gen_app_versions_1_7())
     else:
         versions += list(self.gen_app_versions_1_6())
     self.record_stats({
         "versions":
         OrderedDict(sorted(versions, key=lambda v: v[0])),
         "paths":
         sys.path
     })
예제 #9
0
 def __init__(self, *args, **kwargs):
     super(CachePanel, self).__init__(*args, **kwargs)
     self.total_time = 0
     self.hits = 0
     self.misses = 0
     self.calls = []
     self.counts = OrderedDict((
         ('add', 0),
         ('get', 0),
         ('set', 0),
         ('delete', 0),
         ('get_many', 0),
         ('set_many', 0),
         ('delete_many', 0),
         ('has_key', 0),
         ('incr', 0),
         ('decr', 0),
         ('incr_version', 0),
         ('decr_version', 0),
     ))
     cache_called.connect(self._store_call_info)
예제 #10
0
 def __init__(self, *args, **kwargs):
     super(CachePanel, self).__init__(*args, **kwargs)
     self.total_time = 0
     self.hits = 0
     self.misses = 0
     self.calls = []
     self.counts = OrderedDict((
         ("add", 0),
         ("get", 0),
         ("set", 0),
         ("delete", 0),
         ("clear", 0),
         ("get_many", 0),
         ("set_many", 0),
         ("delete_many", 0),
         ("has_key", 0),
         ("incr", 0),
         ("decr", 0),
         ("incr_version", 0),
         ("decr_version", 0),
     ))
     cache_called.connect(self._store_call_info)
예제 #11
0
 def process_response(self, request, response):
     self.response_headers = OrderedDict(sorted(response.items()))
     self.record_stats({
         'response_headers': self.response_headers,
     })
예제 #12
0
 def process_response(self, request, response):
     self.record_stats({
         'settings':
         OrderedDict(sorted(get_safe_settings().items(),
                            key=lambda s: s[0])),
     })
예제 #13
0
class DebugToolbar(object):
    def __init__(self, request):
        self.request = request
        self.config = dt_settings.CONFIG.copy()
        self._panels = OrderedDict()
        for panel_class in self.get_panel_classes():
            panel_instance = panel_class(self)
            self._panels[panel_instance.panel_id] = panel_instance
        self.stats = {}
        self.store_id = None

    # Manage panels

    @property
    def panels(self):
        """
        Get a list of all available panels.
        """
        return list(self._panels.values())

    @property
    def enabled_panels(self):
        """
        Get a list of panels enabled for the current request.
        """
        return [panel for panel in self._panels.values() if panel.enabled]

    def get_panel_by_id(self, panel_id):
        """
        Get the panel with the given id, which is the class name by default.
        """
        return self._panels[panel_id]

    # Handle rendering the toolbar in HTML

    def render_toolbar(self):
        """
        Renders the overall Toolbar with panels inside.
        """
        if not self.should_render_panels():
            self.store()
        try:
            context = {'toolbar': self}
            return render_to_string('debug_toolbar/base.html', context)
        except TemplateSyntaxError:
            if django.VERSION[:2] >= (1, 7):
                from django.apps import apps
                staticfiles_installed = apps.is_installed(
                    'django.contrib.staticfiles')
            else:
                staticfiles_installed = ('django.contrib.staticfiles'
                                         in settings.INSTALLED_APPS)
            if not staticfiles_installed:
                raise ImproperlyConfigured(
                    "The debug toolbar requires the staticfiles contrib app. "
                    "Add 'django.contrib.staticfiles' to INSTALLED_APPS and "
                    "define STATIC_URL in your settings.")
            else:
                raise

    # Handle storing toolbars in memory and fetching them later on

    _store = OrderedDict()

    def should_render_panels(self):
        render_panels = self.config['RENDER_PANELS']
        if render_panels is None:
            # Django 1.4 still supports mod_python :( Fall back to the safe
            # and inefficient default in that case. Revert when we drop 1.4.
            render_panels = self.request.META.get('wsgi.multiprocess', True)
        return render_panels

    def store(self):
        self.store_id = uuid.uuid4().hex
        cls = type(self)
        cls._store[self.store_id] = self
        for _ in range(len(cls._store) - self.config['RESULTS_CACHE_SIZE']):
            try:
                # collections.OrderedDict
                cls._store.popitem(last=False)
            except TypeError:
                # django.utils.datastructures.SortedDict
                del cls._store[cls._store.keyOrder[0]]

    @classmethod
    def fetch(cls, store_id):
        return cls._store.get(store_id)

    # Manually implement class-level caching of panel classes and url patterns
    # because it's more obvious than going through an abstraction.

    _panel_classes = None

    @classmethod
    def get_panel_classes(cls):
        if cls._panel_classes is None:
            # Load panels in a temporary variable for thread safety.
            panel_classes = []
            for panel_path in dt_settings.PANELS:
                # This logic could be replaced with import_by_path in Django 1.6.
                try:
                    panel_module, panel_classname = panel_path.rsplit('.', 1)
                except ValueError:
                    raise ImproperlyConfigured(
                        "%s isn't a debug panel module" % panel_path)
                try:
                    mod = import_module(panel_module)
                except ImportError as e:
                    raise ImproperlyConfigured(
                        'Error importing debug panel %s: "%s"' %
                        (panel_module, e))
                try:
                    panel_class = getattr(mod, panel_classname)
                except AttributeError:
                    raise ImproperlyConfigured(
                        'Toolbar Panel module "%s" does not define a "%s" class'
                        % (panel_module, panel_classname))
                panel_classes.append(panel_class)
            cls._panel_classes = panel_classes
        return cls._panel_classes

    _urlpatterns = None

    @classmethod
    def get_urls(cls):
        if cls._urlpatterns is None:
            from . import views
            # Load URLs in a temporary variable for thread safety.
            # Global URLs
            urlpatterns = [
                url(r'^render_panel/$',
                    views.render_panel,
                    name='render_panel'),
            ]
            # Per-panel URLs
            for panel_class in cls.get_panel_classes():
                urlpatterns += panel_class.get_urls()
            cls._urlpatterns = urlpatterns
        return cls._urlpatterns
예제 #14
0
파일: toolbar.py 프로젝트: AayushU/osqa
class DebugToolbar(object):

    def __init__(self, request):
        self.request = request
        self.config = dt_settings.CONFIG.copy()
        self._panels = OrderedDict()
        for panel_class in self.get_panel_classes():
            panel_instance = panel_class(self)
            self._panels[panel_instance.panel_id] = panel_instance
        self.stats = {}
        self.store_id = None

    # Manage panels

    @property
    def panels(self):
        """
        Get a list of all available panels.
        """
        return list(self._panels.values())

    @property
    def enabled_panels(self):
        """
        Get a list of panels enabled for the current request.
        """
        return [panel for panel in self._panels.values() if panel.enabled]

    def get_panel_by_id(self, panel_id):
        """
        Get the panel with the given id, which is the class name by default.
        """
        return self._panels[panel_id]

    # Handle rendering the toolbar in HTML

    def render_toolbar(self):
        """
        Renders the overall Toolbar with panels inside.
        """
        if not self.should_render_panels():
            self.store()
        try:
            context = {'toolbar': self}
            return render_to_string('debug_toolbar/base.html', context)
        except TemplateSyntaxError:
            if django.VERSION[:2] >= (1, 7):
                from django.apps import apps
                staticfiles_installed = apps.is_installed(
                    'django.contrib.staticfiles')
            else:
                staticfiles_installed = ('django.contrib.staticfiles'
                                         in settings.INSTALLED_APPS)
            if not staticfiles_installed:
                raise ImproperlyConfigured(
                    "The debug toolbar requires the staticfiles contrib app. "
                    "Add 'django.contrib.staticfiles' to INSTALLED_APPS and "
                    "define STATIC_URL in your settings.")
            else:
                raise

    # Handle storing toolbars in memory and fetching them later on

    _store = OrderedDict()

    def should_render_panels(self):
        render_panels = self.config['RENDER_PANELS']
        if render_panels is None:
            # Django 1.4 still supports mod_python :( Fall back to the safe
            # and inefficient default in that case. Revert when we drop 1.4.
            render_panels = self.request.META.get('wsgi.multiprocess', True)
        return render_panels

    def store(self):
        self.store_id = uuid.uuid4().hex
        cls = type(self)
        cls._store[self.store_id] = self
        for _ in range(len(cls._store) - self.config['RESULTS_CACHE_SIZE']):
            try:
                # collections.OrderedDict
                cls._store.popitem(last=False)
            except TypeError:
                # django.utils.datastructures.SortedDict
                del cls._store[cls._store.keyOrder[0]]

    @classmethod
    def fetch(cls, store_id):
        return cls._store.get(store_id)

    # Manually implement class-level caching of panel classes and url patterns
    # because it's more obvious than going through an abstraction.

    _panel_classes = None

    @classmethod
    def get_panel_classes(cls):
        if cls._panel_classes is None:
            # Load panels in a temporary variable for thread safety.
            panel_classes = []
            for panel_path in dt_settings.PANELS:
                # This logic could be replaced with import_by_path in Django 1.6.
                try:
                    panel_module, panel_classname = panel_path.rsplit('.', 1)
                except ValueError:
                    raise ImproperlyConfigured(
                        "%s isn't a debug panel module" % panel_path)
                try:
                    mod = import_module(panel_module)
                except ImportError as e:
                    raise ImproperlyConfigured(
                        'Error importing debug panel %s: "%s"' %
                        (panel_module, e))
                try:
                    panel_class = getattr(mod, panel_classname)
                except AttributeError:
                    raise ImproperlyConfigured(
                        'Toolbar Panel module "%s" does not define a "%s" class' %
                        (panel_module, panel_classname))
                panel_classes.append(panel_class)
            cls._panel_classes = panel_classes
        return cls._panel_classes

    _urlpatterns = None

    @classmethod
    def get_urls(cls):
        if cls._urlpatterns is None:
            from . import views
            # Load URLs in a temporary variable for thread safety.
            # Global URLs
            urlpatterns = [
                url(r'^render_panel/$', views.render_panel, name='render_panel'),
            ]
            # Per-panel URLs
            for panel_class in cls.get_panel_classes():
                urlpatterns += panel_class.get_urls()
            cls._urlpatterns = urlpatterns
        return cls._urlpatterns
예제 #15
0
 def generate_stats(self, request, response):
     self.response_headers = OrderedDict(sorted(response.items()))
     self.record_stats({
         'response_headers': self.response_headers,
     })