我有一系列集成级测试,它们作为管理命令在我的 Django 项目中运行。这些测试正在验证从外部来源摄取到我的数据库中的大量天气数据的完整性。因为我有如此大量的数据,所以我真的必须针对我的生产数据库进行测试才能使测试有意义。我想弄清楚的是如何定义特定于该命令或连接对象的只读数据库连接。我还应该补充一点,这些测试无法通过 ORM,因此我需要执行原始 SQL。
我的测试结构是这样的
class Command(BaseCommand):
help = 'Runs Integration Tests and Query Tests against Prod Database'
def handle(self,*args, **options):
suite = unittest.TestLoader().loadTestsFromTestCase(TestWeatherModel)
ret = unittest.TextTestRunner().run(suite)
if(len(ret.failures) != 0):
sys.exit(1)
else:
sys.exit(0)
class TestWeatherModel(unittest.TestCase):
def testCollectWeatherDataHist(self):
wm = WeatherManager()
wm.CollectWeatherData()
self.assertTrue(wm.weatherData is not None)
WeatherManager.CollectWeatherData() 方法看起来像这样:
def CollecWeatherData(self):
cur = connection.cursor()
cur.execute(<Raw SQL Query>)
wm.WeatherData = cur.fetchall()
cur.close()
我想以某种方式防止白痴发生,以免其他人(或我)稍后出现并意外编写会修改生产数据库的测试。
最佳答案
您可以通过连接到 Django 的 connection_created
信号来实现这一点,并且
然后将交易设为只读。
以下适用于 PostgreSQL:
from django.db.backends.signals import connection_created
class MyappConfig(AppConfig):
def ready(self):
def connection_created_handler(connection, **kwargs):
with connection.cursor() as cursor:
cursor.execute('SET default_transaction_read_only = true;')
connection_created.connect(connection_created_handler, weak=False)
这对于某些特定的 Django 设置很有用(例如运行开发
使用 runserver
针对生产数据库编写代码),您不希望这样做
创建一个真正的只读数据库用户。
关于python - 为 Django.db 连接对象指定只读访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39794123/