我正在嘗試撰寫一個函式,該函式將為我的每個集合動態異步創建索引。我遇到的困難是訪問我的每個集合的類實體,然后呼叫物件來創建索引。
我努力了:
- 獲取屬性
- ast.literal_eval
注意:出于安全原因,我無法使用 eval()
我的類實體的外觀示例:
import ast
from models.database_models import IndexedKeyModels
class Mongo: # pylint: disable=too-many-instance-attributes
def __init__(self):
self.connection = self.get_set_connection() # Function to create MongoDB connection
self.db = self.connection.pal_db
self.test1 = self.db.test1
self.test2 = self.db.test2
async def set_indexes(self) -> None:
test_string: str = ""
if self.dev == "True":
test_string = "test_"
for name in IndexedKeyModels():
await ast.literal_eval(
f"self.{test_string}{name[0]}.create_index([('{name[1]}', {ASCENDING})], background=True)"
)
IndexedKeyModels 如下所示:
class IndexedKeyModels(BaseModel):
"""
MongoDB Indexed Key names
"""
test1: str = "Index1"
test2: str = "Index2"
我希望能夠為每個集合動態創建每個索引,而不必為我們擁有的每個集合定義每個 create_index。
uj5u.com熱心網友回復:
如果要在特定集合和欄位上創建索引,可以使用以下構造以編程方式執行此操作:
collectionname = 'coll1'
fieldname = 'field1'
db[collectionname].create_index([(fieldname , pymongo.ASCENDING)])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/508488.html
標籤:python-3.x mongodb 异步 pymongo 获取属性
上一篇:異步通道無法停止
