Pymongo error connecting to mongodb via atlas - python

I am trying to establish a connection to my mongodb database via atlas and pymongo. I am connecting my application using the connection string given from atlas page, and everything seems to be working fine. I can connect to my database but then I get an error message when I try to count how many entries are in my database/retrieve/send data to atlas.
import pymongo
import dns
client = pymongo.MongoClient("mongodb+srv://username:<password>#storedinputs-vc4cl.mongodb.net/test?retryWrites=true")
db = client.get_database("dbname")
records = db.collectiontable
count = records.count_documents({})
print(count)
Then I get the following error:
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issue
r certificate (_ssl.c:1056),storedinputs-shard-00-00-vc4cl.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] cer
tificate verify failed: unable to get local issuer certificate (_ssl.c:1056)
Again I've tried it line by line and everything works fine until I try and count the amount of documents in my collection. I appreciate all the help I can get.

Try with
client = pymongo.MongoClient("mongodb+srv://username:<password>#storedinputs-vc4cl.mongodb.net/test", ssl=True,ssl_cert_reqs='CERT_NONE')
It should work.

Just add '&ssl=true&ssl_cert_reqs=CERT_NONE' to the db string and it will work fine !

Take a look at the troubleshooting section in PyMongo documentation, it covers the issue you are experiencing together with possible solutions.

Related

python-oracledb thin client returns DPY-6005

I'm trying to connect to a 21c ATP and 19c ADP (free tier, ACL enabled/configured with "My Address", TLS enabled (mTLS set to "Not required"), connection string contains "ssl_server_dn_match=yes") using Python's thin client but at the point of making a connection or setting up a connection pool, I get:
OperationalError: DPY-6005: cannot connect to database. Connection
failed with "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify
failed: self signed certificate in certificate chain (_ssl.c:1131)"
Envioronment:
DB: ATP 21c and ADP 19c
Python client library: oracledb-1.2.1 (I've tried 1.2.0 and 1.1.1, as well, but to no avail)
Environment: Python 3.10.4 and 3.8.10 (running on Mac OS)
Code sample:
import oracledb
# copied from the ATP's "Database Connection"
cs='''(description= (retry_count=20)(retry_delay=3)(address=(protocol=tcps)(port=1521)(host=adb.uk-london-1.oraclecloud.com))(connect_data=(service_name=xxxx.adb.oraclecloud.com))(security=(ssl_server_dn_match=yes)))'''
connection = oracledb.connect(user="admin", password="<password>", dsn=cs)
with connection.cursor() as cursor:
try:
sql = """select systimestamp from dual"""
for r in cursor.execute(sql):
print(r)
except oracledb.Error as e:
error, = e.args
print(error.message)
print(sql)
if (error.offset):
print('^'.rjust(error.offset+1, ' '))
References:
I've used the following documents as a reference:
https://blogs.oracle.com/opal/post/easy-way-to-connect-python-applications-to-oracle-autonomous-databases
https://blogs.oracle.com/developers/post/writing-a-flask-application-using-python-oracledb
https://python-oracledb.readthedocs.io/en/latest/user_guide/installation.html
https://docs.oracle.com/en/cloud/paas/autonomous-database/adbsa/connecting-python-tls.html#GUID-CA446B91-BC48-4A66-BF69-B8D54B9CBAD4
That error tells you that the certificate supplied by the server is not one that any local certificate authority recognizes (which is necessarily the case with self-signed certificates). Two options are available to resolve this:
Tell the OS the certificate is acceptable by adding it to the OS certificate "store"
Use an Oracle wallet (ewallet.pem) that contains the relevant certificates and set the wallet_location parameter appropriately. This was discussed in this issue.

MongoEngine cannot connect through Atlas Uri string. Tried everything

I'm new to programming and am building my first app.. I'm building a kivy app trying to use mongoDB as the database. I can connect to a localhost to query and create documents. I cannot get it to connect to the atlas no matter what I try. I'm also using Pycharm and a venv.
Heres the basic info:
import pymongo
from pymongo.server_api import ServerApi
import mongoengine as mongo
import ssl
data = 'events'
username = 'admin'
password = 'abc123'
host_name = 'mongodb+srv://events.xfmhxnj.mongodb.net'
uri = f'mongodb+srv://{username}:{password}#events.xfmhxnj.mongodb.net/'
mongo.connect(db=db,
username=username,
password=password,
host=host_name)
class Obj(mongo.Document):
name = mongo.StringField(required=True)
div = Obj()
div.name = 'test'
div.save()
which gives me this error: raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: ac-liums0m-shard-00-00.xfmhxnj.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate
Then i looked up this error and found someone recommended:
mongo.connect(db=db,
username=username,
password=password,
host=host_name,
ssl=True,
ssl_cert_reqs=ssl.CERT_NONE,)
)
error: raise ConnectionFailure(f"Cannot connect to database {alias} :\n{e}") mongoengine.connection.ConnectionFailure: Cannot connect to database default : Unknown option ssl_cert_reqs
I don't understand why its an unknown option. pymongo has it listed in the example.
https://api.mongodb.com/python/3.3.0/examples/tls.html
I've also tried the string straight from Atlas:
client = pymongo.MongoClient(f"mongodb+srv://{username}:{password}#events.xfmhxnj.mongodb.net/?retryWrites=true&w=majority", server_api=ServerApi('1'))
db = client.test
client.server_info()
error: raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: ac-liums0m-shard-00-01.xfmhxnj.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate
or if i just paste in the uri string from compass
mongo.connect('mongodb+srv://admin:abc123#events.xfmhxnj.mongodb.net/test')
error: raise InvalidName("database names cannot contain the character %r" % invalid_char) pymongo.errors.InvalidName: database names cannot contain the character '.'
any help is super appreciated! I feel like i've tried every combination of connection settings. This is the last thing i need before pushing my app to x-code
Have you tried using MongoClient(connection_string, tlsCAFile=certifi.where()) ?
Certifi provides Mozilla’s carefully curated collection of Root
Certificates for validating the trustworthiness of SSL certificates
while verifying the identity of TLS hosts.
Before testing the new code remember to do "pip install certifi".

