Python出现ModuleNotFoundError: No module named 'certs.check'报错如何解决
错误根因
check.crt是SSL证书资源文件,不是后缀为.py的Python模块,使用import语句导入非Python模块的文件,必然会抛出ModuleNotFoundError。你需要做的是读取该证书的文件路径,传入MongoClient的对应配置项,而非导入文件。
正确实现方案
方案1:在连接字符串中拼接证书参数
import os import pymongo import constants class Client: def get_parameters(self): # 动态获取check.crt的绝对路径,避免相对路径出错 cert_path = os.path.join(os.path.dirname(__file__), "Certs", "check.crt") # 拼接标准MongoDB连接串,证书作为查询参数传入 conn_str = f"mongodb://{constants.USER_NAME}:{constants.PWD}@{constants.server}/?ssl=true&ssl_ca_certs={cert_path}" client = pymongo.MongoClient(conn_str) print("Done") c = Client() c.get_parameters()
方案2:通过MongoClient单独参数传入证书
代码可读性更高,避免字符串拼接错误:
import os import pymongo import constants class Client: def get_parameters(self): cert_path = os.path.join(os.path.dirname(__file__), "Certs", "check.crt") client = pymongo.MongoClient( host=constants.server, username=constants.USER_NAME, password=constants.PWD, ssl=True, tlsCAFile=cert_path ) print("Done") c = Client() c.get_parameters()
注意事项
- 注意文件夹名大小写为
Certs,Linux、macOS系统下路径大小写敏感,拼写错误会导致找不到证书文件 - 若MongoDB服务未开启SSL验证,可直接去掉ssl相关配置和证书参数,不需要传入crt文件
内容的提问来源于stack exchange,提问作者user15780176
相关产品推荐
相关产品推荐

