<s> import datetime <EOL> from peewee import PeeweeException , Proxy , Model <EOL> from playhouse . db_url import connect <EOL> from playhouse . shortcuts import model_to_dict , dict_to_model <EOL> __version__ = "<STR_LIT>" <EOL> __project__ = "<STR_LIT>" <EOL> __author__ = "<STR_LIT>" <EOL> __license__ = "<STR_LIT>" <EOL> class PeeweePlugin ( object ) : <EOL> """<STR_LIT>""" <EOL> name = '<STR_LIT>' <EOL> api = <NUM_LIT:2> <EOL> default_connection = '<STR_LIT>' <EOL> def __init__ ( self , connection = None ) : <EOL> self . database = None <EOL> self . connection = connection or self . default_connection <EOL> self . proxy = Proxy ( ) <EOL> self . serializer = Serializer ( ) <EOL> def setup ( self , app ) : <EOL> """<STR_LIT>""" <EOL> app . config . setdefault ( '<STR_LIT>' , self . connection ) <EOL> self . connection = app . config . get ( '<STR_LIT>' ) <EOL> self . database = connect ( self . connection ) <EOL> self . proxy . initialize ( self . database ) <EOL> def apply ( self , callback , route ) : <EOL> def wrapper ( * args , ** kwargs ) : <EOL> if self . connection . startswith ( '<STR_LIT>' ) : <EOL> return callback ( * args , ** kwargs ) <EOL> self . database . connect ( ) <EOL> try : <EOL> with self . database . transaction ( ) : <EOL> response = callback ( * args , ** kwargs ) <EOL> except PeeweeException : <EOL> self . database . rollback ( ) <EOL> raise <EOL> finally : <EOL> self . database . commit ( ) <EOL> if not self . database . is_closed ( ) : <EOL> self . database . close ( ) <EOL> return response <EOL> return wrapper <EOL> def to_dict ( self , obj , ** kwargs ) : <EOL> return self . serializer . serialize_object ( obj , ** kwargs ) <EOL> class Serializer ( object ) : <EOL> date_format = '<STR_LIT>' <EOL> time_format = '<STR_LIT>' <EOL> datetime_format = '<STR_LIT:U+0020>' . join ( [ date_format , time_format ] ) <EOL> def convert_value ( self , value ) : <EOL> if isinstance ( value , datetime . datetime ) : <EOL> return value . strftime ( self . datetime_format ) <EOL> if isinstance ( value , datetime . date ) : <EOL> return value . strftime ( self . date_format ) <EOL> if isinstance ( value , datetime . time ) : <EOL> return value . strftime ( self . time_format ) <EOL> if isinstance ( value , Model ) : <EOL> return value . get_id ( ) <EOL> return value <EOL> def clean_data ( self , data ) : <EOL> for key , value in data . items ( ) : <EOL> if isinstance ( value , dict ) : <EOL> self . clean_data ( value ) <EOL> elif isinstance ( value , ( list , tuple ) ) : <EOL> data [ key ] = map ( self . clean_data , value ) <EOL> else : <EOL> data [ key ] = self . convert_value ( value ) <EOL> return data <EOL> def serialize_object ( self , obj , ** kwargs ) : <EOL> data = model_to_dict ( obj , ** kwargs ) <EOL> return self . clean_data ( data ) <EOL> class Deserializer ( object ) : <EOL> @ staticmethod <EOL> def deserialize_object ( model , data ) : <EOL> return dict_to_model ( model , data ) </s>
