python - 为 Django.db 连接对象指定只读访问

标签 python django django-testing django-database django-postgresql

我有一系列集成级测试,它们作为管理命令在我的 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/

相关文章:

python - 无法读取 python 临时文件

django - Windows 中的旋转文件处理程序 "Text File Busy"

Django 使用不正确的序列起始值为 Postgresql 创建测试数据库

python - 如何比较两个大文本之间的度量 - Python 中的余弦、Jaccard 相似性、Sim_MinEdit (Sim_String) 和 Sim_Simple

python - Tensorflow:加载预训练的 ResNet 模型时出错

django - 如何从django-haystack和Elasticsearch中排除无关的搜索结果?

django - 工厂男孩错误 : ValueError: save() prohibited to prevent data loss due to unsaved related object

python - 有什么方法可以将自定义/调试消息添加到 python/django unittest.TestCase 的失败测试方法的详细信息中?

python - 为什么 HTTPS 请求会产生 SSL CERTIFICATE_VERIFY_FAILED 错误?

javascript - Django - Javascript - 在图像刷新时禁用缓存