Exemplo n.º 1
0
 def validate_thread_sharing(self):
     """
     Validates that the connection isn't accessed by another thread than the
     one which originally created it, unless the connection was explicitly
     authorized to be shared between threads (via the `allow_thread_sharing`
     property). Raises an exception if the validation fails.
     """
     if (not self.allow_thread_sharing
         and self._thread_ident != thread.get_ident()):
             raise DatabaseError("DatabaseWrapper objects created in a "
                 "thread can only be used in that same thread. The object "
                 "with alias '%s' was created in thread id %s and this is "
                 "thread id %s."
                 % (self.alias, self._thread_ident, thread.get_ident()))
Exemplo n.º 2
0
 def validate_thread_sharing(self):
     """
     Validates that the connection isn't accessed by another thread than the
     one which originally created it, unless the connection was explicitly
     authorized to be shared between threads (via the `allow_thread_sharing`
     property). Raises an exception if the validation fails.
     """
     if not (self.allow_thread_sharing
             or self._thread_ident == thread.get_ident()):
         raise DatabaseError("DatabaseWrapper objects created in a "
             "thread can only be used in that same thread. The object "
             "with alias '%s' was created in thread id %s and this is "
             "thread id %s."
             % (self.alias, self._thread_ident, thread.get_ident()))
Exemplo n.º 3
0
    def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS,
                 allow_thread_sharing=False):
        # `settings_dict` should be a dictionary containing keys such as
        # NAME, USER, etc. It's called `settings_dict` instead of `settings`
        # to disambiguate it from Django settings modules.
        self.connection = None
        self.queries = []
        self.settings_dict = settings_dict
        self.alias = alias
        self.use_debug_cursor = None

        # Savepoint management related attributes
        self.savepoint_state = 0

        # Transaction management related attributes
        self.transaction_state = []
        # Tracks if the connection is believed to be in transaction. This is
        # set somewhat aggressively, as the DBAPI doesn't make it easy to
        # deduce if the connection is in transaction or not.
        self._dirty = False

        # Connection termination related attributes
        self.close_at = None
        self.errors_occurred = False

        # Thread-safety related attributes
        self.allow_thread_sharing = allow_thread_sharing
        self._thread_ident = thread.get_ident()
Exemplo n.º 4
0
    def process_request(self, request):
        __traceback_hide__ = True
        if self.show_toolbar(request):
            urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
            if isinstance(urlconf, string_types):
                urlconf = import_module(
                    getattr(request, 'urlconf', settings.ROOT_URLCONF))

            if urlconf not in self._urlconfs:
                new_urlconf = imp.new_module('urlconf')
                new_urlconf.urlpatterns = debug_toolbar.urls.urlpatterns + \
                    list(urlconf.urlpatterns)

                if hasattr(urlconf, 'handler403'):
                    new_urlconf.handler403 = urlconf.handler403
                if hasattr(urlconf, 'handler404'):
                    new_urlconf.handler404 = urlconf.handler404
                if hasattr(urlconf, 'handler500'):
                    new_urlconf.handler500 = urlconf.handler500

                self._urlconfs[urlconf] = new_urlconf

            request.urlconf = self._urlconfs[urlconf]

            toolbar = DebugToolbar(request)
            for panel in toolbar.panels:
                panel.process_request(request)
            self.__class__.debug_toolbars[_thread.get_ident()] = toolbar
