def test_readonly_three_replicas(self): set_thread_readonly_db() replica0 = 'my-replica-db0' replica1 = 'my-replica-db1' replica2 = 'my-replica-db2' pool = { replica0: 1, replica1: 1, replica2: 1, } replicas = pool.keys() with override_settings(DATABASE_POOL=pool): router = DBRouter() out0 = router.db_for_read(Submission) self.assertIn(out0, replicas) out1 = router.db_for_read(Submission) self.assertIn(out1, replicas) self.assertNotEqual(out0, out1) out2 = router.db_for_read(Submission) self.assertIn(out2, replicas) self.assertNotEqual(out1, out2) out3 = router.db_for_read(Submission) # Round-robin should have come around by now self.assertEqual(out3, out0) self.assertFalse(was_db_written())
def test_readonly_one_replica(self): set_thread_readonly_db() replica = 'my-only-replica-db' pool = { replica: 1 } with override_settings(DATABASE_POOL=pool): router = DBRouter() out = router.db_for_read(Submission) self.assertEqual(replica, out) out = router.db_for_read(Submission) self.assertEqual(replica, out) self.assertFalse(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_readonly(self): set_thread_readonly_db() assert not is_thread_readwrite() with readonly_db(): assert not is_thread_readwrite() assert not is_thread_readwrite()