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

在Django中调用gremlinpython异步查询出现证书验证错误

解决本地Django调用Azure Cosmos DB Gremlin客户端的SSL证书验证失败问题

问题概述

同一Gremlin查询模块,本地Jupyter Notebook调用正常,但本地Django应用调用时抛出SSL证书验证错误:

Cannot connect to host graph-exodestiny.gremlin.cosmos.azure.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)')]

该模块核心代码如下:

## Managing the client
def open_client(self):
        self.c = client.Client(
            self.endpoint,
            "g",
            username=self.username,
            password=self.password,
            message_serializer=serializer.GraphSONSerializersV2d0(),
        )
        
def close_client(self):
    self.c.close()

## Managing the queries
def run_query(self, query="g.V().count()"):
    self.open_client()
    callback = self.c.submitAsync(query)
    res = callback.result().all().result()
    self.close_client()
    self.res = res

本地Jupyter与Django共享同一环境、同一连接器模块,且Azure Web App部署的相同应用运行正常。

解决方案

1. 配置Gremlin客户端使用可信CA证书(推荐)

通过ssl_options参数指定CA证书路径,推荐使用certifi库提供的标准CA证书集合:

  1. 先安装certifi:
pip install certifi
  1. 修改open_client方法:
import certifi

def open_client(self):
        self.c = client.Client(
            self.endpoint,
            "g",
            username=self.username,
            password=self.password,
            message_serializer=serializer.GraphSONSerializersV2d0(),
            ssl_options={"ca_certs": certifi.where()}
        )

2. 临时禁用证书验证(仅测试场景)

如果是本地测试需要快速验证功能,可临时关闭SSL证书验证(生产环境绝对禁止使用):

def open_client(self):
        self.c = client.Client(
            self.endpoint,
            "g",
            username=self.username,
            password=self.password,
            message_serializer=serializer.GraphSONSerializersV2d0(),
            ssl_options={"verify": False}
        )

3. 配置Django环境的SSL证书路径

若上述方法无效,可在Django启动入口(如manage.py)添加环境变量配置,强制指定CA证书路径:

import os
import certifi

os.environ['REQUESTS_CA_BUNDLE'] = certifi.where()

# 原有Django启动代码
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings")
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

原因分析

本地Jupyter环境默认加载了系统或certifi提供的可信CA证书集合,而Django运行环境(如开发服务器、WSGI容器)可能未正确读取这些证书配置,导致无法验证Azure Cosmos DB的SSL证书。Azure Web App环境已内置完整的CA证书链,因此无需额外配置即可正常连接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:07:17