Exemplo n.º 5
0
 def process_response(self, request, response):
     __traceback_hide__ = True
     ident = _thread.get_ident()
     toolbar = self.__class__.debug_toolbars.get(ident)
     if not toolbar or request.is_ajax():
         return response
     if isinstance(response, HttpResponseRedirect):
         if not toolbar.config['INTERCEPT_REDIRECTS'] or request.is_ajax():
             return response
         redirect_to = response.get('Location', None)
         if redirect_to:
             cookies = response.cookies
             response = render_to_response('debug_toolbar/redirect.html',
                                           {'redirect_to': redirect_to})
             response.cookies = cookies
     if ('gzip' not in response.get('Content-Encoding', '') and
             response.get('Content-Type', '').split(';')[0] in _HTML_TYPES):
         for panel in toolbar.panels:
             panel.process_response(request, response)
         response.content = replace_insensitive(
             smart_text(response.content), self.tag,
             smart_text(toolbar.render_toolbar() + self.tag))
         if response.get('Content-Length', None):
             response['Content-Length'] = len(response.content)
     del self.__class__.debug_toolbars[ident]
     return response
Exemplo n.º 6
0
    def process_request(self, request):
        __traceback_hide__ = True
        if self.show_toolbar(request):
            urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
            if isinstance(urlconf, string_types):
                urlconf = import_module(getattr(request, 'urlconf', settings.ROOT_URLCONF))

            if urlconf not in self._urlconfs:
                new_urlconf = imp.new_module('urlconf')
                new_urlconf.urlpatterns = debug_toolbar.urls.urlpatterns + \
                    list(urlconf.urlpatterns)

                if hasattr(urlconf, 'handler403'):
                    new_urlconf.handler403 = urlconf.handler403
                if hasattr(urlconf, 'handler404'):
                    new_urlconf.handler404 = urlconf.handler404
                if hasattr(urlconf, 'handler500'):
                    new_urlconf.handler500 = urlconf.handler500

                self._urlconfs[urlconf] = new_urlconf

            request.urlconf = self._urlconfs[urlconf]

            toolbar = DebugToolbar(request)
            for panel in toolbar.panels:
                panel.process_request(request)
            self.__class__.debug_toolbars[_thread.get_ident()] = toolbar
Exemplo n.º 7
0
 def process_response(self, request, response):
     __traceback_hide__ = True
     ident = _thread.get_ident()
     toolbar = self.__class__.debug_toolbars.get(ident)
     if not toolbar or request.is_ajax():
         return response
     if isinstance(response, HttpResponseRedirect):
         if not toolbar.config['INTERCEPT_REDIRECTS'] or request.is_ajax():
             return response
         redirect_to = response.get('Location', None)
         if redirect_to:
             cookies = response.cookies
             response = render_to_response(
                 'debug_toolbar/redirect.html',
                 {'redirect_to': redirect_to}
             )
             response.cookies = cookies
     if ('gzip' not in response.get('Content-Encoding', '') and
             response.get('Content-Type', '').split(';')[0] in _HTML_TYPES):
         for panel in toolbar.panels:
             panel.process_response(request, response)
         response.content = replace_insensitive(
             smart_text(response.content),
             self.tag,
             smart_text(toolbar.render_toolbar() + self.tag))
         if response.get('Content-Length', None):
             response['Content-Length'] = len(response.content)
     del self.__class__.debug_toolbars[ident]
     return response
Exemplo n.º 8
0
    def validate_thread_sharing(self):
        """
<<<<<<< HEAD
        Validates that the connection isn't accessed by another thread than the
        one which originally created it, unless the connection was explicitly
        authorized to be shared between threads (via the `allow_thread_sharing`
        property). Raises an exception if the validation fails.
        """
        if not (self.allow_thread_sharing or self._thread_ident == thread.get_ident()):
