def __exit__(self, exc_type, exc_value, traceback): self.connection.use_debug_cursor = self.old_debug_cursor request_started.connect(reset_queries) if exc_type is not None: return final_count = len(self.connection.queries) self.num_queries = final_count - self.starting_count
def __call__(self, environ): from django.conf import settings # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._request_middleware is None: self.load_middleware() request_started.disconnect(close_old_connections) request_started.send(sender=self.__class__) request_started.connect(close_old_connections) request = WSGIRequest(environ) # sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably # required for backwards compatibility with external tests against # admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks response = self.get_response(request) # We're emulating a WSGI server; we must call the close method # on completion. if response.streaming: response.streaming_content = closing_iterator_wrapper(response.streaming_content, response.close) else: request_finished.disconnect(close_old_connections) response.close() # will fire request_finished request_finished.connect(close_old_connections) return response
def ready(self): from .patches import json json.patch() from djangae.db.backends.appengine.caching import reset_context from django.core.signals import request_finished, request_started request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset") request_started.connect(reset_context, dispatch_uid="request_started_context_reset") from django.conf import settings contenttype_configuration_error = ImproperlyConfigured( "If you're using django.contrib.contenttypes, then you need " "to add djangae.contrib.contenttypes to INSTALLED_APPS after " "django.contrib.contenttypes." ) if 'django.contrib.contenttypes' in settings.INSTALLED_APPS: from django.db import router, connections from django.contrib.contenttypes.models import ContentType conn = connections[router.db_for_read(ContentType)] if conn.settings_dict.get("ENGINE") != 'djangae.db.backends.appengine': # Don't enforce djangae.contrib.contenttypes if content types are being # saved to a different database backend return if not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS: # Raise error if User is using Django CT, but not Djangae raise contenttype_configuration_error else: if settings.INSTALLED_APPS.index('django.contrib.contenttypes') > \ settings.INSTALLED_APPS.index('djangae.contrib.contenttypes'): # Raise error if User is using both Django and Djangae CT, but # Django CT comes after Djangae CT raise contenttype_configuration_error
def __init__(self): """Initializes the search context.""" self._request_active = False self._stack = [] # Connect to the signalling framework. request_started.connect(self._request_started_receiver) request_finished.connect(self._request_finished_receiver)
def defer_exception(self, exception): # XXX: this is a terrible hack to improve error reporting. # # Raising an exception here results in some awful error # reporting when models.py modules have ImportError. Django # will import the models module more than once, meaning # classes will get registered more than once, and if we # raise an exception here, you get an ImproperlyConfigured # instead of the ImportError that would help you find the # problem. See https://code.djangoproject.com/ticket/20839. self.deferred_exception = exception # sys._getframe(1) == skip defer_exception's frame, because it's # not interesting self.stacktrace = ''.join(traceback.format_stack(sys._getframe(1))) # We need an opportunity to raise the exception. Anything will # work as long as it happens after model loading. It'd be nice # if it happened during validation and didn't wait until the # first request, but there's no way to hook into that. # # The handler can't be registered in BaseRegistry.__init__ # because the tests import this module before settings are # configured, and the signal can't be imported without settings. def handler(**kwargs): self.raise_deferred_exception() request_started.disconnect(handler) request_started.connect(handler, weak=False)
def verbose_cursor(): old_method = BaseDatabaseWrapper.cursor l, _, new_method = make_verbose_cursor() request_started.disconnect(reset_queries) BaseDatabaseWrapper.cursor = new_method yield l BaseDatabaseWrapper.cursor = old_method request_started.connect(reset_queries)
def install(self): request_started.connect(self.before_request, weak=False) got_request_exception.connect(self.exception_handler, weak=False) if self.has_celery: try: self.install_celery() except Exception: logger.exception('Failed to install Celery error handler')
def ready(self): from .patches.contenttypes import patch patch(sender=self) from djangae.db.backends.appengine.caching import reset_context from django.core.signals import request_finished, request_started request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset") request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
def ready(self): # too bad there isn't an "all_django_apps_ready" signal request_started.connect( init_badges_once, dispatch_uid='init_askbot_badges_once') import followit user_model = get_user_model() followit.register(user_model)
def __exit__(self, exc_type, exc_value, traceback): self.connection.use_debug_cursor = self.old_debug_cursor request_started.connect(reset_queries) if exc_type is not None: return final_queries = len(self.connection.queries) executed = final_queries - self.starting_queries self.test_case.assertEqual(executed, self.num, "%d queries executed, %d expected" % (executed, self.num))
def patch_sessions(num_requests): """ Connects the clear_expired_sessions function to the request_started signal, and does a little configuration calculations and checking. """ if num_requests < 1: raise ImproperlyConfigured('The num_requests setting must be > 0') clear_expired_sessions.engine = importlib.import_module(settings.SESSION_ENGINE) clear_expired_sessions.probability = 1.0 / num_requests request_started.connect(clear_expired_sessions)
def register_handlers(): from django.core.signals import got_request_exception, request_started def before_request(*args, **kwargs): client.context.activate() request_started.connect(before_request, weak=False) # HACK: support Sentry's internal communication if 'sentry' in settings.INSTALLED_APPS: from django.db import transaction # Django 1.6 if hasattr(transaction, 'atomic'): commit_on_success = transaction.atomic else: commit_on_success = transaction.commit_on_success @commit_on_success def wrap_sentry(request, **kwargs): if transaction.is_dirty(): transaction.rollback() return sentry_exception_handler(request, **kwargs) exception_handler = wrap_sentry else: exception_handler = sentry_exception_handler # Connect to Django's internal signal handler got_request_exception.connect(exception_handler, weak=False) # If Celery is installed, register a signal handler if 'djcelery' in settings.INSTALLED_APPS: try: # Celery < 2.5? is not supported from raven.contrib.celery import ( register_signal, register_logger_signal) except ImportError: logger.exception('Failed to install Celery error handler') else: try: register_signal(client) except Exception: logger.exception('Failed to install Celery error handler') try: ga = lambda x, d=None: getattr(settings, 'SENTRY_%s' % x, d) options = getattr(settings, 'RAVEN_CONFIG', {}) loglevel = options.get('celery_loglevel', ga('CELERY_LOGLEVEL', logging.ERROR)) register_logger_signal(client, loglevel=loglevel) except Exception: logger.exception('Failed to install Celery error handler')
def ready(self): from .patches import json json.patch() from djangae.db.backends.appengine.caching import reset_context from djangae.db.migrations.signals import check_migrations from django.core.signals import request_finished, request_started from django.db.models.signals import pre_migrate request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset") request_started.connect(reset_context, dispatch_uid="request_started_context_reset") pre_migrate.connect(check_migrations, dispatch_uid="pre_migrate_check_connections") self._check_content_types()
def __exit__(self, exc_type, exc_value, traceback): self.connection.use_debug_cursor = self.old_debug_cursor request_started.connect(reset_queries) if exc_type is not None: return final_queries = len(self.connection.queries) executed = final_queries - self.starting_queries self.test_case.assertEqual( # KA-LITE-MOD This is necessary for FuzzyInt to print a meaningful error message. executed, self.num, "%s queries executed, %s expected" % ( executed, self.num ) )
def __exit__(self, exc_type, exc_value, traceback): settings.DEBUG = self.old_debug request_started.connect(reset_queries) if exc_type is not None: return final_queries = len(self.connection.queries) executed = final_queries - self.starting_queries queries = '\n'.join([q['sql'] for q in self.connection.queries[self.starting_queries:]]) self.test_case.assertEqual( executed, self.num, "%d queries executed, %d expected. Queries executed:\n%s" % ( executed, self.num, queries ) )
def queries(count=None, using=None): """ A context manager that captures the queries that were made. :param count: assert this number of queries were made :param using: alias of the database to monitor .. note:: The `list` of queries is not populated until after the context manager exits. Usage:: with queries() as qs: User.objects.count() assert len(qs) == 5 # The same could be rewritten as with queries(count=5): User.objects.count() """ if using is None: using = DEFAULT_DB_ALIAS conn = connections[using] # For compatbility with Django 1.2, apply necessary patching. patches = [] if not hasattr(conn, "use_debug_cursor"): patches.append(hacks.django12_debug_cursor(conn)) with utils.nested(*patches): # A debug cursor saves all the queries to conn.queries, in case one isn't # already being used, restore the current state after the test. was_debug_cursor = conn.use_debug_cursor conn.use_debug_cursor = True prior = len(conn.queries) executed = [] request_started.disconnect(reset_queries) try: yield executed finally: request_started.connect(reset_queries) conn.use_debug_cursor = was_debug_cursor executed[:] = conn.queries[prior:] if count is not None: assert len(executed) == count
def __exit__(self, exc_type, exc_value, traceback): self.connection.use_debug_cursor = self.old_debug_cursor request_started.connect(reset_queries) if exc_type is not None: return final_queries = len(self.connection.queries) executed = final_queries - self.starting_queries print print "_"*79 if self.msg: print " *** %s ***" % self.msg for no, q in enumerate(self.connection.queries[-executed:], 1): print "%i - %s" % (no, pformat_sql(q["sql"])) print print "-"*79
def ready(self): from djangae.db.backends.appengine.caching import reset_context from django.core.signals import request_finished, request_started request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset") request_started.connect(reset_context, dispatch_uid="request_started_context_reset") from django.conf import settings contenttype_configuration_error = ImproperlyConfigured( "If you're using django.contrib.contenttypes, then you need " "to add djangae.contrib.contenttypes to INSTALLED_APPS after " "django.contrib.contenttypes." ) if 'django.contrib.contenttypes' in settings.INSTALLED_APPS: if not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS: # Raise error if User is using Django CT, but not Djangae raise contenttype_configuration_error else: if settings.INSTALLED_APPS.index('django.contrib.contenttypes') > \ settings.INSTALLED_APPS.index('djangae.contrib.contenttypes'): # Raise error if User is using both Django and Djangae CT, but # Django CT comes after Djangae CT raise contenttype_configuration_error
def __call__(self, environ): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware() request_started.disconnect(close_old_connections) request_started.send(sender=self.__class__, environ=environ) request_started.connect(close_old_connections) request = WSGIRequest(environ) # sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably # required for backwards compatibility with external tests against # admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = self.get_response(request) # Simulate behaviors of most Web servers. conditional_content_removal(request, response) # Attach the originating request to the response so that it could be # later retrieved. response.wsgi_request = request # We're emulating a WSGI server; we must call the close method # on completion. if response.streaming: response.streaming_content = closing_iterator_wrapper( response.streaming_content, response.close) else: request_finished.disconnect(close_old_connections) response.close() # will fire request_finished request_finished.connect(close_old_connections) return response
def ready(self): from djangae.db.backends.appengine.caching import reset_context from django.core.signals import request_finished, request_started request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset") request_started.connect(reset_context, dispatch_uid="request_started_context_reset") from django.conf import settings contenttype_configuration_error = ImproperlyConfigured( "If you're using django.contrib.contenttypes, then you need " "to add djangae.contrib.contenttypes to INSTALLED_APPS after " "django.contrib.contenttypes.") if 'django.contrib.contenttypes' in settings.INSTALLED_APPS: if not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS: # Raise error if User is using Django CT, but not Djangae raise contenttype_configuration_error else: if settings.INSTALLED_APPS.index('django.contrib.contenttypes') > \ settings.INSTALLED_APPS.index('djangae.contrib.contenttypes'): # Raise error if User is using both Django and Djangae CT, but # Django CT comes after Djangae CT raise contenttype_configuration_error
def __exit__(self, exc_type, exc_value, traceback): # leaving the 'with' block self.connection.force_debug_cursor = self.force_debug_cursor request_started.connect(reset_queries) if exc_type is not None: # pragma: no cover return final_queries = len(self.connection.queries_log) executed = final_queries - self.initial_queries if executed > self.num: # pragma: no cover queries = 'Captured queries from index %s to %s:' % ( self.initial_queries, final_queries) for i, query in enumerate( self.connection.queries[self. initial_queries:final_queries], start=1): queries += '\n [%d] %s' % (i, self._reformat_sql(query['sql'])) # for msg = "Too many queries: %s; maximum %d. " % (executed, self.num) self.test_case.fail(msg=msg + queries) else: ongebruikt = self.num - executed if self.num > 20: if ongebruikt / self.num > 0.25: # pragma: no cover queries = 'Captured queries from index %s to %s:' % ( self.initial_queries, final_queries) for i, query in enumerate( self.connection. queries[self.initial_queries:final_queries], start=1): queries += '\n [%d] %s' % ( i, self._reformat_sql(query['sql'])) # for self.test_case.fail( msg= "Maximum (%s) has a lot of margin. Can be set as low as %s\n%s" % (self.num, executed, queries))
def __call__(self, environ): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware() request_started.disconnect(close_old_connections) request_started.send(sender=self.__class__, environ=environ) request_started.connect(close_old_connections) request = WSGIRequest(environ) # sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably # required for backwards compatibility with external tests against # admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = self.get_response(request) # Simulate behaviors of most Web servers. conditional_content_removal(request, response) # Attach the originating request to the response so that it could be # later retrieved. response.wsgi_request = request # Emulate a WSGI server by calling the close method on completion. if response.streaming: response.streaming_content = closing_iterator_wrapper( response.streaming_content, response.close) else: request_finished.disconnect(close_old_connections) response.close() # will fire request_finished request_finished.connect(close_old_connections) return response
def templates_do_not_do_queries(app_configs, **kwargs): # get only the processors that aren't defaults processors = set(settings.TEMPLATE_CONTEXT_PROCESSORS) base_processors = set(global_settings.TEMPLATE_CONTEXT_PROCESSORS) only_these_processors = processors - base_processors request = RequestFactory().get('/') issues = [] # emulates .django.test.utils.CaptureQueriesContext.__enter__ connection.use_debug_cursor = True request_started.disconnect(reset_queries) raw_msg = 'executed {{ count }} quer{{ count|pluralize:"y,ies" }}' msg_template = Template(raw_msg) for processor in only_these_processors: count_before = len(connection.queries) # fetch and execute the context processor. # emulates django.template.context.RequestContext.__init__ data = import_string(processor)(request) # call any callables, and hope that __repr__ is defined and # causes an evaluation. for key, value in data.items(): if callable(value): value = value() repr(value) count_after = len(connection.queries) if count_after > count_before: final_count = count_after - count_before msg = msg_template.render(Context({'count': final_count})) issues.append( checks.Warning(msg, obj=processor, id="morechecks.W001")) # emulates .django.test.utils.CaptureQueriesContext.__exit__ connection.use_debug_cursor = False request_started.connect(reset_queries) return issues
if counter_field: fields = model._meta.get_all_field_names() if not isinstance(counter_field,(list,tuple)): counter_field = [counter_field] # Patch model fields for f in counter_field: if f not in fields: # Add counter field as usigned int model.add_to_class(f, models.PositiveIntegerField(default=0,editable=True,blank=True)) def __init_patch__(**kwargs): if not getattr(__init_patch__,'inited',False): from .settings import ATOMREGISTER for k in ATOMREGISTER: app, mod = k.split('.') model = import_class('%s.models' % app, mod) monkey(model,ATOMREGISTER[k]) setattr(__init_patch__,'inited',True) if len(sys.argv)>1 and ('run' in sys.argv[1] or 'server' in sys.argv[1] or sys.argv[1] in ['supervisor']): request_started.connect(__init_patch__) else: __init_patch__()
start_time = 0 db_time = 0 serializer_time = 0 def started(sender, **kwargs): # global start_time # global db_time start_time = time.time() def finished(sender, **kwargs): total_time = time.time() - start_time print ("Database lookup | %.6fs" % db_time) print ("Serialization | %.6fs" % serializer_time) print ("Django request/response | %.6fs" % total_time) request_started.connect(started) request_finished.connect(finished) def home(request): return render(request, 'rest/index.html') @api_view(['GET', 'POST']) def file_collection(request): # global serializer_time # global db_time if request.method == 'GET': db_start = time.time()
from django.core.signals import request_finished, request_started from django.dispatch import receiver from pynput.mouse import Listener def on_click(x, y, button, pressed): if pressed and button == button.left: print('Left clicked at ({0}, {1})'.format(x, y)) listeners = [] def listener_join(sender, **kwargs): listeners = [Listener(on_click=on_click)] listeners[0].start() def listener_stop(sender, **kwargs): if len(listeners) > 0: listeners[0].stop() request_started.connect(listener_stop, dispatch_uid='stop') request_finished.connect(listener_join, dispatch_uid='start')
def ready(self): from config.utils.utils import log_request request_started.connect(log_request)
if kwargs['action'] == 'post_add': logger.info("List of students was modified \ in result_exam {}".format(result_exam.id)) # bellow will be custom signal contact_admin_signal = Signal(providing_args=[]) def contact_admin_handler(sender, **kwargs): logger = logging.getLogger('contact_admin_logger') logger.info("My custom handler for contact admin form.") contact_admin_signal.connect(contact_admin_handler) # handler for requests def counter_start_request(sender, **kwargs): day_counter, created = DayCounterRequest.objects.get_or_create(date=date.today()) day_counter.counter += 1 day_counter.save() logger = logging.getLogger('django.request') logger.info("request #{}".format(day_counter.counter)) request_started.connect(counter_start_request) @receiver(post_migrate) def all_migrate_command(sender, **kwargs): logger = logging.getLogger(__name__) db_info = kwargs['using'] app_config_label = kwargs['app_config'].label logger.info("Here is used {} database! App: {}".format(db_info, app_config_label))
def setUp(self): self.signals = [] request_started.connect(self.register_started) request_finished.connect(self.register_finished)
from django.core.signals import request_finished, request_started def request_started_callback(sender, environ, **kwargs): method = environ.get('REQUEST_METHOD', None) uri = '%s%s' % (environ.get('HTTP_HOST'), environ.get('PATH_INFO')) print('request started -> %s on %s' % (method, uri)) def request_finished_callback(sender, **kwargs): print('request finished') request_started.connect(request_started_callback) request_finished.connect(request_finished_callback)
# -*- coding: utf-8 -*- # __author__: MUSIBII # __email__ : [email protected] # __file__ : __init__.py.py # __time__ : 2019-05-26 16:16 from django.core.signals import request_started def call(*args, **kwargs): return kwargs request_started.connect(call())
class TriggerDate(Trigger): date = models.DateTimeField() class Meta: verbose_name = _(u'Date Trigger') verbose_name_plural = _(u'Date Triggers') def __str__(self): return str(self.date) class TriggerObject(models.Model): fields_trigger = models.CharField(max_length=1000) def activate_semaphore(self): pass def free_semaphore(self): pass def callback_event(sender, **kwargs): for e in Event.objects.filter(done=False): if len(e.triggerdate_set.filter(date__lte=datetime.now())) > 0: e.apply_event() request_started.connect(callback_event)
from django.conf import settings from django.core.signals import request_started, request_finished from django.core.urlresolvers import reverse from django.utils.encoding import smart_unicode, smart_str from speedbar.signals import setup_request_tracing, store_request_trace from speedbar.utils import init_modules from speedbar.modules.base import RequestTrace if getattr(settings, 'SPEEDBAR_ENABLE', True): # We hook everything up in the middleware file as loading the middleware is one of the first things performed # by the django WSGI implementation. init_modules() request_started.connect( setup_request_tracing, dispatch_uid='request_started_speedbar_setup_request_tracing') request_finished.connect( store_request_trace, dispatch_uid='request_started_speedbar_store_request_trace') HTML_TYPES = ('text/html', 'application/xhtml+xml') METRIC_PLACEHOLDER_RE = re.compile( '<span data-module="(?P<module>[^"]+)" data-metric="(?P<metric>[^"]+)"></span>' ) class SpeedbarMiddleware(MiddlewareMixin): """ Middleware module to add speedbar related headers to respones and replace any speedbar template tags with their correct values.
client.connect('tcp://%s' % settings.JAZZ_SERVER) else: client = None def ping(*args, **kwargs): client.send('ping') client.recv() def trash(*args, **kwargs): client.send('trash') client.recv() def error(*args, **kwargs): client.send('error') client.recv() if client: client.send('ping') client.recv() from django.core.signals import request_started, got_request_exception from django.db.models.signals import post_delete request_started.connect(ping) post_delete.connect(trash) got_request_exception.connect(error)
def __unicode__(self): ret = "<Chat: %s, %s, %s, " % (self.what, self.when, self.who) if self.what == "skip": ret += str(self.info) else: ret += self.message return ret + ">" class QueueItem(models.Model): who = models.CharField(max_length=200) what = models.ForeignKey('MusicFile') index = models.FloatField() @staticmethod def current(): items = QueueItem.objects.all()[:1] if len(items) == 0: return None else: return items[0] def __unicode__(self): return "<Music item %s>" % str(self.what) class Meta: ordering = ["index"] request_started.connect(runStartupTasks)
def my_callback(sender, **kwargs): print("Login !") def my_callback0(sender, **kwargs): print("Request finished!+++++") def my_callback1(sender, **kwargs): print("Request Started!+++++") from django.core.signals import request_finished, request_started request_finished.connect(my_callback0) request_started.connect(my_callback1) from django.contrib.auth import user_logged_in user_logged_in.connect(my_callback) ############################################################################### from django import forms class ExamDocumentForm(forms.Form): docfile = forms.FileField(label='Select a file') def list(request):
def tearDown(self): request_started.connect(close_old_connections)
def ready(self): request_started.connect(check_apps_need_reloading)
cache_signals = CacheSignals() def load_cache_signals(version=None, **kwargs): """On startup, sync signals with registered models""" if not cache_signals.ready: results = CacheBotSignals.objects.all() tables = [r.table_name for r in results] mapping = cache.get_many(tables) for result in results: key = cache.make_key(u'.'.join(('cachesignals', result.table_name)), version=version) accessor_set = mapping.get(key) or set() accessor_set.add((result.accessor_path, result.lookup_type, result.exclude)) mapping[key] = accessor_set cache.set_many(mapping, 0) cache_signals.ready = True request_started.connect(load_cache_signals) ### INVALIDATION FUNCTIONS ### def post_update_cachebot(sender, queryset, **kwargs): invalidate_cache(sender, queryset) post_update.connect(post_update_cachebot) def post_save_cachebot(sender, instance, **kwargs): invalidate_cache(sender, (instance,)) post_save.connect(post_save_cachebot) def pre_delete_cachebot(sender, instance, **kwargs): invalidate_cache(sender, (instance,)) pre_delete.connect(pre_delete_cachebot)
from __future__ import unicode_literals
from configs import CONFIG_CACHE, CONFIGS from django.core.signals import request_started def nuke_cache(**kwargs): for key in CONFIGS.keys(): if key in CONFIG_CACHE: #the following is necessary because not everyone will keep calling get_config config = CONFIG_CACHE[key] config._reset() request_started.connect(nuke_cache)
results = CacheBotSignals.objects.all() tables = [r.table_name for r in results] mapping = cache.get_many(tables) for result in results: key = cache.make_key(u'.'.join( ('cachesignals', result.table_name)), version=version) accessor_set = mapping.get(key) or set() accessor_set.add( (result.accessor_path, result.lookup_type, result.exclude)) mapping[key] = accessor_set cache.set_many(mapping, 0) cache_signals.ready = True request_started.connect(load_cache_signals) ### INVALIDATION FUNCTIONS ### def post_update_cachebot(sender, queryset, **kwargs): invalidate_cache(sender, queryset) post_update.connect(post_update_cachebot) def post_save_cachebot(sender, instance, **kwargs): invalidate_cache(sender, (instance, )) post_save.connect(post_save_cachebot)
from django.contrib.sessions.backends.db import SessionStore from django.core.signals import request_started def set_default_language(sender, **kwargs): r = kwargs print '---------- TRACE --------' print sender.request_class #print sender.request_class.REQUEST #print r #if 'django_language' not in r.session: # r.session['django_language'] = 'en' # Connect the request_started signal. request_started.connect(set_default_language)
def start_listening(): log.debug('setting up threaded keyedcache') cache_use_request_caching() request_started.connect(set_request_uid) request_finished.connect(clear_request_uid)
session = Session.objects.get(session_key=session_id) except Session.DoesNotExist: session = None if session: user_id = session.get_decoded().get('_auth_user_id') try: user = get_user_model().objects.get(id=user_id) except: user = None request_event = audit_logger.request({ 'url': environ['PATH_INFO'], 'method': environ['REQUEST_METHOD'], 'query_string': environ['QUERY_STRING'], 'user_id': getattr(user, 'id', None), 'remote_ip': environ[REMOTE_ADDR_HEADER], 'datetime': timezone.now() }) if WATCH_REQUEST_EVENTS: request_started.connect(request_started_handler, dispatch_uid='easy_audit_signals_request_started')
def ready(self): from django.core.signals import request_finished, request_started from fluent.trans import ensure_threads_join, invalidate_caches_if_necessary request_finished.connect(ensure_threads_join, dispatch_uid="fluent.ensure_threads_join") request_started.connect(invalidate_caches_if_necessary, dispatch_uid="fluent.invalidate_caches_if_necessary")
def __exit__(self, exc_type, exc_value, traceback): self.connection.force_debug_cursor = self.force_debug_cursor request_started.connect(reset_queries) if exc_type is not None: return self.final_queries = len(self.connection.queries_log)
from configs import CONFIG_CACHE, CONFIGS from django.core.signals import request_started def nuke_cache(**kwargs): for key in CONFIGS.keys(): if hasattr(CONFIG_CACHE, key): delattr(CONFIG_CACHE, key) request_started.connect(nuke_cache)
def setUp(self): self.signals = [] self.signaled_environ = None request_started.connect(self.register_started) request_finished.connect(self.register_finished)
from django.conf import settings from django.core.signals import request_started, request_finished from django.core.urlresolvers import reverse from django.utils.encoding import smart_unicode, smart_str from speedbar.signals import setup_request_tracing, store_request_trace from speedbar.utils import init_modules from speedbar.modules.base import RequestTrace if getattr(settings, 'SPEEDBAR_ENABLE', True): # We hook everything up in the middleware file as loading the middleware is one of the first things performed # by the django WSGI implementation. init_modules() request_started.connect(setup_request_tracing, dispatch_uid='request_started_speedbar_setup_request_tracing') request_finished.connect(store_request_trace, dispatch_uid='request_started_speedbar_store_request_trace') HTML_TYPES = ('text/html', 'application/xhtml+xml') METRIC_PLACEHOLDER_RE = re.compile('<span data-module="(?P<module>[^"]+)" data-metric="(?P<metric>[^"]+)"></span>') class SpeedbarMiddleware(object): def process_request(self, request): if getattr(settings, 'SPEEDBAR_ENABLE', True): RequestTrace.instance().stacktracer.root.label = '%s %s' % (request.method, request.path) def process_response(self, request, response): if not getattr(settings, 'SPEEDBAR_ENABLE', True): return response
def ready(self): request_started.connect(log_request())
self.serializer_time = 0 return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8') def started_fn(sender, **kwargs): global started started = time.time() def finished_fn(sender, **kwargs): request_response_time = (time.time() - started) - cbv.dispatch_time total = cbv.db_time + cbv.serializer_time + cbv.api_view_time + cbv.render_time + request_response_time print('Database Lookup - db_time : {:.6f}s, {:>4.1f}%'.format( cbv.db_time, 100 * (cbv.db_time / total))) print('Serialization - serializer_time : {:.6f}s, {:>4.1f}%'.format( cbv.serializer_time, 100 * (cbv.serializer_time / total))) print('API View - api_view_time : {:.6f}s, {:>4.1f}%'.format( cbv.api_view_time, 100 * (cbv.api_view_time / total))) print('Response rendering - render_time : {:.6f}s, {:>4.1f}%'.format( cbv.render_time, 100 * (cbv.render_time / total))) print('Django request/response : {:.6f}s, {:>4.1f}%'.format( request_response_time, 100 * (request_response_time / total))) request_started.connect(started_fn) # 요청 처리 시작 request_finished.connect(finished_fn) # 요청 처리 끝
return super(PostRequestTask, self).apply_async(args=args, kwargs=kwargs, **extrakw) def apply_async(self, args=None, kwargs=None, **extrakw): if is_task_queuing_enabled_for_this_thread(): result = _append_task((self, args, kwargs, extrakw)) else: result = self.original_apply_async(args=args, kwargs=kwargs, **extrakw) return result # Replacement `@task` decorator. task = partial(base_task, base=PostRequestTask) # Hook the signal handlers up. # Start queuing the tasks only if we're inside a request-response cycle thread. request_started.connect(_start_queuing_tasks, dispatch_uid='{}.request_started'.format(__name__)) # Send the tasks to celery and stop queuing when the request is finished. request_finished.connect(_send_tasks_and_stop_queuing, dispatch_uid='{}.request_finished'.format(__name__)) # And make sure to discard the task queue when we have an exception in the # request-response cycle. got_request_exception.connect( _discard_tasks, dispatch_uid='{}.got_request_exception'.format(__name__))
# -*- coding: utf-8 -*- # __author__ = "Breakering" # Date: 2017/9/6 from django.core.signals import request_finished # 请求结束后 from django.core.signals import request_started # 请求到来前 from django.core.signals import got_request_exception # 请求异常后 from django.db.models.signals import class_prepared # 程序启动时,检测已注册的app中的modal类,对于每一个类,自动触发 from django.db.models.signals import pre_init, post_init # 构造方法前和构造方法后 from django.db.models.signals import pre_save, post_save # 对象保存前和对象保存后 from django.db.models.signals import pre_delete, post_delete # 对象删除前和对象删除后 from django.db.models.signals import m2m_changed # 操作第三张表前后 from django.db.models.signals import pre_migrate, post_migrate # 执行migrate命令前后 from django.test.signals import setting_changed # 使用test测试修改配置文件时 from django.test.signals import template_rendered # 使用test测试渲染模板时 from django.db.backends.signals import connection_created # 创建数据库连接时 def recive(sender, **kwargs): pass def save_obj(sender, **kwargs): pass request_started.connect(recive) post_save.connect(save_obj)
# Deleveoped By # Fahad Md Kamal # NCC ID: 00171328 from django.core.signals import request_started from django.conf import settings from .models import Fleet from datetime import datetime def checkdate(sender, **kwargs): fleets = Fleet.objects.all() # Checks for all Fleets and their approval date. # If it is 30 day it automatically sets False to is_approval of the fleet and to is_purchased parameter for fleet in fleets: if fleet.is_approved and fleet.duration_check() > 30: fleet.is_approved = False fleet.is_purchased = False fleet.save() request_started.connect(checkdate)
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.signals import request_started, request_finished from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "physionet.settings.development") application = get_wsgi_application() # If we are running under uWSGI, then store the current request path # in the process name (which can be seen with 'ps ax'.) try: from uwsgi import setprocname except ImportError: pass else: def set_process_name_for_request(sender, environ, **kwargs): path = environ.get('PATH_INFO', '<unknown>') setprocname('uwsgi ' + path) def unset_process_name(sender, **kwargs): setprocname('uwsgi (idle)') request_started.connect(set_process_name_for_request) request_finished.connect(unset_process_name)