AttributeError:“ str”对象没有属性“ client”

时间:2019-09-02 15:33:13

标签: python mongodb flask

我有一个代码,用于与MongoDB建立连接。这段代码是

ConnectMongoDB.py:

import pymongo
from pymongo import MongoClient
from flask import Flask, render_template, request,redirect,url_for

app = Flask(__name__)

# Connection to MongoDB

class ConnectMdb:
    @staticmethod
    def connect2mongodb():
        global client
        try:
            client = pymongo.MongoClient("mongodb") # modified to avoid showing actual string. Kindly ignore this part.
            print("Connected to Avengers MongoClient Successfully!!!")
            print (type(client))
            print(client)
        except:
            print("Connection to MongoClient Failed!!!")

        #db = client.avengers_hack_db
        return("Connection established")

if __name__ == '__main__':
   ConnectMdb.connect2mongodb()

我将此脚本导入具有业务逻辑的另一个程序中。以下是与此问题相关的部分代码:

ProcessData.py:


import pymongo
from pymongo import MongoClient
import datetime
import sys
from flask import Flask, render_template, request
#import ProcessTaskData
#import werkzeug
import ConnectMongoDB as cDB
app = Flask(__name__)

CMdb = cDB.ConnectMdb.connect2mongodb()

db = CMdb.client.avengers_hack_db

@app.route('/')
def index():
  return render_template('index.html')

@app.route('/Avengers',methods = ['POST'])  
def Avengers():
    ip = request.remote_addr
    Project_ID = request.form['pid'] 
    Name = request.form['pname'] 
    Resource_Names = request.form['rsrc']

    db.ppm_master_db_collection.insert_many([
            {"Org_Id":"",
             "Name": Name,     
             "last_modified": datetime.datetime.utcnow()}
        ]) 
    return render_template('ptasks.html', user_ip=ip)   

@app.route('/ProjectTasks',methods = ['POST'])  
def ProjectTask():
    ip = request.remote_addr
    Task_ID = request.form['tid'] 
    TAlert = request.form['talrt']
    TResource_Names = request.form['trsrc']

    db.ppm_tasks_data_collection.insert_many([
            {"Task_ID": Task_ID,
             "Resource_Names": TResource_Names,
             "last_modified": datetime.datetime.utcnow()}
            ])  
    return render_template('ptasks.html', user_ip=ip)

if __name__ == '__main__':  
   app.run(debug = True)

如果我将ConnectMongoDB.py中的代码直接放入ProcessData.py中而不是导入,则效果很好。但是从单独的文件中会出错。

此外,客户端类型:

 <class 'pymongo.mongo_client.MongoClient'>

理想情况下,就像代码在ProcessData.py中一样,它可以正常运行(也建立与db的连接)。不知道我在哪里。

1 个答案:

答案 0 :(得分:1)

改变 db = CMdb.client.avengers_hack_dbdb = cDB.client.avengers_hack_db 应该使错误消失,您引用的是错误的内容。静态方法的返回值是一个字符串,并且没有客户端属性。


如果您的connect2mongodb方法是return client,则更好的方法是:

class ConnectMdb:
    @staticmethod
    def connect2mongodb():
        try:
            client = pymongo.MongoClient("mongodb") # modified to avoid showing actual string. Kindly ignore this part.
            print("Connected to Avengers MongoClient Successfully!!!")
            print (type(client))
            print(client)
        except:
            raise Exception("Connection to MongoClient Failed!!!")

        return client

这样db = CMdb.client.avengers_hack_db可以工作。