标签: tornado-motor

如何隐藏聚合中的_id?

我有这个问题:

produits = yield motor.Op(db.users.aggregate, [{"$unwind":"$pup"},{"$match":{"pup.spec.np":nomp}}, {"$group":{"_id":"$pup.spec.id","pup":{"$push":"$pup"}}}])
Run Code Online (Sandbox Code Playgroud)

结果给了我这个:

print produits

{u'ok': 1.0, u'result': [{u'_id': None, u'pup': [{u'avt': {u'fto': ..all the results}}]}]}
Run Code Online (Sandbox Code Playgroud)

所以我能做到:

prod = produits["result"]

[{u'_id': None, u'pup': [{u'avt': {u'fto': ..all the results}}]}]
Run Code Online (Sandbox Code Playgroud)

但我怎么隐藏"_id"所以我只能得到

[{u'pup': [{u'avt': {u'fto': ..all the results}}]}]
Run Code Online (Sandbox Code Playgroud)

在正常的查询中,我只是添加类似{"_id":0}这里的东西它不起作用.

mongodb motordriver pymongo tornado-motor

22
推荐指数
2
解决办法
2万
查看次数

如果文档存在,MongoDB返回True

如果userID已经存在,我想返回true,否则从我的集合返回false.我有这个函数,但它总是返回True.

def alreadyExists(newID):
    if db.mycollection.find({'UserIDS': { "$in": newID}}):
        return True
    else:
        return False
Run Code Online (Sandbox Code Playgroud)

如果用户ID已经存在,我怎么能让这个函数只返回true?

python mongodb pymongo tornado-motor

17
推荐指数
2
解决办法
3万
查看次数

带有 FastAPI 的 MongoDb

我正在使用FastAPI并希望将其连接到 MongoDB 数据库。然而,我很困惑在异步电机和 mongoengine 之间选择哪个 ODM。此外,在此处的 NoSQL 示例中他们创建了一个新存储桶,并在每次使用时调用了连接到 db 的代码。但是,motor 和 mongoengine 似乎都更喜欢全局连接。那么什么是连接到 mongodb 的好方法呢?

mongodb mongoengine tornado-motor motorengine fastapi

12
推荐指数
2
解决办法
1万
查看次数

运行时错误:任务附加到不同的循环

嗨,我正在使用 AsyncIOMotorClient 对 mongoDb 进行异步数据库调用。下面是我的代码。

xyz.py
async def insertMany(self,collection_name,documents_to_insert):
    try:
        collection=self.database[collection_name]
        document_inserted = await collection.insert_many(documents_to_insert)
        return document_inserted
    except Exception:
        raise

def insertManyFn(self,collection_name,documents_to_insert):
    try:
        loop=asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop1=asyncio.get_event_loop()
        inserted_documents_count = loop1.run_until_complete(self.insertMany(collection_name, documents_to_insert))
        if inserted_documents_count==len(documents_to_insert):
            document_to_insert={Config.DB_JOB_COLUMN:Job.job_id,Config.DB_JOB_RESULT_COLUMN:Config.DB_JOB_RESULT_SUCCESS}
            loop1.run_until_complete(self.insertOne(Config.DB_JOB_COLLECTION, document_to_insert))
    except Exception:
        raise

xyz1.py
t=Timer(10,xyz.insertManyFn,\
                (collection_name,documents_to_insert))
t.start()   
Run Code Online (Sandbox Code Playgroud)

运行此程序时出现异常

RuntimeError: Task <Task pending coro=<xyz.insertMany() running at <my workspace location>/xyz.py:144> cb=[_run_until_complete_cb() at /usr/lib64/python3.5/asyncio/base_events.py:164]> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/lib64/python3.5/asyncio/futures.py:431]> attached to a different loop
Run Code Online (Sandbox Code Playgroud)

在上面的程序中,insertManyFn 将在 10 秒后被调用并进行插入操作。但是当它第一次调用 insertMany 时,我得到了一个异常。

mongodb python-asyncio tornado-motor

6
推荐指数
2
解决办法
1万
查看次数

如何在其他函数中移动db请求(使用yield)?

我正在玩龙卷风和mongodb,使用异步驱动电机.使用回调时一切都很好.然后我发现有可能使用motor.Op或tornado.gen.Task来仅在一个函数中执行请求:

这是有效的:

class Contact_handler(Main_handler):

    @web.asynchronous
    @gen.coroutine
    def get(self, other_id):

        event = events.Event_send_contact_request(self.user_id)
        result = yield motor.Op(db.users.update,
                     {'_id': ObjectId(other_id)},
                     {'$push': {'evts': event.data}}
                    )

        self.finish("ok")
Run Code Online (Sandbox Code Playgroud)

但我想将此数据库请求在其自己的函数中移动到另一个模块中.问题是我真的不明白产量在这里是如何工作的(尽管我读了很多关于产量的问题).所以这就是我尝试过的,但它不起作用:

#------ file views.py -------------

class Contact_handler(Main_handler):

    def get(self, other_id):

        event = events.Event_send_contact_request(self.user_id)
        result = model.push_event_to_user(other_id, event)

        self.finish("ok")
Run Code Online (Sandbox Code Playgroud)

而另一个函数的调用:

#------ file model.py -------------

