0

在 MongoDB 上,使用 "username" 上的 uniq 索引创建 "security" 集合,我正在使用 motor.motor_asynci 与 Mongo 一起工作。尝试获取与“用户名”相关的文档,如下所示:

from motor.motor_asyncio import AsyncIOMotorClient


def load_config() -> dict:
    with open('config/config.yml') as yaml_file:
        conf = yaml.load(yaml_file.read(), Loader=yaml.SafeLoader)
    return conf


CONF = load_config()


## Mongo
DB_CLIENT = AsyncIOMotorClient(
    host=CONF.get("databases", dict())["mongo"]["HOST"],
    port=CONF.get("databases", dict())["mongo"]["PORT"],
    username=CONF.get("databases", dict())["mongo"]["USER"],
    password=CONF.get("databases", dict())["mongo"]["PASSWORD"],
)


DB = DB_CLIENT[CONF.get("databases", dict())["mongo"]["NAME"]]



cursor_user =  DB.security.find({'username': "someuser"}) 
for doc in  cursor_user:
   print (doc)

得到“TypeError:'AsyncIOMotorCursor'对象不可迭代”

由于这个集合在搜索键上有 uniq 索引,我也尝试了 find_one 但也没有工作:


user =  DB.security.find_one({'username': "someuser"}) 
print(user)


得到:

<Future pending cb=[run_on_executor.<locals>._call_check_cancel() at /usr/local/lib/python3.8/site-packages/motor/frameworks/asyncio/__init__.py:80]>
4

1 回答 1

0

我在我的配置文件中创建了一个函数并将其导入到路由文件中,注意,默认情况下它还会抑制来自 Mongo 的 _id

async def search_user(username: str):
    user = await security_collection.find_one({"username": username} ,{"_id":0})
    return user


从路由:

@security_router.get("/find_username")
async def search_username(username: str):
    user = await search_user(username)
    print("User main",user)
    if user:
        return ResponseModel(
            "User: {} exist ".format(user), "Something"
        )
    return ErrorResponseModel(
        "An error occurred", 404, "User {0} doesn't exist".format(username)
    )

于 2021-03-15T16:34:12.337 回答