繁体   English   中英

Pymongo,TypeError:预期的字符缓冲区对象

[英]Pymongo, TypeError : expected a character buffer object

我正在尝试连接并读取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%,即使有文档,我也看不到如何解决此问题。

谢谢。

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

dbco = ''

之后,我看到您定义了几个函数,然后在该字符串上调用find()

user_info = dbco.find({})

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

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

dataconnect =  connectToMongoDb()

我又做了一次,改变了一些小东西。 现在,它可以工作了。 这是代码,供将来需要的人使用。

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

client = MongoClient()
connected = ''

# Retrieve connection information from ini file
def dbConfig(section, filename='database.ini'):
    # Keep result in global variable when the function is finished
    global client

    # 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':
        # Variables for the connection
        host = ''
        username = ''
        passwd = ''
        port = ''
        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

        # Make the URI needed for the connection to Mongo DB
        passwing = "mongodb://" + username + ":" + quote_plus(passwd) + "@" + host + ":" + port
        client = MongoClient(passwing)
        return client

# Close MongoDB connection
def closeMongoDbConnection():
    # Try to close the connection to Mongo DB
    try:
        client.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."

# Connection to MongoDB
def connectToMongoDb(mydb):
    db = client.get_database(mydb)
    return db.measure

# Make a query in MongoDB
def mongoDbQuery():
    docs = connected.find().count()
    #for document in docs:
        #print(document)
    print(docs)

if __name__ == '__main__':
    connected = connectToMongoDb('neocampus')
    #docs = connected.find()
    # print(test)
    #for document in docs:
        #print(document)
    mongoDbQuery()

    # Show if the connection to Mongo DB is a success or not
    print(closeMongoDbConnection())

问题是:-关于函数中的全局变量和函数外的信息-数据库变量为空(因此)-首次调用MongoClient()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM