Ошибка операции: поиск команды требует аутентификации

#python #pandas #mongodb #jupyter #pymongo

#python #pandas #mongodb #jupyter #pymongo

Вопрос:

Я очень новичок в pymongo, а также в jupyter notebook. Проблема, с которой я сталкиваюсь в настоящее время, заключается в том, что я получаю сообщение об ошибке, которое отображается ниже, и я не могу понять, почему, поскольку я подключен к jupyter notebook через mongo под правильными учетными данными.

Вот мой код файла .py:

 import pymongo
from pymongo import MongoClient
from bson.objectid import ObjectId

class AnimalShelter(object):
    """CRUD operations for Animal collection in Mongodatabase"""
    #Initializes MongoClient
    def __init__(self, username, password):
        self.client = MongoClient('mongodb://127.0.0.1:38574'.format(username, password))
        self.database = self.client['AAC']  
    #Implement create method
    def create(self, data):
        if data is not None:
            return self.database.animals.insert_one(data)
        else:
            raise Exception("Nothing to save, because data parameter is empty")
    #Implement read method
    def read(self, data):
        if data is not None:
            return self.database.animals.find(data)
        else:
            raise Exception("Nothing to read, because data parameter is empty")
    #Implement update method
    def update(self, data):
        if find is not None:
            return self.database.animals.update_one(data)
        else:
            raise Exception("Nothing to update, because data parameter is empty")
    #Implement delete method
    def delete(self, data):
        if data is not None:
            return self.database.animals.delete_one(data)
        else:
            raise Exception("Nothing to delete, because data parameter is empty")
 

Вот мой код:

 from jupyter_plotly_dash import JupyterDash
import dash
import dash_leaflet as dl
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import dash_table
from dash.dependencies import Input, Output
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pymongo import MongoClient
#### FIX ME #####
# change animal_shelter and AnimalShelter to match your CRUD Python module file name and class name
from AAC import AnimalShelter

###########################
# Data Manipulation / Model
###########################
# FIX ME update with your username and password and CRUD Python module name
username = "aacuser"
password = "monogoadmin"
shelter = AnimalShelter(username, password)
# class read method must support return of cursor object and accept projection json input
df = pd.DataFrame.from_records(shelter.read({}))

print (df)

#########################
# Dashboard Layout / View
#########################
app = JupyterDash('Milestone 6')

app.layout = html.Div([
    html.Div(id='hidden-div', style={'display':'none'}),
    html.Center(html.B(html.H1('SNHU CS-340 Dashboard'))),
    html.Hr(),
    dash_table.DataTable(
        id='datatable-id',
        columns=[
            {"name": i, "id": i, "deletable": False, "selectable": True} for i in df.columns
        ],
        data=df.to_dict('records'),
        #FIXME: Set up the features for your interactive data table to make it user-friendly for your client
        editable=False,
        filter_action="native",
        sort_mode="multi",
        column_selectable=False,
        row_selectable=False,
        row_deletable=False,
        selected_columns=[],
        selected_rows=[],
        page_action="native",
        page_current= 0,
        page_size= 10,
    ),
    html.Br(),
     html.Hr(),
     html.Div(
            id='map-id',
            className='col s12 m6',
            )
])

#############################################
# Interaction Between Components / Controller
#############################################
#This callback will highlight a row on the data table when the user selects it
@app.callback(
    Output('datatable-id', 'style_data_conditional'),
    [Input('datatable-id', 'selected_columns')]
)
def update_styles(selected_columns):
    return [{
        'if': { 'column_id': i },
        'background_color': '#D2F3FF'
    } for i in selected_columns]


@app.callback(
    Output('map-id', "children"),
    [Input('datatable-id', "derived_viewport_data")])
def update_map(viewData):
#FIXME Add in the code for your geolocation chart
    dff = pd.DataFrame.from_dict(viewData)
    # Austin TX is at [30.75,-97.48]
    return [
        dl.Map(style={'width': '1000px', 'height': '500px'}, center=[30.75,-97.48], zoom=10, children=[
            dl.TileLayer(id="base-layer-id"),
            # Marker with tool tip and popup
            dl.Marker(position=[30.75,-97.48], children=[
                dl.Tooltip(dff.iloc[0,4]),
                dl.Popup([
                     html.H1("Animal Name"),
                     html.P(dff.iloc[1,9])
                ])
            ])
        ])
    ]
app
 

Это сообщение об ошибке:

 ---------------------------------------------------------------------------
