Does Motorengine mantain an IO stream with mongo db?

萝らか妹 提交于 2019-12-11 12:14:10

问题


I want to use Motorengine for my Tornado application. As given in the docs, this is how I am supposed to make the ODM

from motorengine.document import Document
from motorengine.fields import StringField, DateTimeField

class Article(Document):
    title = StringField(required=True)
    description = StringField(required=True)
    published_date = DateTimeField(auto_now_on_insert=True)

    new_title = "Better Title %s" % uuid4()

def create_article():
    Article.objects.create(
        title="Some Article",
        description="This is an article that really matters.",
        callback=handle_article_created
    )

def handle_article_created(article):
   article.title = new_title
   article.save(callback=handle_article_updated)

def handle_article_updated(article):
    Article.objects.find_all(callback=handle_articles_loaded)

def handle_articles_loaded(articles):
    assert len(articles) == 1
    assert articles[0].title == new_title
    articles[0].delete(callback=handle_article_deleted)

def handle_article_deleted(number_of_deleted_items):
    try:
        assert number_of_deleted_items == 1
    finally:
        io_loop.stop()

io_loop.add_timeout(1, create_article)
io_loop.start()

The confusion is, will this maintain a consistent connection with the database once an instance is created ? I want non-blocking I/O operations with the database for all the models so it's not a problem if it does. But I should not be implementing it for the Users model which I will access only once at the time of verification. Is there a normal way to access Users data ?

Also, I'm unclear about a few things :

  1. What exactly are the last two lines (ioloop) doing here?

  2. I am declaring different models in separate files, do I do a io_loop.start() is each file? This is the part that seems weird to me.

Please help me out. Thanks.


回答1:


Reading MotorEngine's code, it appears to me that each operation you do with MongoDB, like Article.objects.create, checks for a MotorClient instance and reuses one if possible. Here's where the connection is cached and looked up from the cache:

https://github.com/heynemann/motorengine/blob/master/motorengine/connection.py#L62

Each MotorClient maintains a persistent pool of IOStreams, so the answer to your question is yes.

IOLoop.start starts your application server. You should call it once, in one file. The call to start runs forever, or until you kill the process.

The add_timeout call is just a way to demonstrate MotorEngine's functionality, it waits one second then calls create_article. You wouldn't do anything like that in your actual application; you'd likely call create_article directly in a RequestHandler, without add_timeout.



来源:https://stackoverflow.com/questions/30641824/does-motorengine-mantain-an-io-stream-with-mongo-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!