gpt4 book ai didi

python - 我需要在 mongodb 中关闭连接吗?

转载 作者:IT老高 更新时间:2023-10-28 13:18:37 35 4
gpt4 key购买 nike

我正在使用 python 和 django 来制作基于 Web 的应用程序。我使用 mongodb 作为后端数据库。我有一个名为 MongoConnection 的基类,它使用 pymongo 层与 mongodb 进行通信。我对这一层非常满意,因为它为我将数据库与业务层分开。我的自定义 MongoConnenction 类如下:-

#!/usr/bin/env python
# encoding: utf-8
# Create your views here.
from pymongo import MongoClient
import pymongo
from pymongo import Connection
import json
from bson import BSON
from bson import json_util


class MongoConnection():
def __init__ (self, host="localhost",port=27017, db_name='indexer', conn_type="local", username='', password=''):
self.host = host
self.port = port
self.conn = Connection(self.host, self.port)
self.db = self.conn[db_name]
self.db.authenticate(username, password)

def ensure_index(self, table_name, index=None):
self.db[table_name].ensure_index([(index,pymongo.GEOSPHERE)])

def create_table(self, table_name, index=None):
self.db[table_name].create_index( [(index, pymongo.DESCENDING)] )


def get_one(self,table_name,conditions={}):
single_doc = self.db[table_name].find_one(conditions)
json_doc = json.dumps(single_doc,default=json_util.default)
json_doc = json_doc.replace("$oid", "id")
json_doc = json_doc.replace("_id", "uid")
return json.loads(json_doc)

def get_all(self,table_name,conditions={}, sort_index ='_id', limit=100):
all_doc = self.db[table_name].find(conditions).sort(sort_index, pymongo.DESCENDING).limit(limit)
json_doc = json.dumps(list(all_doc),default=json_util.default)
json_doc = json_doc.replace("$oid", "id")
json_doc = json_doc.replace("_id", "uid")
return json.loads(str(json_doc))


def insert_one(self, table_name, value):
self.db[table_name].insert(value)

def update_push(self, table_name, where, what):
#print where, what
self.db[table_name].update(where,{"$push":what},upsert=False)

def update(self, table_name, where, what):
#print where, what
self.db[table_name].update(where,{"$set":what},upsert=False)

def update_multi(self, table_name, where, what):
self.db[table_name].update(where,{"$set":what},upsert=False, multi=True)

def update_upsert(self, table_name, where, what):
self.db[table_name].update(where,{"$set":what},upsert=True)


def map_reduce(self, table_name, mapper, reducer, query, result_table_name):
myresult = self.db[table_name].map_reduce(mapper, reducer, result_table_name, query)
return myresult

def map_reduce_search(self, table_name, mapper, reducer,query, sort_by, sort = -1, limit = 20):
if sort_by == "distance":
sort_direction = pymongo.ASCENDING
else:
sort_direction = pymongo.DESCENDING
myresult = self.db[table_name].map_reduce(mapper,reducer,'results', query)
results = self.db['results'].find().sort("value."+sort_by, sort_direction).limit(limit)
json_doc = json.dumps(list(results),default=json_util.default)
json_doc = json_doc.replace("$oid", "id")
json_doc = json_doc.replace("_id", "uid")
return json.loads(str(json_doc))

def aggregrate_all(self,table_name,conditions={}):
all_doc = self.db[table_name].aggregate(conditions)['result']
json_doc = json.dumps(list(all_doc),default=json_util.default)
json_doc = json_doc.replace("$oid", "id")
json_doc = json_doc.replace("_id", "uid")
return json.loads(str(json_doc))

def group(self,table_name,key, condition, initial, reducer):
all_doc = self.db[table_name].group(key=key, condition=condition, initial=initial, reduce=reducer)
json_doc = json.dumps(list(all_doc),default=json_util.default)
json_doc = json_doc.replace("$oid", "id")
json_doc = json_doc.replace("_id", "uid")
return json.loads(str(json_doc))

def get_distinct(self,table_name, distinct_val, query):
all_doc = self.db[table_name].find(query).distinct(distinct_val)
count = len(all_doc)
parameter = {}
parameter['count'] = count
parameter['results'] = all_doc
return parameter

def get_all_vals(self,table_name,conditions={}, sort_index ='_id'):
all_doc = self.db[table_name].find(conditions).sort(sort_index, pymongo.DESCENDING)
json_doc = json.dumps(list(all_doc),default=json_util.default)
json_doc = json_doc.replace("$oid", "id")
json_doc = json_doc.replace("_id", "uid")
return json.loads(json_doc)

def get_paginated_values(self, table_name, conditions ={}, sort_index ='_id', pageNumber = 1):
all_doc = self.db[table_name].find(conditions).sort(sort_index, pymongo.DESCENDING).skip((pageNumber-1)*15).limit(15)
json_doc = json.dumps(list(all_doc),default=json_util.default)
json_doc = json_doc.replace("$oid", "id")
json_doc = json_doc.replace("_id", "uid")
return json.loads(json_doc)

def get_count(self, table_name,conditions={}, sort_index='_id'):
count = self.db[table_name].find(conditions).count()
return count

现在,问题是我的 moongodb 使用了大量的处理能力和 RAM。通常它消耗大约 80-90% 的 CPU。

我怀疑每次创建此类的实例时我都没有关闭 mongoconnection。我需要在 mongodb 中手动关闭连接吗?

最佳答案

Connection 实例无需关闭,Python 垃圾回收时它会自行清理。

你应该使用 MongoClient 而不是 Connection; Connection 已弃用。要利用连接池,您可以创建一个在进程的整个生命周期中持续存在的 MongoClient

PyMongo 将文档表示为 dicts。为什么要将它给您的每个字典编码为 JSON,然后再次解码?直接修改对象可能更有效。

也就是说,我同意 user3683180 的观点,即真正的问题——MongoDB 占用如此多 CPU 的原因——在于您的架构或索引设计,而不是您的 Python 代码。

关于python - 我需要在 mongodb 中关闭连接吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23909975/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com