If I run in the shell:
mongo ds0219xx.mlab.com:219xx/dbname -u user -p pass
It works and allows me to connect to the database and pull information. But if I'm within my python application (Flask) and run this:
import pymongo
client = pymongo.MongoClient("mongodb://user:pass#ds0219xx.mlab.com:219xx/dbname")
db = client["dbname"]
db.users.insert_one({
"user1": "hello"
})
It gives me an:
pymongo.errors.OperationFailure: Authentication failed.
I'm pretty sure it's failing before it gets to the insert_one() call, but I'm not completely sure.
Thanks!
Edit:
By request, here is the full callback:
Traceback (most recent call last):
File "run.py", line 1, in <module>
from app import app
File "/Users/Derek/Documents/programming/shenalum/app/__init__.py", line 6, in <module>
from app import views
File "/Users/Derek/Documents/programming/shenalum/app/views.py", line 4, in <module>
from data import get_posts, get_user_info
File "/Users/Derek/Documents/programming/shenalum/app/data.py", line 9, in <module>
"user1": "hello"
File "/usr/local/lib/python2.7/site-packages/pymongo/collection.py", line 622, in insert_one
with self._socket_for_writes() as sock_info:
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/usr/local/lib/python2.7/site-packages/pymongo/mongo_client.py", line 718, in _get_socket
with server.get_socket(self.__all_credentials) as sock_info:
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/usr/local/lib/python2.7/site-packages/pymongo/server.py", line 152, in get_socket
with self.pool.get_socket(all_credentials, checkout) as sock_info:
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/usr/local/lib/python2.7/site-packages/pymongo/pool.py", line 541, in get_socket
sock_info.check_auth(all_credentials)
File "/usr/local/lib/python2.7/site-packages/pymongo/pool.py", line 306, in check_auth
auth.authenticate(credentials, self)
File "/usr/local/lib/python2.7/site-packages/pymongo/auth.py", line 436, in authenticate
auth_func(credentials, sock_info)
File "/usr/local/lib/python2.7/site-packages/pymongo/auth.py", line 416, in _authenticate_default
return _authenticate_scram_sha1(credentials, sock_info)
File "/usr/local/lib/python2.7/site-packages/pymongo/auth.py", line 188, in _authenticate_scram_sha1
res = sock_info.command(source, cmd)
File "/usr/local/lib/python2.7/site-packages/pymongo/pool.py", line 213, in command
read_concern)
File "/usr/local/lib/python2.7/site-packages/pymongo/network.py", line 99, in command
helpers._check_command_response(response_doc, None, allowable_errors)
File "/usr/local/lib/python2.7/site-packages/pymongo/helpers.py", line 196, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: Authentication failed.
I figured it out. You can do this from the python file and it will work:
connection = pymongo.MongoClient(ab123456.mlab.com, 123456)
db = connection[databasename]
db.authenticate(database_user, database_pass)
Appending /?authSource=admin helped me.
Full Example:
uri = 'mongodb://username:password#r1.example.net:27017/?authSource=admin'
client = MongoClient(uri)
db = client.test
result = db.users.find()
for document in result:
print(document)
Version: pymongo 3.7.2
You need to authenticate after selecting the database for mongo < 4.0
Related
I have a problem: I wrote python code to communicate with other people through a database that runs on Pymongo. My program was able to connect to the database but could not send files (this is how I tried to get my variable to the database: db.insert_one (msg)). The computer gives me this error:
Traceback (most recent call last):
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\pool.py", line 1394, in _get_socket
sock_info = self.sockets.popleft()
IndexError: pop from an empty deque
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Luis\PycharmProjects\PresentationGuru2021\main.py", line 133, in <module>
Startup()
File "C:\Users\Luis\PycharmProjects\PresentationGuru2021\main.py", line 63, in Startup
main()
File "C:\Users\Luis\PycharmProjects\PresentationGuru2021\main.py", line 128, in main
db.insert_one(msg)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\collection.py", line 705, in insert_one
self._insert(document,
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\collection.py", line 620, in _insert
return self._insert_one(
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\collection.py", line 609, in _insert_one
self.__database.client._retryable_write(
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\mongo_client.py", line 1552, in _retryable_write
return self._retry_with_session(retryable, func, s, None)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\mongo_client.py", line 1438, in _retry_with_session
return self._retry_internal(retryable, func, session, bulk)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\mongo_client.py", line 1462, in _retry_internal
with self._get_socket(server, session) as sock_info:
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 117, in __enter__
return next(self.gen)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\mongo_client.py", line 1308, in _get_socket
with server.get_socket(
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 117, in __enter__
return next(self.gen)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\pool.py", line 1331, in get_socket
sock_info = self._get_socket(all_credentials)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\pool.py", line 1397, in _get_socket
sock_info = self.connect(all_credentials)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\pool.py", line 1297, in connect
sock_info.check_auth(all_credentials)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\pool.py", line 820, in check_auth
self.authenticate(credentials)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\pool.py", line 837, in authenticate
auth.authenticate(credentials, self)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\auth.py", line 672, in authenticate
auth_func(credentials, sock_info)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\auth.py", line 590, in _authenticate_default
return _authenticate_scram(credentials, sock_info, 'SCRAM-SHA-1')
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\auth.py", line 333, in _authenticate_scram
res = sock_info.command(source, cmd)
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\pool.py", line 710, in command
return command(self, dbname, spec, secondary_ok,
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\network.py", line 158, in command
helpers._check_command_response(
File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\helpers.py", line 167, in _check_command_response
raise OperationFailure(errmsg, code, response, max_wire_version)
pymongo.errors.OperationFailure: bad auth : Authentication failed., full error: {'ok': 0, 'errmsg': 'bad auth : Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}
Can someone help me fix this?
Here is the code (without my password from Pymongo):
cluster = MongoClient (
"mongodb + srv: // Luis: <NOPASSWORT HERE> # cluster0.mme3c.mongodb.net / myFirstDatabase? retryWrites = true & w = majority")
db = cluster ["socialMedia"] ["messaging"]
date = datetime.now (). strftime ("% x")
person = username
message = input ("Message:")
time = datetime.now (). strftime ("% X")
msg = {"User": person, "message": message, "Date": date, "Time": time}
print (msg)
db.insert_one (msg)
I am receiving a 504 Deadline Exceeded error trying to run a simple python script to add a document to Firestore.
from firebase_admin import firestore, credentials
cred = credentials.Certificate("<path to service account>")
firebase_admin.initialize_app(cred)
print("initialized firebase successfully")
product_dict={
'test1': 'test',
'test2': 'test2'
}
firestore_client = firestore.client()
doc_ref = firestore_client.collection('products').document('test')
doc_ref.set(product_dict)
Output:
intialized firebase successfully
Traceback (most recent call last):
File "test.py", line 14, in <module>
doc_ref.set(product_dict)
File "/Users/.../env/lib/python2.7/site-packages/google/cloud/firestore_v1/document.py", line 234, in set
write_results = batch.commit()
File "/Users/.../env/lib/python2.7/site-packages/google/cloud/firestore_v1/batch.py", line 147, in commit
metadata=self._client._rpc_metadata,
File "/Users/.../env/lib/python2.7/site-packages/google/cloud/firestore_v1/gapic/firestore_client.py", line 1042, in commit
request, retry=retry, timeout=timeout, metadata=metadata
File "/Users/.../env/lib/python2.7/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
return wrapped_func(*args, **kwargs)
File "/Users/.../env/lib/python2.7/site-packages/google/api_core/retry.py", line 273, in retry_wrapped_func
on_error=on_error,
File "/Users/.../env/lib/python2.7/site-packages/google/api_core/retry.py", line 182, in retry_target
return target()
File "/Users/.../env/lib/python2.7/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
return func(*args, **kwargs)
File "/Users/.../env/lib/python2.7/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "/Users/.../env/lib/python2.7/site-packages/six.py", line 737, in raise_from
raise value
google.api_core.exceptions.DeadlineExceeded: 504 Deadline Exceeded
I've tried using Pipenv with Python 3.7, and virtualenv with python 2, same results.
Running from terminal on macOS Mojave 10.14.3
Hi I'm using pyftpsync in order to upload new images (downloaded every day) in a online store skipping the existing ones.
From the author site I'm using this code (with my personal data of course):
from ftpsync.targets import FsTarget
from ftpsync.ftp_target import FtpTarget
from ftpsync.synchronizers import UploadSynchronizer
local = FsTarget("~/temp")
user ="joe"
passwd = "secret"
remote = FtpTarget("/temp", "example.com", username=user, password=passwd)
opts= {"force": False, "delete_unmatched": True, "verbose": 3, "dry_run" : False}
s = UploadSynchronizer(local, remote, opts,tls=True)
s.run()
This work for me correctly only if I delete the tls option, otherwise I obtain this error while connecting to my server:
Traceback (most recent call last):
File "sync.py", line 25, in <module>
s.run()
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/synchronizers.py", line 139, in run
res = self._sync_dir()
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/synchronizers.py", line 416, in _sync_dir
remote_entries = self.remote.get_dir()
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/ftp_target.py", line 310, in get_dir
self.ftp.retrlines("MLSD", _addline)
File "/usr/lib/python3.4/ftplib.py", line 466, in retrlines
resp = self.sendcmd('TYPE A')
File "/usr/lib/python3.4/ftplib.py", line 272, in sendcmd
return self.getresp()
File "/usr/lib/python3.4/ftplib.py", line 235, in getresp
resp = self.getmultiline()
File "/usr/lib/python3.4/ftplib.py", line 221, in getmultiline
line = self.getline()
File "/usr/lib/python3.4/ftplib.py", line 209, in getline
raise EOFError
EOFError
Could not remove lock file: Underlying socket connection gone (_ssl.c:1570)
Exception ignored in: <bound method FtpTarget.__del__ of <ftpsync.ftp_target.FtpTarget object at 0x7fe397ae7710>>
Traceback (most recent call last):
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/targets.py", line 70, in __del__
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/ftp_target.py", line 153, in close
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/ftp_target.py", line 187, in _unlock
File "/usr/lib/python3.4/ftplib.py", line 613, in delete
File "/usr/lib/python3.4/ftplib.py", line 271, in sendcmd
File "/usr/lib/python3.4/ftplib.py", line 198, in putcmd
File "/usr/lib/python3.4/ftplib.py", line 193, in putline
File "/usr/lib/python3.4/ssl.py", line 720, in sendall
File "/usr/lib/python3.4/ssl.py", line 681, in send
ssl.SSLError: Underlying socket connection gone (_ssl.c:1570)
It's obviously a problem related to the encryption, but I don't know how to fix it.
I'm using python2.7 and fabric to connect to an sftp server.
Here's what I'm doing:
from fabric.api import env, get, run
env.key_filename = '/path/to/keyfile'
env.host_string = 'host.string'
env.user = 'user'
At this point, get('filename') successfully downloads a file from the sftp server. But run('ls') gives me:
[host.string] run: ls
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/fabric/network.py", line 647, in host_prompting_wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/fabric/operations.py", line 1054, in run
shell_escape=shell_escape)
File "/usr/local/lib/python2.7/dist-packages/fabric/operations.py", line 923, in _run_command
stderr=stderr, timeout=timeout)
File "/usr/local/lib/python2.7/dist-packages/fabric/operations.py", line 764, in _execute
channel.get_pty(width=cols, height=rows)
File "/usr/local/lib/python2.7/dist-packages/paramiko/channel.py", line 60, in _check
return func(self, *args, **kwds)
File "/usr/local/lib/python2.7/dist-packages/paramiko/channel.py", line 177, in get_pty
self._wait_for_event()
File "/usr/local/lib/python2.7/dist-packages/paramiko/channel.py", line 1086, in _wait_for_event
raise e
paramiko.ssh_exception.SSHException: Channel closed.
When I manually log into the sftp server, using the same creds, I can ls just fine.
Any ideas? Thanks.
I have provisioned many servers and deployed this project many times, but this is the first time I have come across this issue.
I can connect to MySQL via command line and Sequel Pro just fine, it's only the Django specific commands that are producing this error.
(Staging)optimal#Simon:/var/virtualenvs/Staging/app$ python manage.py syncdb
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/django/core/management/base.py", line 219, in execute
self.validate()
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/django/core/management/validation.py", line 36, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/django/db/models/loading.py", line 146, in get_app_errors
self._populate()
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/var/virtualenvs/Staging/releases/20130204145734/apps/orpheus/files/models.py", line 17, in <module>
from orpheus.orders.models import Order
File "/var/virtualenvs/Staging/releases/20130204145734/apps/orpheus/orders/models.py", line 29, in <module>
from orpheus.variable_images.models import Newsletter
File "/var/virtualenvs/Staging/releases/20130204145734/apps/orpheus/variable_images/models.py", line 144, in <module>
class Topper(mixins.ModifiedDates):
File "/var/virtualenvs/Staging/releases/20130204145734/apps/orpheus/variable_images/models.py", line 149, in Topper
file = CouchDBFileField(storage=LongTermStorage(), blank=True)
File "/var/virtualenvs/Staging/releases/20130204145734/apps/orpheus/files/storage.py", line 183, in __init__
self.db = server[kwargs.get('database')]
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/couchdb/client.py", line 137, in __getitem__
db.resource.head() # actually make a request to the database
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/couchdb/http.py", line 377, in head
return self._request('HEAD', path, headers=headers, **params)
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/couchdb/http.py", line 419, in _request
credentials=self.credentials)
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/couchdb/http.py", line 239, in request
resp = _try_request_with_retries(iter(self.retry_delays))
File "/var/virtualenvs/Staging/lib/python2.7/site-packages/couchdb/http.py", line 205, in _try_request_with_retries
raise e
socket.error: [Errno 111] Connection refused
I'm just hoping there is an obvious solution that I am overlooking. Hopefully someone else has ran into this problem, I didn't find anything using Google.