<s> from multiprocessing import Process <EOL> from contextlib import contextmanager <EOL> from . models import BaseModel <EOL> from . exceptions import NotFound <EOL> from . globals import SwappableDict , cosmos <EOL> db = SwappableDict ( ) <EOL> class DBModel ( BaseModel ) : <EOL> @ classmethod <EOL> def get_by_id ( cls , id ) : <EOL> try : <EOL> return db [ cls . table_name ] [ id ] <EOL> except KeyError : <EOL> raise NotFound <EOL> @ classmethod <EOL> def get_list ( cls , ** kwargs ) : <EOL> if not kwargs : <EOL> return sorted ( db [ cls . table_name ] . items ( ) ) <EOL> ret = [ ] <EOL> for id , rep in db [ cls . table_name ] . items ( ) : <EOL> keep = True <EOL> for key , val in kwargs . items ( ) : <EOL> if rep [ key ] != val : <EOL> keep = False <EOL> break <EOL> if keep : <EOL> ret . append ( ( id , rep ) ) <EOL> return sorted ( ret ) <EOL> @ classmethod <EOL> def create ( cls , ** patch ) : <EOL> id = str ( len ( db [ cls . table_name ] ) ) <EOL> db [ cls . table_name ] [ id ] = patch <EOL> return id , patch <EOL> @ classmethod <EOL> def update ( cls , id , ** patch ) : <EOL> rep = db [ cls . table_name ] [ id ] <EOL> rep . update ( patch ) <EOL> return rep <EOL> @ classmethod <EOL> def delete ( cls , id ) : <EOL> if id not in db [ cls . table_name ] : <EOL> raise NotFound <EOL> del db [ cls . table_name ] [ id ] <EOL> @ contextmanager <EOL> def served_api ( api , port , ** kwargs ) : <EOL> from time import sleep <EOL> p = Process ( target = api . run , args = ( port , ) , kwargs = kwargs ) <EOL> p . start ( ) <EOL> sleep ( <NUM_LIT:0.1> ) <EOL> try : <EOL> with cosmos . swap ( { } ) : <EOL> yield <EOL> except Exception as e : <EOL> raise e <EOL> finally : <EOL> p . terminate ( ) <EOL> class WildcardClass ( object ) : <EOL> def __eq__ ( self , other ) : <EOL> return True <EOL> Wildcard = WildcardClass ( ) </s>
