如何将Django连接到Cassandra数据库?
我有一个项目需要用 Django
来开发,并且要使用 Cassandra
数据库。我查了相关文档,但里面只有关于 mysql
、sklite
和 postgre
数据库的信息,完全没有关于 Cassandra
的内容。我想找一个示例,看看怎么把 Django
连接到 Cassandra
。
我知道我需要在 setting.py
文件里设置数据库的配置:
# Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle".
"ENGINE": "django.db.backends.cassandra",
# DB name or path to database file if using sqlite3.
"NAME": "test",
# Not used with sqlite3.
"USER": "",
enter code here# Not used with sqlite3.
"PASSWORD": "",
# Set to empty string for localhost. Not used with sqlite3.
"HOST": "127.0.0.1",
但是它报了一个错:
Error was: No module named django_cassandra.base
有没有人能帮帮我?
2 个回答
1
Django目前不支持nosql数据库作为后端。不过,有一个很像Django的ORM工具叫做cqlengine,你可以在这里找到它,这个工具正在积极开发中,datastax团队表示他们正在和cqlengine的开发者合作。虽然你不能在settings.py文件中使用数据库定义,但你可以使用类似Django的命令,比如thingy.objects.all()来访问你的cassandra数据库。
在datastax网站上找到的原生python驱动程序更偏向于cqlsh,可能会让你想起oracle连接器,但速度稍微快一些。
链接中推荐的答案已经很老了。
希望这些信息对你有帮助。
2
你可以在你的Django项目文件夹里的settings.py文件中使用这个模式:
DATABASES = {
'default': {
'ENGINE': 'django_cassandra_engine', # Install this engine from https://pypi.org/project/django-cassandra-engine/
'NAME': 'yourkeyspace', # the keyspace was created at cassandra
'USER': 'user',
'PASSWORD': 'password',
'HOST': '127.0.0.1', # You can add your hosts here (use ,)
'OPTIONS': {
'replication': {
'strategy_class': 'SimpleStrategy', # or any strategy you need
'replication_factor': 1 # Depend on your decision
},
'connection': {
'consistency': ConsistencyLevel.ONE,
'lazy_connect': True,
'retry_connect': True,
'port': 9042, # default port
# You can add any connection options for cassandra.Cluster() here!
}
}
}
}