为Django.db连接对象指定只读访问权限 [英] Specifying Readonly access for Django.db connection object
问题描述
我有一系列集成级别的测试,这些测试在我的Django项目中作为管理命令运行。这些测试正在验证从外部来源吸收到我的数据库中的大量天气数据的完整性。因为我有大量的数据,所以我确实必须针对生产数据库进行测试才能使测试有意义。我要弄清楚的是如何定义特定于该命令或连接对象的只读数据库连接。我还应该补充一点,这些测试无法通过ORM,因此我需要执行原始SQL。
I have a series of integration-level tests that are being run as a management command in my Django project. These tests are verifying the integrity of a large amount of weather data ingested from external sources into my database. Because I have such a large amount of data, I really have to test against my production database for the tests to be meaningful. What I'm trying to figure out is how I can define a read-only database connection that is specific to that command or connection object. I should also add that these tests can't go through the ORM, so I need to execute raw 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()方法如下所示:
And the WeatherManager.CollectWeatherData() method would look like this:
def CollecWeatherData(self):
cur = connection.cursor()
cur.execute(<Raw SQL Query>)
wm.WeatherData = cur.fetchall()
cur.close()
我想以某种方式防止白痴这样,以便其他人(或我)以后无法再出现并意外地编写了一个可以修改生产数据库的测试。
I want to somehow idiot-proof this, so that someone else (or me) can't come along later and accidentally write a test that would modify the production database.
推荐答案
再说一次,在这里发表问题之前,我应该更仔细地阅读文档。我可以在设置文件中定义到生产数据库的只读连接,然后直接从 docs :
Man, once again, I should read the docs more carefully before I post questions here. I can define a readonly connection to my production database in the settings file, and then straight from the docs:
如果您使用多个数据库,则可以使用django.db.connections获取一个数据库的连接(和游标)。特定的数据库。 django.db.connections是一个类似于字典的对象,允许您使用其别名检索特定的连接:
If you are using more than one database, you can use django.db.connections to obtain the connection (and cursor) for a specific database. django.db.connections is a dictionary-like object that allows you to retrieve a specific connection using its alias:
from django.db import connections
cursor = connections['my_db_alias'].cursor()
# Your code here...
这篇关于为Django.db连接对象指定只读访问权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!