Exemplo n.º 9
0
    def __init__(self,
                 settings_dict,
                 alias=DEFAULT_DB_ALIAS,
                 allow_thread_sharing=False):
        # Connection related attributes.
        # The underlying database connection.
        self.connection = None
        # `settings_dict` should be a dictionary containing keys such as
        # NAME, USER, etc. It's called `settings_dict` instead of `settings`
        # to disambiguate it from Django settings modules.
        self.settings_dict = settings_dict
        self.alias = alias
        # Query logging in debug mode or when explicitly enabled.
        self.queries_log = deque(maxlen=self.queries_limit)
        self.force_debug_cursor = False

        # Transaction related attributes.
        # Tracks if the connection is in autocommit mode. Per PEP 249, by
        # default, it isn't.
        self.autocommit = False
        # Tracks if the connection is in a transaction managed by 'atomic'.
        self.in_atomic_block = False
        # Increment to generate unique savepoint ids.
        self.savepoint_state = 0
        # List of savepoints created by 'atomic'.
        self.savepoint_ids = []
        # Tracks if the outermost 'atomic' block should commit on exit,
        # ie. if autocommit was active on entry.
        self.commit_on_exit = True
        # Tracks if the transaction should be rolled back to the next
        # available savepoint because of an exception in an inner block.
        self.needs_rollback = False

        # Connection termination related attributes.
        self.close_at = None
        self.closed_in_transaction = False
        self.errors_occurred = False

        # Thread-safety related attributes.
        self.allow_thread_sharing = allow_thread_sharing
        self._thread_ident = thread.get_ident()

        # A list of no-argument functions to run when the transaction commits.
        # Each entry is an (sids, func) tuple, where sids is a set of the
        # active savepoint IDs when this function was registered.
        self.run_on_commit = []

        # Should we run the on-commit hooks the next time set_autocommit(True)
        # is called?
        self.run_commit_hooks_on_set_autocommit_on = False

        self.client = self.client_class(self)
        self.creation = self.creation_class(self)
        self.features = self.features_class(self)
        self.introspection = self.introspection_class(self)
        self.ops = self.ops_class(self)
        self.validation = self.validation_class(self)
Exemplo n.º 10
0
    def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS,
                 allow_thread_sharing=False):
        # Connection related attributes.
        # The underlying database connection.
        self.connection = None
        # `settings_dict` should be a dictionary containing keys such as
        # NAME, USER, etc. It's called `settings_dict` instead of `settings`
        # to disambiguate it from Django settings modules.
        self.settings_dict = settings_dict
        self.alias = alias
        # Query logging in debug mode or when explicitly enabled.
        self.queries_log = deque(maxlen=self.queries_limit)
        self.force_debug_cursor = False

        # Transaction related attributes.
        # Tracks if the connection is in autocommit mode. Per PEP 249, by
        # default, it isn't.
        self.autocommit = False
        # Tracks if the connection is in a transaction managed by 'atomic'.
        self.in_atomic_block = False
        # Increment to generate unique savepoint ids.
        self.savepoint_state = 0
        # List of savepoints created by 'atomic'.
        self.savepoint_ids = []
        # Tracks if the outermost 'atomic' block should commit on exit,
        # ie. if autocommit was active on entry.
        self.commit_on_exit = True
        # Tracks if the transaction should be rolled back to the next
        # available savepoint because of an exception in an inner block.
        self.needs_rollback = False

        # Connection termination related attributes.
        self.close_at = None
        self.closed_in_transaction = False
        self.errors_occurred = False

        # Thread-safety related attributes.
        self.allow_thread_sharing = allow_thread_sharing
        self._thread_ident = thread.get_ident()

        # A list of no-argument functions to run when the transaction commits.
        # Each entry is an (sids, func) tuple, where sids is a set of the
        # active savepoint IDs when this function was registered.
        self.run_on_commit = []

        # Should we run the on-commit hooks the next time set_autocommit(True)
        # is called?
        self.run_commit_hooks_on_set_autocommit_on = False

        self.client = self.client_class(self)
        self.creation = self.creation_class(self)
        self.features = self.features_class(self)
        self.introspection = self.introspection_class(self)
        self.ops = self.ops_class(self)
        self.validation = self.validation_class(self)
Exemplo n.º 11
0
    def setUp(self):
        request = rf.get('/')
        response = HttpResponse()
        toolbar = DebugToolbar(request)

        DebugToolbarMiddleware.debug_toolbars[_thread.get_ident()] = toolbar

        self.request = request
        self.response = response
        self.toolbar = toolbar
        self.toolbar.stats = {}