OperationFailure                          Traceback (most recent call last)
<ipython-input-3-fdaad3d4f048> in <module>
     23 shelter = AnimalShelter(username, password)
     24 # class read method must support return of cursor object and accept projection json input
---> 25 df = pd.DataFrame.from_records(shelter.read({}))
     26 
     27 print (df)

/usr/local/anaconda/lib/python3.6/site-packages/pandas/core/frame.py in from_records(cls, data, index, exclude, columns, coerce_float, nrows)
   1556 
   1557             try:
-> 1558                 first_row = next(data)
   1559             except StopIteration:
   1560                 return cls(index=index, columns=columns)

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/cursor.py in next(self)
   1154         if self.__empty:
   1155             raise StopIteration
-> 1156         if len(self.__data) or self._refresh():
   1157             if self.__manipulate:
   1158                 _db = self.__collection.database

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/cursor.py in _refresh(self)
   1071                                   self.__session,
   1072                                   self.__collection.database.client)
-> 1073             self.__send_message(q)
   1074         elif self.__id:  # Get More
   1075             if self.__limit:

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/cursor.py in __send_message(self, operation)
    953             response = client._run_operation_with_response(
    954                 operation, self._unpack_response, exhaust=self.__exhaust,
--> 955                 address=self.__address)
    956         except OperationFailure:
    957             self.__killed = True

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/mongo_client.py in _run_operation_with_response(self, operation, unpack_res, exhaust, address)
   1344             address=address,
   1345             retryable=isinstance(operation, message._Query),
-> 1346             exhaust=exhaust)
   1347 
   1348     def _retry_with_session(self, retryable, func, session, bulk):

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/mongo_client.py in _retryable_read(self, func, read_pref, session, address, retryable, exhaust)
   1462                         # not support retryable reads, raise the last error.
   1463                         raise last_error
-> 1464                     return func(session, server, sock_info, slave_ok)
   1465             except ServerSelectionTimeoutError:
   1466                 if retrying:

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/mongo_client.py in _cmd(session, server, sock_info, slave_ok)
   1338                 self._event_listeners,
   1339                 exhaust,
-> 1340                 unpack_res)
   1341 
   1342         return self._retryable_read(

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/server.py in run_operation_with_response(self, sock_info, operation, set_slave_okay, listeners, exhaust, unpack_res)
    134                 operation.client._process_response(
    135                     first, operation.session)
--> 136                 _check_command_response(first)
    137         except Exception as exc:
    138             if publish:

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/helpers.py in _check_command_response(response, msg, allowable_errors, parse_write_concern_error)
    157 
    158             msg = msg or "%s"
--> 159             raise OperationFailure(msg % errmsg, code, response)
    160 
    161 

OperationFailure: command find requires authentication
 

Это учетные данные, которые я использовал для входа в систему, и, как вы можете видеть, он прошел успешно.:

 (base) britteny.itte_snhu@msnv-snhu3-l001:~$ mongo --authenticationDatabase "AAC" -u "aacuser" -p
MongoDB shell version v4.2.6
Enter password: 
connecting to: mongodb://127.0.0.1:38574/?authSource=AACamp;compressors=disabledamp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("a6130001-0c42-4974-80d8-ef12957f6df9") }
MongoDB server version: 4.2.6
 

И, наконец, это разрешения для пользователя, которого я использую…хотя я не уверен, имеет ли значение эта или предыдущая информация, поскольку, похоже, она просто не выполняет операцию…

 > use AAC
switched to db AAC
> db.getUsers()
[
    {
        "_id" : "AAC.aacuser",
        "userId" : UUID("ed423a79-d9d6-46a7-a4bb-beb0eaf2db73"),
        "user" : "aacuser",
        "db" : "AAC",
        "roles" : [
            {
                "role" : "read",
                "db" : "AAC"
            }
        ],
        "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
        ]
    }
]
 

Любая помощь будет с благодарностью принята, поскольку я борюсь!

Ответ №1:

Я думаю, что вы передаете неправильные аргументы MongoClient:

 client = MongoClient('example.com',
                     username='user',
                     password='password',
                     authSource='the_database',
                     authMechanism='SCRAM-SHA-1')
 

Или через URI:

 uri = "mongodb://user:password@example.com/?authSource=the_databaseamp;authMechanism=SCRAM-SHA-1"
client = MongoClient(uri)
 

https://pymongo.readthedocs.io/en/stable/examples/authentication.html#scram-sha-1-rfc-5802