<s> """<STR_LIT>""" <EOL> import json <EOL> from pymongo import MongoClient <EOL> from pymongo . errors import CollectionInvalid <EOL> from . . utils import uuid <EOL> def delete_collection ( db_name , collection_name , host = '<STR_LIT:localhost>' , port = <NUM_LIT> ) : <EOL> """<STR_LIT>""" <EOL> client = MongoClient ( "<STR_LIT>" % ( host , port ) ) <EOL> client [ db_name ] . drop_collection ( collection_name ) <EOL> class Backend ( object ) : <EOL> def __init__ ( self , ** kwrds ) : <EOL> self . mongo_url = kwrds . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . mongo_client = MongoClient ( self . mongo_url ) <EOL> def get_collection ( self , collection_name ) : <EOL> return self . mongo_client . get_default_database ( ) [ collection_name ] <EOL> def ensure_table ( self , cls ) : <EOL> coll_name = cls . get_table_name ( ) <EOL> try : <EOL> db = self . mongo_client . get_default_database ( ) <EOL> db . create_collection ( coll_name ) <EOL> except CollectionInvalid : <EOL> pass <EOL> coll = self . get_collection ( coll_name ) <EOL> for idx_name in cls . index_names ( ) : <EOL> coll . ensure_index ( idx_name ) <EOL> def _find ( self , cls , query ) : <EOL> coll = self . get_collection ( cls . get_table_name ( ) ) <EOL> final_results = [ ] <EOL> for db_result in coll . find ( query ) : <EOL> obj_data = json . dumps ( db_result [ '<STR_LIT:value>' ] ) <EOL> obj = cls . from_data ( obj_data ) <EOL> final_results . append ( obj ) <EOL> return final_results <EOL> def find_one ( self , cls , id ) : <EOL> one = self . _find ( cls , { "<STR_LIT>" : id } ) <EOL> if not one : <EOL> return None <EOL> return one [ <NUM_LIT:0> ] <EOL> def find_all ( self , cls ) : <EOL> return self . _find ( cls , { } ) <EOL> def find_by_index ( self , cls , index_name , value ) : <EOL> return self . _find ( cls , { index_name : str ( value ) } ) <EOL> def save ( self , obj ) : <EOL> if not obj . id : <EOL> obj . id = uuid ( ) <EOL> stored_data = { <EOL> '<STR_LIT>' : obj . id , <EOL> '<STR_LIT:value>' : json . loads ( obj . to_data ( ) ) <EOL> } <EOL> index_vals = obj . indexes ( ) or { } <EOL> for key in obj . __class__ . index_names ( ) or [ ] : <EOL> val = index_vals . get ( key , '<STR_LIT>' ) <EOL> stored_data [ key ] = str ( val ) <EOL> coll = self . get_collection ( obj . __class__ . get_table_name ( ) ) <EOL> coll . update ( { "<STR_LIT>" : obj . id } , stored_data , upsert = True ) </s>
