mongodb 使用问题,封装了一下查询无结果(快抓狂了)

发布于 2021-11-15 10:45:53 字数 4315 浏览 767 评论 1

# pymongo 封装如下,利用module特性实现单例模式。

import logging

import functools

import pymongo

# custom module
import settings
from tornado.web import HTTPError

def _check_collection(method):
    ''' Decorate mehtod to validate collection arguments '''
    @functools.wraps(method)
    def wrapped(self, collection, **kwargs):
        if collection not in self.COLLECTIONS:
            # logger.error('%s not in permit collections tuple', table)
            raise HTTPError(500, 'Internal server error') 
    return wrapped

LOGIN = 'login'
REGISTER = 'register'
DEVICE = 'device'

class Database(pymongo.Connection):
    ''' 
        Inherit from pymongo.Connection
    '''
    COLLECTIONS = (REGISTER, LOGIN, DEVICE)
    def __init__(self, db_name='cloud', **kwargs):
        '''
        '''
        super(Database, self).__init__(**kwargs)
        self.db = getattr(self, db_name)

    def __del__(self):
        '''
            Disconnect the current link to database
        '''
        self.close()

    def drop_collection(self, collection):
        '''
           Drop a collection. 
        '''
        self.db.drop_collection(collection)
    
    @_check_collection
    def find_one(self, collection, **kwargs):
        '''
            This method returns a single document matching a query(or None
            if there are no mathches).
        '''
        coll = getattr(self.db, collection)
        return coll.find_one(**kwargs)

    @_check_collection
    def find(self, collection, **kwargs):
        ''' 
            This method a Cursor instance, which allow us iterate over all
            matching document.
        '''
        coll = getattr(self.db, collection)
        return coll.find(**kwargs)


    @_check_collection
    def find_and_modify(self, collection, **kwargs):
        '''
            This method directly call atomic findAndModify interface.
            Passed in kwargs Arguments should reference mongodb's
            'findAndModify' method.
        '''
        coll = getattr(self.db, collection)
        coll.find_and_modify(**kwargs)

    @_check_collection
    def update(self, collection, **kwargs):
        '''
            Find special document and then modify it
        '''
        coll = getattr(self.db, collection)
        coll.update(**kwargs)

    @_check_collection
    def remove(self, collection, **kwargs):
        '''
            Remove matching document form the collection.
            To ensure remove document safely, add {$atomic:True} 
            argument to kwargs
        '''        
        coll = getattr(self.db, collection)
        kwargs.update({'$atomic':True})
        coll.remove(**kwargs)

    @_check_collection
    def insert(self, collection, doc_or_docs, **kwargs):
        '''
            Add new document to collection.
            check_keys argument should True(Default), to make sure
            the key doesn't start with '$' or contain '.'.
        '''
        coll = getattr(self.db, collection)
        coll.insert(doc_or_docs, **kwargs)

import sys

#db_config = settings['database_config']
#cloud = db_config.pop('db_name')
db = Database(cloud, host='mongodb://user:password@localhost:27017/db_name')
sys.modules[__name__] = db

下面是测试代码

>>> import db
>>> db
Connection('localhost', 27017)
>>> db.db
Database(Connection('localhost', 27017), u'cloud')

>>> db.find_one('register', spec_or_id={'_id':'test@domain.com'})
('Find parameter,', Collection(Database(Connection('localhost', 27017), u'cloud'), u'register'), ({'_id': 'test@domain.com'},), {'slave_okay': False, 'read_preference': 0}) #我在collection.py
# find_one方法加了一行调试信息,使用我封装的方法无结果返回。
>>> db.db.register.find_one(spec_or_id={'_id':'test@domain.com'})
('Find parameter,', Collection(Database(Connection('localhost', 27017), u'cloud'), u'register'), ({'_id': 'test@domain.com'},), {'slave_okay': False, 'read_preference': 0})
SON([(u'_id', u'test@domain.com')])
# 同样是使用db module,这样就可以,说实话看不出两种方式调用用啥区别,这里请教
# 各位了,百思不得其解啊

上面2中方法使用的查询参数以及查询的库都一致,一个能够查询到结果,一个却不能

求解或。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦中楼上月下 2021-11-17 10:52:48
def _check_collection(method):
    ''' Decorate mehtod to validate collection arguments '''
    @functools.wraps(method)
    def wrapped(self, collection, **kwargs):
        if collection not in self.COLLECTIONS:
            # logger.error('%s not in permit collections tuple', table)
           raise HTTPError(500, 'Internal server error')
        return method(self, collection, **kwargs)
    return wrapped

装饰器忘记调用 db 操作方法了。 反省

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文