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

用户名已存在 发布于 2012/06/21 15:35
阅读 1K+
收藏 2

# 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中方法使用的查询参数以及查询的库都一致,一个能够查询到结果,一个却不能

求解或。

以下是问题补充:

@用户名已存在:mongod : V2.0.6 pymongo: V2.2 (2012/06/21 16:52)
加载中
0
用户名已存在
用户名已存在
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 操作方法了。 反省
返回顶部
顶部