Exemplo n.º 12
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     __traceback_hide__ = True
     toolbar = self.__class__.debug_toolbars.get(_thread.get_ident())
     if not toolbar:
         return
     result = None
     for panel in toolbar.panels:
         response = panel.process_view(request, view_func, view_args, view_kwargs)
         if response:
             result = response
     return result
Exemplo n.º 13
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     __traceback_hide__ = True
     toolbar = self.__class__.debug_toolbars.get(_thread.get_ident())
     if not toolbar:
         return
     result = None
     for panel in toolbar.panels:
         response = panel.process_view(request, view_func, view_args,
                                       view_kwargs)
         if response:
             result = response
     return result
Exemplo n.º 14
0
    def savepoint(self):
        """
        Creates a savepoint (if supported and required by the backend) inside the
        current transaction. Returns an identifier for the savepoint that will be
        used for the subsequent rollback or commit.
        """
        thread_ident = thread.get_ident()

        self.savepoint_state += 1

        tid = str(thread_ident).replace('-', '')
        sid = "s%s_x%d" % (tid, self.savepoint_state)
        self._savepoint(sid)
        return sid
Exemplo n.º 15
0
    def savepoint(self):
        """
        Creates a savepoint (if supported and required by the backend) inside the
        current transaction. Returns an identifier for the savepoint that will be
        used for the subsequent rollback or commit.
        """
        thread_ident = thread.get_ident()

        self.savepoint_state += 1

        tid = str(thread_ident).replace('-', '')
        sid = "s%s_x%d" % (tid, self.savepoint_state)
        self._savepoint(sid)
        return sid
Exemplo n.º 16
0
    def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS, allow_thread_sharing=False):
        # `settings_dict` should be a dictionary containing keys such as
        # NAME, USER, etc. It's called `settings_dict` instead of `settings`
        # to disambiguate it from Django settings modules.
        self.connection = None
        self.queries = []
        self.settings_dict = settings_dict
        self.alias = alias
        self.use_debug_cursor = None

        # Transaction related attributes
        self.transaction_state = []
        self.savepoint_state = 0
        self._dirty = None
        self._thread_ident = thread.get_ident()
        self.allow_thread_sharing = allow_thread_sharing
Exemplo n.º 17
0
    def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS,
                 allow_thread_sharing=False):
        # `settings_dict` should be a dictionary containing keys such as
        # NAME, USER, etc. It's called `settings_dict` instead of `settings`
        # to disambiguate it from Django settings modules.
        self.connection = None
        self.queries = []
        self.settings_dict = settings_dict
        self.alias = alias
        self.use_debug_cursor = None

        # Transaction related attributes
        self.transaction_state = []
        self.savepoint_state = 0
        self._dirty = None
        self._thread_ident = thread.get_ident()
        self.allow_thread_sharing = allow_thread_sharing
Exemplo n.º 18
0
    def savepoint(self):
        """
        Creates a savepoint inside the current transaction. Returns an
        identifier for the savepoint that will be used for the subsequent
        rollback or commit. Does nothing if savepoints are not supported.
        """
        if not self._savepoint_allowed():
            return

        thread_ident = thread.get_ident()
        tid = str(thread_ident).replace('-', '')

        self.savepoint_state += 1
        sid = "s%s_x%d" % (tid, self.savepoint_state)

        self.validate_thread_sharing()
        self._savepoint(sid)

        return sid
Exemplo n.º 19
0
    def savepoint(self):
        """
        Creates a savepoint inside the current transaction. Returns an
        identifier for the savepoint that will be used for the subsequent
        rollback or commit. Does nothing if savepoints are not supported.
        """
        if not self._savepoint_allowed():
            return

        thread_ident = thread.get_ident()
        tid = str(thread_ident).replace('-', '')

        self.savepoint_state += 1
        sid = "s%s_x%d" % (tid, self.savepoint_state)

        self.validate_thread_sharing()
        self._savepoint(sid)

        return sid
