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

使用cloudant库访问CouchDB数据库返回None的问题

问题

使用Cloudant Python库连接CouchDB数据库已成功,调用client.all_dbs()能看到包含test_db的数据库列表,但用client[db_name]或client.get(db_name)访问该数据库时返回None。已确认数据库名称正确,尝试设置partitioned=True和False均无效果。

测试代码

import urllib3
from requests_pkcs12 import Pkcs12Adapter
from cloudant.client import CouchDB
import warnings
from cryptography.fernet import Fernet

def connect_to_db(db_name):

    warnings.simplefilter('ignore', urllib3.exceptions.SecurityWarning)

    pkcs12_filename = 'path_to_client03.p12'
    pkcs12_password = 'pkcs12_password'
    CERT = 'path_client.crt'
    KEY = 'path_client.key'

    adapter = Pkcs12Adapter(pkcs12_filename=pkcs12_filename, pkcs12_password=pkcs12_password)
    USERNAME = 'user'
    PASSWORD = 'password'

    try:
        client = CouchDB(USERNAME, PASSWORD, url='https://url', connect=True, cert=(CERT, KEY), adapter=adapter, partitioned=True)

        if not client.session():
            print("CONNEXION  : Failed to establish a session with CouchDB.")
            return None

        print('CONNEXION  : Client created successfully.')
        print("Available databases:", client.all_dbs())

        if db_name in client:
            my_database = client[db_name]
            print(f'CONNEXION  : Database "{db_name}" accessed successfully.')
            return my_database
        else:
            print(f'CONNEXION  : Database "{db_name}" not found.')
            return None

    except Exception as e:
        print(f'CONNEXION  : Error connecting to CouchDB: {e}')
        return None

test = connect_to_db('test_db')
print(test)

运行输出

CONNEXION  : Client created successfully.
Available databases: ['_replicator', '_users', 'abir_test', 'production', ... , 'test_db', ...]
CONNEXION  : Database "test_db" not found.
None
解决方案
  • 直接构造Database对象:绕过client[db_name]的内置判断逻辑,手动初始化数据库实例,代码示例:
    from cloudant.database import Database
    # 在确认db_name存在于all_dbs()结果后执行
    my_database = Database(client, db_name)
    if my_database.exists():
        print(f'成功访问数据库 "{db_name}"')
        return my_database
    
  • 检查用户权限:确认当前连接的用户对test_db拥有至少读取权限,可通过CouchDB管理界面验证权限配置。
  • 清空客户端缓存:client对象可能存在缓存数据,尝试调用client.reset()清空缓存后,再重新尝试访问数据库。
  • 核对名称大小写:CouchDB数据库名称区分大小写,确保传入的db_name与client.all_dbs()返回的名称大小写完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 14:07:05