我目前正在开发一个 Python Discord 机器人,它使用 Mongo 数据库来存储用户数据。
随着这些数据不断变化,数据库将接受大量查询以提取和更新数据;所以我试图找到减少客户端-服务器通信并减少机器人响应时间的方法。
从这个意义上说,在脚本运行后立即创建一个 Mongo 集合的副本作为字典列表,并离线操作数据而不是不断查询数据库是个好主意吗?
特别是,每次使用 collection.find() 方法搜索数据时,都会从列表中提取数据。另一方面,每次需要使用 collection.update() 更新数据时,都会更新列表和数据库。
我将举一个例子来更好地解释我正在尝试做什么。假设我的集合包含具有以下结构的文档:
{"user_id": id_of_the_user, "experience": current_amount_of_experience}
Run Code Online (Sandbox Code Playgroud)
并且经验值必须不断增加。
这是我目前实施它的方式:
online_collection = db["collection_name"] # mongodb cursor
offline_collection = list(online_collection.find()) # a copy of the collection
def updateExperience(user_id):
online_collection.update_one({"user_id":user_id}, {"$inc":{"experience":1}})
mydocument = next((document for document in offline_documents if document["user_id"] == user_id))
mydocument["experience"] += 1
def findExperience(user_id):
mydocument = next((document for document in offline_documents if document["user_id"] == user_id))
return mydocument["experience"]
Run Code Online (Sandbox Code Playgroud)
如您所见,数据库仅涉及更新功能。
这是一种有效的方法吗?对于非常大的集合(数百万个文档),next () 函数是否具有相同的执行时间,或者仍然会有一些减速?
此外,虽然在问题中没有明确提出,但我很乐意就如何提高 Discord 机器人的性能获得任何建议,只要它不包括使用 VPS 或分片,因为我是已经在使用这些选项。
SyntaxError在列表或生成器理解中使用时,带星号的表达式会引发。
我很好奇这背后的原因;它是一种实现选择还是存在阻止此操作的技术限制?
我发现了很多关于不允许解包迭代的上下文,但没有说明原因。
例子:
lis = [1, 2, 3, 4, 5]
listcomp = [*lis for i in range(3)]
Run Code Online (Sandbox Code Playgroud)
我想也许我可以用它来获得[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]结果,但它提高了
SyntaxError("Iterable unpacking 不能用于理解中")
假设我想实现我的自定义list类,并且我想重写__getitem__以便item可以使用 default 初始化参数None,并做出相应的行为:
class CustomList(list):
def __init__(self, iterable, default_index):
self.default_index = default_index
super().__init__(iterable)
def __getitem__(self, item=None):
if item is None:
item = self._default_index
return super().__getitem__(item)
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
my_list = CustomList(iterable, 2)
Run Code Online (Sandbox Code Playgroud)
这允许my_list[None],但如果能有像my_list[]固有地使用默认参数这样的东西那就太棒了。
不幸的是,这引发了SyntaxError,所以我假设该语句在语法级别上是非法的......我的问题是:为什么?它会与其他一些说法相冲突吗?
我对此很好奇,非常感谢愿意解释的人!