@gen.coroutine
def push_event_to_user(user_id, event):

    ## Ajout de la demande dans les events du demandé:
    yield motor.Op(db.users.update,
                     {'_id': ObjectId(user_id)},
                     {'$push': {'evts': event}}
                    )
Run Code Online (Sandbox Code Playgroud)

如果我用pdb调查:

(Pdb) l
157             event = events.Event_send_contact_request(self.user_id)
158             result = model.push_event_to_user(other_id, event) …
Run Code Online (Sandbox Code Playgroud)

python tornado mongodb tornado-motor

5
推荐指数
1
解决办法
1762
查看次数

龙卷风协程功能中的变量会发生什么?

我对非阻塞IO的概念不熟悉,并且有一些我无法理解的问题 - 关于协同程序.考虑这段代码:

class UserPostHandler(RequestHandler):
    @gen.coroutine
    def get(self):
        var = 'some variable'
        data = json.loads(self.request.body)
        yield motor_db.users.insert({self.request.remote_ip: data})#asynch non blocking db insert call
        #success
        self.set_status(201)
        print var
Run Code Online (Sandbox Code Playgroud)

get调用函数时,它会创建字符串var.当函数等待motor.insert完成时,该变量会发生什么?据我所知,"非阻塞"意味着没有线程在等待IO调用完成,并且在等待时没有使用内存.那么var存储的价值在哪里?执行恢复时如何访问?

任何帮助,将不胜感激!

python tornado coroutine python-3.x tornado-motor

3
推荐指数
1
解决办法
403
查看次数

龙卷风电机中如何通过ObjectId查询

我正在尝试使用龙卷风,我的用例是通过对象 ID 进行查询。

我已经看到示例和 ref 可以通过任何其他方式进行查询,但 ObjectID 除外。因为它是独一无二的,所以我想用它来代替查询。

关于如何使用 ObjectId 进行电机查询的任何建议

python mongodb objectid tornado-motor

3
推荐指数
1
解决办法
1764
查看次数

Mongodb Motor推荐驱动Windows

有关电机的问题https://github.com/mongodb/motor

README说:“ Unix,包括Mac OSX。不支持Windows。”

我在Windows上使用motor 1.0运行python 3.5,看来效果很好。

插入,更新,删除,查找,重新索引操作,加盖的集合和可结尾的游标可以与配合使用asyncio

Windows不支持什么?

python mongodb pymongo tornado-motor

3
推荐指数
1
解决办法
200
查看次数

电机:运行时错误:将对象编码为 BSON 时超出了最大递归深度

我有一个基于异步 Tornado 和 mongoDB 的 API。它工作正常,除了一个处理程序:

@gen.coroutine
def get(self, *args, **kwargs):
    """
    Gets tracking lib
    """
    data = self._get_request_data()
    self._serialize_request_data(AuthValidator, data)

    tags = yield self.motor.tags.find_one({"client_id": data["client_id"]})
    raise Return(self.write(tags))
Run Code Online (Sandbox Code Playgroud)

当请求到来时,tornado 返回带有以下堆栈跟踪的 HTTP 500:

response: Traceback (most recent call last):
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/web.py", line 1334, in _execute
result = yield result
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/gen.py", line 617, in run
value = future.result()
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/concurrent.py", line 109, in result
raise_exc_info(self._exc_info)
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/gen.py", line 620, in run
yielded = self.gen.throw(*sys.exc_info())
  File "/Users/artemkorhov/Projects/cartreminder/cartreminder_app/tracking_api/api_handlers/endpoints.py", line 35, in get
tags …
Run Code Online (Sandbox Code Playgroud)

tornado mongodb pymongo python-2.7 tornado-motor

1
推荐指数
1
解决办法
1922
查看次数

使用find()Motor [MongoDB + Tornado]时出现BadYieldError

我是python龙卷风框架的新手.我在MongoDB中有一小部分数据.我在我的python文件中使用了一个简单的get函数.我BadYieldError在使用该db.collection.find()选项时得到了一个.但db.collection.find_one()工作正常但它只显示一条记录.

import tornado
import bson
from bson import json_util
from bson.json_util import dumps
class TypeList(APIHandler):
@gen.coroutine
def get(self):
    doc = yield db.vtype.find()
    self.write(json_util.dumps(doc))
Run Code Online (Sandbox Code Playgroud)

错误是:

tornado.gen.BadYieldError:产生未知对象MotorCursor()

python json mongodb tornado-motor

1
推荐指数
1
解决办法
1255
查看次数

对象 MotorLatentCommandCursor 不能在“await”表达式中使用

在Tornado中使用motor连接mongodb

我创建了一个电机连接

import motor.motor_tornado
from tornado.web import RequestHandler
client = motor.motor_tornado.MotorClient('mongodb://xxx')

class BaseHandler(RequestHandler):
    @property
    def db(self):
        return client['realtime-test']

class Account(BaseHandler):
    async def get(self,*args,**kwargs):
        all_user = await self.db.account.aggregate([
            {'$match': {'status': 1}},
            {'$group': {'_id':''}}
        ])
        print(all_user)
Run Code Online (Sandbox Code Playgroud)

当我开始时,我收到此消息:“对象 MotorLatentCommandCursor 不能在 'await' 表达式中使用”

不知道为什么~好像没什么问题

python tornado mongodb tornado-motor

0
推荐指数
1
解决办法
4387
查看次数