why is my python script saying I have an ssl certificate error when all my certificates are up to date

I'm trying to connect via websockets to a service called Alpaca, basically you subscribe to there server and they send stock data back through the websocket to your computer. Everything is running perfectly fine except when I try to run the software I get:
ERROR:root:error while consuming ws messages: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)
I check and updated my certificates about 1000 times and that clearly does nothing. I ran the code on another laptop that has python on it and when I ran it on that machine everything went fine. Its really weird and I cannot figure it out for the life of me so any help would be fantastic. the code below is actually what I'm running except I don't have my api keys since those need to be kept a secret.
import alpaca_trade_api as tradeapi
import threading
conn = tradeapi.stream2.StreamConn('api_key','api_secret_key','https://paperapi.alpaca.markets')
#conn.on(r'^trade_updates$')
async def on_trade_updates(conn, channel, trade):
print('trade', trade)def ws_start():conn.run(['account_updates', 'trade_updates'])
ws_thread = threading.Thread(target=ws_start, daemon=True)
ws_thread.start()

asyncpg error: "no pg_hba.conf entry for host" in Heroku

I'm using asyncpg to connect my database in Heroku postgresql, using python:
import asyncpg
async def create_db_pool():
bot.pg_con = await asyncpg.create_pool(dsn="postgres://....", host="....amazonaws.com", user="xxx", database="yyy", port="5432", password="12345")
it was working perfectly until I received an email from heroku advising me of a maintenance: Maintenance (DATABASE_URL on myappname) is starting now. We will update you when it has completed.
then this error appeared:
asyncpg.exceptions.InvalidAuthorizationSpecificationError: no pg_hba.conf entry for host "123.456.789.10", user "xxx", database "yyy", SSL off
I tried to follow some help, like putting ssl=True
but this error appeared:
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1108)
same as putting ssl="allow"
asyncpg.exceptions.InvalidPasswordError: password authentication failed for user "xxx"
what can I do to fix this?
Using the solution from this worked.
import ssl
ssl_object = ssl.create_default_context()
ssl_object.check_hostname = False
ssl_object.verify_mode = ssl.CERT_NONE
# connect elsewhere
pool = await asyncpg.create_pool(uri, ssl=ssl_object)
Note: You don't need to use any certificate like mentioned in the comment, as we set verify_mode to not use certificates.

Python - Issue SSL: CERTIFICATE_VERIFY_FAILED

I'm trying to solve the problem
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)
when I connect to a handle server.
I also used
ssl._create_default_https_context = ssl._create_unverified_context
as some user suggested, but I'm not able to fix the issue.
Any other solution?
Thanks
Does your server have a valid certificate, signed by a Certification Authority?
If it uses a self-signed certificate I would suggest that you save a copy of the public certificate in your Python project and pass the certificate name in the verify parameter on requests.
You can save the certificate by accessing the server on Firefox, clicking on the Lock icon near to the address bar, selecting the Certificate, then More details, then View Certificate, then export.
You will get a .pem file, let's say: "my_server_certificate.pem".
Then when you create your Session object on requests you can pass the parameter:
session = requests.Session()
session.verify = "my_server_certificate.pem"
I had similar problems when using charles proxy with my Python scripts. I hope this helps you solve your problem as well.

Categories

Resources