Exemplo n.º 20
0
    def __init__(self,
                 settings_dict,
                 alias=DEFAULT_DB_ALIAS,
                 allow_thread_sharing=False):
        # `settings_dict` should be a dictionary containing keys such as
        # NAME, USER, etc. It's called `settings_dict` instead of `settings`
        # to disambiguate it from Django settings modules.
        self.connection = None
        self.queries = []
        self.settings_dict = settings_dict
        self.alias = alias
        self.use_debug_cursor = None

        # Savepoint management related attributes
        self.savepoint_state = 0

        # Transaction management related attributes
        self.autocommit = False
        self.transaction_state = []
        # Tracks if the connection is believed to be in transaction. This is
        # set somewhat aggressively, as the DBAPI doesn't make it easy to
        # deduce if the connection is in transaction or not.
        self._dirty = False
        # Tracks if the connection is in a transaction managed by 'atomic'.
        self.in_atomic_block = False
        # List of savepoints created by 'atomic'
        self.savepoint_ids = []
        # Tracks if the outermost 'atomic' block should commit on exit,
        # ie. if autocommit was active on entry.
        self.commit_on_exit = True
        # Tracks if the transaction should be rolled back to the next
        # available savepoint because of an exception in an inner block.
        self.needs_rollback = False

        # Connection termination related attributes
        self.close_at = None
        self.closed_in_transaction = False
        self.errors_occurred = False

        # Thread-safety related attributes
        self.allow_thread_sharing = allow_thread_sharing
        self._thread_ident = thread.get_ident()
Exemplo n.º 21
0
    def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS,
                 allow_thread_sharing=False):
        # `settings_dict` should be a dictionary containing keys such as
        # NAME, USER, etc. It's called `settings_dict` instead of `settings`
        # to disambiguate it from Django settings modules.
        self.connection = None
        self.queries = []
        self.settings_dict = settings_dict
        self.alias = alias
        self.use_debug_cursor = None

        # Savepoint management related attributes
        self.savepoint_state = 0

        # Transaction management related attributes
        self.autocommit = False
        self.transaction_state = []
        # Tracks if the connection is believed to be in transaction. This is
        # set somewhat aggressively, as the DBAPI doesn't make it easy to
        # deduce if the connection is in transaction or not.
        self._dirty = False
        # Tracks if the connection is in a transaction managed by 'atomic'.
        self.in_atomic_block = False
        # List of savepoints created by 'atomic'
        self.savepoint_ids = []
        # Tracks if the outermost 'atomic' block should commit on exit,
        # ie. if autocommit was active on entry.
        self.commit_on_exit = True
        # Tracks if the transaction should be rolled back to the next
        # available savepoint because of an exception in an inner block.
        self.needs_rollback = False

        # Connection termination related attributes
        self.close_at = None
        self.closed_in_transaction = False
        self.errors_occurred = False

        # Thread-safety related attributes
        self.allow_thread_sharing = allow_thread_sharing
        self._thread_ident = thread.get_ident()
Exemplo n.º 22
0
    def __init__(self,
                 settings_dict,
                 alias=DEFAULT_DB_ALIAS,
                 allow_thread_sharing=False):
        # Connection related attributes.
        self.connection = None
        self.queries = []
        # `settings_dict` should be a dictionary containing keys such as
        # NAME, USER, etc. It's called `settings_dict` instead of `settings`
        # to disambiguate it from Django settings modules.
        self.settings_dict = settings_dict
        self.alias = alias
        self.use_debug_cursor = None

        # Transaction related attributes.
        # Tracks if the connection is in autocommit mode. Per PEP 249, by
        # default, it isn't.
        self.autocommit = False
        # Tracks if the connection is in a transaction managed by 'atomic'.
        self.in_atomic_block = False
        # Increment to generate unique savepoint ids.
        self.savepoint_state = 0
        # List of savepoints created by 'atomic'.
        self.savepoint_ids = []
        # Tracks if the outermost 'atomic' block should commit on exit,
        # ie. if autocommit was active on entry.
        self.commit_on_exit = True
        # Tracks if the transaction should be rolled back to the next
        # available savepoint because of an exception in an inner block.
        self.needs_rollback = False

        # Connection termination related attributes.
        self.close_at = None
        self.closed_in_transaction = False
        self.errors_occurred = False

        # Thread-safety related attributes.
        self.allow_thread_sharing = allow_thread_sharing
        self._thread_ident = thread.get_ident()
