点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # -*- encoding:utf-8 -*-

  3. from pymongo import Connection
  4. from config import database
  5. import functools


  6. class Mongodb(object):
  7.     '''数据库操作辅助类'''
  8.     def __init__(self):
  9.         self.db = None

  10.     def conn(self):
  11.         if not self.db:
  12.             connection = Connection(database.database['dbhost'])
  13.             self.db = connection[database.database['dbname']]
  14.             # from bottle import
  15.             # connection = Connection(bottle.config['database.dbhost'])
  16.             # self.db = connection[bottle.config['database.dbname']]
  17.         return self.db

  18.     def find_one(self, name):
  19.         def wrapper(callback):
  20.             def wrapper(*args, **kwargs):
  21.                 conn = self.conn()
  22.                 query = args[0]
  23.                 if '_id' in query:
  24.                     from bson.objectid import ObjectId
  25.                     if not isinstance(query['_id'], ObjectId):
  26.                         query['_id'] = ObjectId(query['_id'])
  27.                 return conn[name].find_one(query)
  28.             return wrapper
  29.         return wrapper

  30.     def find(self, name, select=None, dump=False):
  31.         def wrapper(callback):
  32.             def wrapper(*args, **kwargs):
  33.                 conn = self.conn()
  34.                 query = args[0]
  35.                 cursor = conn[name].find(query, select)
  36.                 if 'limit' in kwargs: #limit
  37.                     #print 'limit %s' % kwargs['limit']
  38.                     cursor.limit(int(kwargs['limit']))
  39.                 if 'skip' in kwargs: #skip
  40.                     #print 'skip %s' % kwargs['skip']
  41.                     cursor.skip(int(kwargs['skip']))
  42.                 if 'order' in kwargs:
  43.                     order = kwargs['order']
  44.                     if isinstance(order, dict):
  45.                         for k in kwargs['order']:
  46.                             cursor.sort(k, int(kwargs['order'][k]))
  47.                     elif isinstance(order, tuple):
  48.                       for k, v in p:
  49.                           cursor.sort(k, int(v))
  50.                 return [record for record in cursor] if dump or 'dump' in kwargs and kwargs['dump'] else cursor
  51.             return wrapper
  52.         return wrapper

  53.     def save(self, name):
  54.         def wrapper(callback):
  55.             def wrapper(*args, **kwargs):
  56.                 conn = self.conn()
  57.                 obj = args[0]
  58.                 if not obj:
  59.                     raise ValueError("Not to be save null object")
  60.                 if 'addtime' not in obj:
  61.                     import datetime
  62.                     obj['addtime'] = datetime.datetime.now()
  63.                 if '_id' in obj:
  64.                     from bson.objectid import ObjectId
  65.                     if not isinstance(obj['_id'], ObjectId):
  66.                         obj['_id'] = ObjectId(obj['_id'])
  67.                 return conn[name].save(obj)
  68.             return wrapper
  69.         return wrapper

  70.     def remove(self, name):
  71.         def wrapper(callback):
  72.             def wrapper(*args, **kwargs):
  73.                 conn = self.conn()
  74.                 query = args[0]
  75.                 if not query: return
  76.                 if '_id' in query:
  77.                     from bson.objectid import ObjectId
  78.                     if not isinstance(query['_id'], ObjectId):
  79.                         query['_id'] = ObjectId(query['_id'])
  80.                 return conn[name].remove(query,safe=True)['n']
  81.             return wrapper
  82.         return wrapper

  83. # def make_mongodb_wrapper(name):
  84. # @functools.wraps(getattr(Mongodb, name))
  85. # def wrapper(*a, **ka):
  86. # return getattr(Mongodb(), name)(*a, **ka)
  87. # return wrapper

  88. mongo = Mongodb()

用例


点击(此处)折叠或打开

  1. import mongo as m

  2. entity = {}
  3. entity['name'] = "username"
  4. save(entity)

  5. @m.find(name='userTable')
  6. def find(condition, **kwargs):pass

  7. @m.remove(name='userTable')
  8. def delete(condition,**kwargs):pass

  9. @m.save(name='userTable')
  10. def save(item):pass

  11. @m.find_one(name='userTable')
  12. def find_one(condition):pass


10-28 21:23