You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法将Django服务器连接至AstraDB(Cassandra托管服务)

问题描述

我在AstraDB上托管了Cassandra数据库,首次使用Django,尝试将Django服务器与该数据库连接。以下是我的settings.py配置代码:

from pathlib import Path
from cassandra import ConsistencyLevel
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
import os
from dotenv import load_dotenv
import dse

load_dotenv()

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'SECURE_KEY'
DEBUG = True
ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blogs',
    'graphene_django',
]

INSTALLED_APPS = ['django_cassandra_engine'] + INSTALLED_APPS
SESSION_ENGINE = 'django_cassandra_engine.sessions.backends.db'

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'core.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django_cassandra_engine',
        'NAME': 'jasontechblog',
        'OPTIONS': {
            'connection': {
                'auth_provider': PlainTextAuthProvider('CLIENT_ID', 'CLIENT_SECRET'),
                'cloud': {
                    'secure_connect_bundle': 'secure-connect-jasontechblog.zip'
                }
            },
        }
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

已确认密钥和ID正确,但执行python3 manage.py syncdb同步模型至数据库时,出现以下错误:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django_cassandra_engine/connection.py", line 76, in register
    connection.get_connection(name=self.alias)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/dse/cqlengine/connection.py", line 242, in get_connection
    raise CQLEngineException("Connection name '{0}' doesn't exist in the registry.".format(name))
dse.cqlengine.CQLEngineException: Connection name 'default' doesn't exist in the registry.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/urllib/request.py", line 1348, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/http/client.py", line 1286, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/http/client.py", line 1332, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/http/client.py", line 1281, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/http/client.py", line 1041, in _send_output
    self.send(msg)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/http/client.py", line 979, in send
    self.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/http/client.py", line 1458, in connect
    self.sock = self._context.wrap_socket(self.sock,
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/ssl.py", line 517, in wrap_socket
    return self.sslsocket_class._create(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/ssl.py", line 1108, in _create
    self.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/ssl.py", line 1379, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: NO_CIPHERS_AVAILABLE] no ciphers available (_ssl.c:1006)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/dse/datastax/cloud/__init__.py", line 128, in read_metadata_info
    response = urlopen(url, context=config.ssl_context, timeout=timeout)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/urllib/request.py", line 216, in urlopen
    return opener.open(url, data, timeout)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/urllib/request.py", line 519, in open
    response = self._open(req, data)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/urllib/request.py", line 536, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/urllib/request.py", line 496, in _call_chain
    result = func(*args)
             ^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/urllib/request.py", line 1391, in https_open
    return self.do_open(http.client.HTTPSConnection, req,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/urllib/request.py", line 1351, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: NO_CIPHERS_AVAILABLE] no ciphers available (_ssl.c:1006)>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/jasontan/Documents/Jason/jason-tech-blog/jason-tech-blog/server/manage.py", line 22, in <module>
    main()
  File "/Users/jasontan/Documents/Jason/jason-tech-blog/jason-tech-blog/server/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 416, in execute
    django.setup()
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 116, in populate
    app_config.import_models()
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django_cassandra_engine/apps.py", line 60, in import_models
    self.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django_cassandra_engine/apps.py", line 57, in connect
    conn.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django_cassandra_engine/base/__init__.py", line 108, in connect
    self.connection = CassandraConnection(self.alias, **settings)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django_cassandra_engine/connection.py", line 72, in __init__
    self.register()
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django_cassandra_engine/connection.py", line 86, in register
    cluster = Cluster(**self.cluster_options)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/dse/cluster.py", line 1031, in __init__
    cloud_config = dscloud.get_cloud_config(cloud)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/dse/datastax/cloud/__init__.py", line 90, in get_cloud_config
    return read_metadata_info(config, cloud_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/dse/datastax/cloud/__init__.py", line 131, in read_metadata_info
    raise DriverException("Unable to connect to the metadata service at %s" % url)
dse.DriverException: Unable to connect to the metadata service at https://9b4178b8-3300-48f8-b03b-cdf66785c621-us-east1.db.astra.datastax.com:29080/metadata

使用的依赖版本:

Django==5.0.4
django-cassandra-engine==1.9.0
cassandra-driver==3.29.1

期望在数据库中看到与定义模型对应的表,但目前无法实现,寻求问题解决方法。


解决方法

1. 修复SSL cipher兼容性问题

核心错误是ssl.SSLError: [SSL: NO_CIPHERS_AVAILABLE],这是Python 3.11与旧版cassandra-driver的SSL适配问题。可以通过以下方式解决:

  • 在settings.py顶部导入ssl模块,然后在数据库配置中指定SSL版本:
    import ssl
    
    # ... 其他配置 ...
    
    DATABASES = {
        'default': {
            'ENGINE': 'django_cassandra_engine',
            'NAME': 'jasontechblog',
            'OPTIONS': {
                'connection': {
                    'auth_provider': PlainTextAuthProvider(os.getenv('ASTRA_CLIENT_ID'), os.getenv('ASTRA_CLIENT_SECRET')),
                    'cloud': {
                        'secure_connect_bundle': str(BASE_DIR / 'secure-connect-jasontechblog.zip')
                    },
                    'ssl_options': {
                        'ssl_version': ssl.PROTOCOL_TLSv1_2
                    }
                },
            }
        }
    }
    
  • 升级本地OpenSSL到最新版本,确保支持足够的加密套件。

2. 调整依赖版本兼容性

django-cassandra-engine 1.9.0对Django 5.x的支持不完善,建议降级Django到4.2.x版本,同时调整cassandra-driver版本:

Django==4.2.10
django-cassandra-engine==1.9.0
cassandra-driver==3.28.0

3. 修正配置细节

  • 使用绝对路径指定secure_connect_bundle,避免相对路径导致的文件找不到问题:
    'secure_connect_bundle': str(BASE_DIR / 'secure-connect-jasontechblog.zip')
    
  • 通过环境变量读取凭证,不要硬编码CLIENT_ID和CLIENT_SECRET:
    'auth_provider': PlainTextAuthProvider(os.getenv('ASTRA_CLIENT_ID'), os.getenv('ASTRA_CLIENT_SECRET')),
    

4. 使用正确的同步命令

Django 5.x中syncdb已被弃用,对于django-cassandra-engine,应使用专属同步命令:

python3 manage.py sync_cassandra

5. 尝试降级Python版本

如果上述方法无效,暂时降级Python到3.10版本,避免Python 3.11与旧驱动的SSL兼容性问题。


内容的提问来源于stack exchange,提问作者Jason Tan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 15:03:11