Exemplo n.º 23
0
    def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS,
                 allow_thread_sharing=False):
        # Connection related attributes.
        self.connection = None
        self.queries = []
        # `settings_dict` should be a dictionary containing keys such as
        # NAME, USER, etc. It's called `settings_dict` instead of `settings`
        # to disambiguate it from Django settings modules.
        self.settings_dict = settings_dict
        self.alias = alias
        self.use_debug_cursor = None

        # Transaction related attributes.
        # Tracks if the connection is in autocommit mode. Per PEP 249, by
        # default, it isn't.
        self.autocommit = False
        # Tracks if the connection is in a transaction managed by 'atomic'.
        self.in_atomic_block = False
        # Increment to generate unique savepoint ids.
        self.savepoint_state = 0
        # List of savepoints created by 'atomic'.
        self.savepoint_ids = []
        # Tracks if the outermost 'atomic' block should commit on exit,
        # ie. if autocommit was active on entry.
        self.commit_on_exit = True
        # Tracks if the transaction should be rolled back to the next
        # available savepoint because of an exception in an inner block.
        self.needs_rollback = False

        # Connection termination related attributes.
        self.close_at = None
        self.closed_in_transaction = False
        self.errors_occurred = False

        # Thread-safety related attributes.
        self.allow_thread_sharing = allow_thread_sharing
        self._thread_ident = thread.get_ident()
Exemplo n.º 24
0
 def set_global(cls, key, value):
     ident = thread.get_ident()
     if ident not in cls._globals:
         cls._globals[ident] = {}
     cls._globals[ident][key] = value
Exemplo n.º 25
0
 def get_current(cls):
     return cls.debug_toolbars.get(_thread.get_ident())
Exemplo n.º 26
0
        # Tracks if the outermost 'atomic' block should commit on exit,
        # ie. if autocommit was active on entry.
        self.commit_on_exit = True
        # Tracks if the transaction should be rolled back to the next
        # available savepoint because of an exception in an inner block.
        self.needs_rollback = False

        # Connection termination related attributes.
        self.close_at = None
        self.closed_in_transaction = False
        self.errors_occurred = False

        # Thread-safety related attributes.
        self.allow_thread_sharing = allow_thread_sharing
<<<<<<< HEAD
        self._thread_ident = thread.get_ident()
=======
        self._thread_ident = _thread.get_ident()
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435

        # A list of no-argument functions to run when the transaction commits.
        # Each entry is an (sids, func) tuple, where sids is a set of the
        # active savepoint IDs when this function was registered.
        self.run_on_commit = []

        # Should we run the on-commit hooks the next time set_autocommit(True)
        # is called?
        self.run_commit_hooks_on_set_autocommit_on = False

<<<<<<< HEAD
=======
Exemplo n.º 27
0
 def get_current(cls):
     return cls.debug_toolbars.get(_thread.get_ident())
Exemplo n.º 28
0
 def set_global(cls, key, value):
     ident = thread.get_ident()
     if ident not in cls._globals:
         cls._globals[ident] = {}
     cls._globals[ident][key] = value
Exemplo n.º 29
0
 def get_global(cls, key):
     return cls._globals.get(thread.get_ident(), {}).get(key)
Exemplo n.º 30
0
 def get_global(cls, key):
     return cls._globals.get(thread.get_ident(), {}).get(key)
Exemplo n.º 31
0
import copy