首页 > 解决方案 > Pymongo,TypeError:期望一个字符缓冲区对象

问题描述

我正在尝试连接并读取 MongoDB 数据库中的数据,以学习 Python。我正在使用 Pymongo,我有这个错误:

Traceback (most recent call last):
File "secondtest.py", line 107, in <module>
user_info = dbco.find({})
TypeError: expected a character buffer object

这是我的 database.ini :

[postgresql]
host=monhostname
database=monpass
port=15000
user=monuser
password=monpass

[mongodb]
hostname=127.0.0.1
database=Mydatabase
username=Myname
password=Myn@me!
collection=measure
port=27017

我的代码使用它:

# -*- coding: utf-8 -*-
# secondtest.py

import psycopg2
import sys
import pymongo
from urllib import quote_plus
from pymongo import MongoClient
from configparser import ConfigParser

# Connection information in database.ini
params = ''
mongollection = ''

# Variables to connect to a database, to use a cursor object and to fetch all results from a query
mongoClient = ''
pgsqlClient = ''
pgsqlCursor = ''
pgsqlRecords = ''
mongoRecords = ''
dbco = ''

# Retrieve connection information from ini file
def dbConfig(section, filename='database.ini'):
    # Create a parser
    parser = ConfigParser()

    # Read config file
    parser.read(filename)

    # Get section, depending on the database engine
    db = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            db[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))

    # Return data or directly as a string
    if section == 'postgresql':
        return db
    elif section == 'mongodb':
        host = ''
        username = ''
        passwd = ''
        port = ''
        dbmongo = ''
        connectstring = ''

        # Make a string to connect to MongoDB
        for key, value in db.iteritems():
            if key == 'hostname':
                host = value.encode("utf-8")
            elif key == 'username':
               username = value
            elif key == 'password':
               passwd = value
            elif key == 'database':
               dbmongo = value
            elif key == 'collection':
               mongollection = value
            elif key == 'port':
               port = value

        connectstring = "mongodb://" + username + ":" + quote_plus(passwd) + "@" + host + ":" + port
        print("Internal test = " + connectstring)
        return connectstring.encode('iso-8859-1')

# Connection to MongoDB
def connectToMongoDb():
    # The f-string is only available in Python >= 3.6
    params = dbConfig('mongodb')
    print("Parameters : " + params)
    mongoClient = MongoClient(params)

    try:
        # print("Connection to database")
        dbco = mongoClient.mongollection
        print("Here")
        print("Test dbco : " + dbco)
        print("Connected to MongoDB !")
        return dbco
    except:
        return "Error : can't connect to MongoDB !"

# Close MongoDB connection
def closeMongoDbConnection():
    # try:
    mongoClient.close()
    return 'Connection closed'
    # except:
        # return "Can't close the connection. See if you already had one or if you didn't mispell its name."

# Make a query in MongoDB
def mongoDbQuery():
    #mongocursor = mongoClient.mongollection.find()
    #for document in cursor:
        #print(document)
    mongoClient.database_names()

if __name__ == '__main__':
    dataconnect =  connectToMongoDb()
    print("Connection\n")
    #mongoDbQuery()
    #collec = mongoClient.measure
    user_info = dbco.find({})
    print(user_info)
    print(closeMongoDbConnection())

你能帮我解决这个问题吗?我认为 quote_plus() 甚至 dbco = mongoClient.mongollection 是导致此错误发生的原因。但我不是 100% 确定,即使有文档,我也看不到如何解决这个问题。

谢谢你。

标签: pythonmongodbpymongo

解决方案


我正在读你的代码。我在程序的开头看到,您创建了dbco指向空字符串的变量:

dbco = ''

在那之后,我看到你定义了几个函数,然后你调用find()那个字符串:

user_info = dbco.find({})

您将{}(empty dict) 作为参数传递给该方法...但是正如您在此处的文档中看到的那样,此方法需要另一个字符串作为第一个参数。这会导致您看到的错误。

现在我不完全确定如何解决它,因为我不知道你的意思。也许您的意思是使用dataconnect变量,因为它是获得connectToMongoDb函数结果的变量:

dataconnect =  connectToMongoDb()

推荐阅读