python连接mongo

import pymongo

class MongoUtils:
    def __init__(self, host, port):
        self.client =  pymongo.MongoClient(host, port)

    # 连接数据库
    def get_db(self, db_name, user=None, pwd=None):
        db = self.client[db_name]
        if user:
            db.authenticate(user, pwd,mechanism='SCRAM-SHA-1')
        return db

    def close(self):
        return self.client.close()

  

 

from util.mongo_utils import MongoUtils

class Prosesser:
    def __init__(self):
        self.mongo = MongoUtils(host, port)
        self.db_news = self.mongo.get_db(db_name, user, pwd)

    def run(self, message):
msg_dict = json.loads(message)
record = self.db_news['newsContent'].find_one({'_id': msg_dict['_id']})
if record:
print('记录已存在')
return
else:
print('插入新记录')
self.db_news['newsContent'].insert_one(msg_dict)



if __name__ == '__main__':
Processor().run({"_id": "XXX", "message": "hello", "title": "你好!!!"})

  

posted @ 2022-04-18 16:13  亿逍遥  阅读(362)  评论(0编辑  收藏  举报