def test_nesting(self): set_thread_readwrite_db() assert is_thread_readwrite() with readonly_db(): assert not is_thread_readwrite() with readwrite_db(): assert is_thread_readwrite() assert not is_thread_readwrite() assert is_thread_readwrite()
def test_readwrite(self): self.assertFalse(was_db_written()) set_thread_readwrite_db() master = 'my_master_db' with override_settings(MASTER_DATABASE=master): router = DBRouter() out = router.db_for_read(Submission) self.assertEqual(master, out) out = router.db_for_write(Submission) self.assertEqual(master, out) self.assertTrue(was_db_written())
def update_recent_events(): """ Compute recent events and other statistics and cache them. """ logger.debug("update_recent_events: started") try: # No middleware on tasks, so this won't get set otherwise. # Tell the DB router this thread only needs to read the DB, not write. # We run this task frequently, so it's worthwhile. set_thread_readonly_db() votes = Vote.objects.select_related( "voter", "voter__user", "submission").filter( submission__approved=True, submission__duplicate_of__isnull=True).exclude( voter=F('submission__voter')).order_by("-id")[:10] submissions = Submission.objects.select_related( "voter", "voter__user").filter( approved=True, duplicate_of__isnull=True).order_by("-id")[:10] entries = list(votes) + list(submissions) entries = sorted(entries, key=lambda x: x.created_at, reverse=True)[:10] cache.set(RECENT_EVENTS_CACHE_ENTRY, entries, 24*3600) number_of_votes = Vote.objects.count() cache.set(NUMBER_OF_VOTES_CACHE_ENTRY, number_of_votes, 24*3600) logger.debug("There are %d entries" % len(entries)) logger.debug("There are %d votes" % number_of_votes) except: # This task runs too frequently to report a recurring problem every time # it happens. global exception_logged if not exception_logged: logger.exception("Unexpected exception in update_recent_events") exception_logged = True finally: # Be a good citizen and reset the worker's thread to the default state set_thread_readwrite_db()
def test_with_readonly_db_when_readwrite(self): set_thread_readwrite_db() assert is_thread_readwrite() with readonly_db(): assert not is_thread_readwrite() assert is_thread_readwrite()