码迷,mamicode.com
首页 > 其他好文 > 详细

motor的使用

时间:2018-11-18 23:43:18      阅读:375      评论:0      收藏:0      [点我收藏+]

标签:asyncio   self   err   col   god   main   code   __name__   eve   

# -*- coding: utf-8 -*-
# @Time : 2018/11/18 10:41 PM
# @Author : cxa
# @File : motordb.py
# @Software: PyCharm
import asyncio

try:
    import uvloop

    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
    pass

from motor.motor_asyncio import AsyncIOMotorClient


class MotorBase:
    _db = {}
    _collection = {}

    def __init__(self, loop=None):
        self.motor_uri = ‘‘
        self.loop = loop or asyncio.get_event_loop()

    def client(self, db):
        self.motor_uri = f"mongodb://localhost:27017/{db}"
        return AsyncIOMotorClient(self.motor_uri, io_loop=self.loop)

    def get_db(self, db=‘test‘):
        if db not in self._db:
            self._db[db] = self.client(db)[db]

        return self._db[db]


async def savedata():
    mb = MotorBase().get_db(‘test‘)
    await mb.news.insert_one({‘name‘: "lisa"})


if __name__ == ‘__main__‘:
    loop = asyncio.get_event_loop()
    loop.run_until_complete(savedata())

motor的使用

标签:asyncio   self   err   col   god   main   code   __name__   eve   

原文地址:https://www.cnblogs.com/c-x-a/p/9980364.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!