python androidhelper模块_Python mongoHelper模块

#!/usr/bin/env python3#-*- coding: utf-8 -*-

'''Defines a MongoOperator class and allows you to manipulate

the Mongodb Database.(insert, delete, update, select...)'''

from pymongo importMongoClient, errorsclassMongoOperator(object):'''MongoOperator class allows you to manipulate the Mongodb

Database.

:Usage:'''

def __init__(self, **login):'''The constructor of Mongodb class.

Creates an instance of MongoOperator and starts connecting

to the Mongodb server's test database.

:Args:

- **login - Keyword arguments used in MongoClient() and

Database.authenticate() functions in order to connect to

test database and authenticate clients (including host,

user, password...)'''

#connectin to test database:

self.__db = MongoClient(login['host'], login['port'])[login['database']]

self.__db.authenticate(login['user'], login['password'])def insertOne(self, document, *, collection='test'):'''Insert one document into collection named test in Mongodb

database.

:Args:

- document - dict. One document to execute insertion.

- colletion - str. Named keyword argument used to specify

which collection to insert.'''

#select a collection to execute insert operation:

test = self.__db[collection]#insert transaction begin:

try:

result=test.insert_one(document)print('>> MongoDB insertOne operation success.')print('>> Inserted ID:',result.inserted_id)excepterrors.PyMongoError as e:print('>> MongoDB insertOne operation fail:', type(e), e.details)#add exception logging function later:

def insertMany(self, *documents, collection='test'):'''Insert many document into collection named test in Mongodb

database.

:Args:

- *documents - list of document in variable arguments. Many

documents(require more than one) to execute insertion.

- colletion - str. Named keyword argument used to specify

which collection to insert.'''

#params check:

if len(documents) <=0:raise ValueError("Documents can't be empty.")elif len(documents) <= 1:raise TypeError("MongoDB insertMany Operation need more then one record.")#select a collection to execute insert operation:

test = self.__db[collection]#insert transaction begin:

try:

results=test.insert_many(documents)print('>> MongoDB insertMany operation success.')print('>> Inserted IDs:', results.inserted_ids)excepterrors.PyMongoError as e:print('>> MongoDB insertMany operation fail:', type(e), e.details)#add exception logging function later:

def delete(self, filter, *, collection='test', many=False):'''Delete a single or many documents matching the filter

from collection test in Mongodb database.

:Args:

- filter - A query that matches the document to delete.

- many - bool. Named keyword argument. If True, execute

delete_many(); If not, then execute delete_one().

- colletion - str. Named keyword argument used to specify

which collection to delete.'''

#select a collection to execute delete operation:

test = self.__db[collection]#delete transaction begin:

try:

results= test.delete_many(filter) if many elsetest.delete_one(filter)#waiting for test:

print('>> MongoDB delete operation success.')print('>> Delete Information:', results.raw_result)print('>> Delete document count:', results.deleted_count)excepterrors.PyMongoError as e:print('>> MongoDB delete operation fail:', type(e), e)#add exception logging function later:

def select(self, filter=None, *, collection='test', many=False):'''Select a single or many documents matching the filter

from collection test in Mongodb database.

:Args:

- filter - A query that matches the document to select.

- many - bool. Named keyword argument. If True, execute

find(); If not, then execute find_one().

- colletion - str. Named keyword argument used to specify

which collection to select.

:Returns:

- results - If select success, returns a Cursor instance for

navigating select results. If not, returns None.'''

#selcet a collection to execute select operation:

test = self.__db[collection]#select transaction begin:

try:

results= test.find(filter, no_cursor_timeout=True) if many elsetest.find_one(filter)#waiting for test:

print('>> MongoDB select operation success.', type(results))excepterrors.PyMongoError as e:print('>> MongoDB select operation fail:', type(e), e)

results=None#add exception logging function later:

finally:returnresultsdef update(self, filter, update, *, collection='test', many=False):'''Update a single or many documents matching the filter

from collection test in Mongodb database.

:Args:

- filter - A query that matches the document to update.

- update - The modifications to apply.

- many - bool. Named keyword argument. If True, execute

update_many(); If not, then execute update_one().

- colletion - str. Named keyword argument used to specify

which collection to update.'''

#select a collection to execute update operation:

test = self.__db[collection]#update transaction begin:

try:

results= test.update_many(filter, update) if many elsetest.update_one(filter, update)#waiting for test:

print('>> MongoDB update operation success:', type(results), results)print('>> Update Information:', results.raw_result)print('>> Matching Counts:', results.matched_count)print('>> Modified Counts:', results.modified_count)excepterrors.PyMongoError as e:print('>> MongoDB update operation fail:', type(e), e)#add exception logging function later:

#test:

if __name__ == '__main__':

logIn= {'host': 'localhost', 'port': 27017, 'database': 'test','user': '', 'password': ''}

documents= [{'id': 1, 'name': 'zty'}, {'id': 2, 'name': 'zzz'}, {'id': 3, 'name': 'ttt'}]

document= {'id': 1, 'name': 'zty'}

mongoHandler= MongoOperator(**logIn)for document in mongoHandler.select({'name': 'zty'}, many=True):print(document)

mongoHandler.insertOne(document)print(mongoHandler.select({'name': 'zty'}))

mongoHandler.insertMany(*documents)for document in mongoHandler.select({'name': 'zty'}, many=True):print(document)

mongoHandler.update({'name': 'zty'}, {'$set': {'name': 'yyy'}}, many=True)for document in mongoHandler.select({'name': 'zzz'}, many=True):print(document)

mongoHandler.delete({'name': 'zzz'}, many=True)for document in mongoHandler.select({'name': 'zzz'}, many=True):print(document)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值