[英]Python - getting document from MongoDB [motor_asyncio]
on MongoDB, create "security" collection with a uniq index on "username", I'm using motor.motor_asynci for working with Mongo.在 MongoDB 上,使用“用户名”上的 uniq 索引创建“安全”集合,我正在使用 motor.motor_asynci 与 Mongo 一起工作。 trying to fetch document related to "username" as following:
尝试获取与“用户名”相关的文档,如下所示:
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)
getting "TypeError: 'AsyncIOMotorCursor' object is not iterable"得到“TypeError:'AsyncIOMotorCursor'object 不可迭代”
as this collection has uniq index on the search key, i also tried find_one but also not working:由于这个集合在搜索键上有 uniq 索引,我也尝试了 find_one 但也没有工作:
user = DB.security.find_one({'username': "someuser"})
print(user)
getting:得到:
<Future pending cb=[run_on_executor.<locals>._call_check_cancel() at /usr/local/lib/python3.8/site-packages/motor/frameworks/asyncio/__init__.py:80]>
I create a function in my config file and import it to routes file, Note, it also suppress _id coming from Mongo by default我在我的配置文件中创建了一个 function 并将其导入到路由文件中,注意,它还默认禁止来自 Mongo 的 _id
async def search_user(username: str):
user = await security_collection.find_one({"username": username} ,{"_id":0})
return user
from routing:从路由:
@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)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.