<s> import inflect <EOL> from flask import request <EOL> from flask_restful . utils import unpack <EOL> from marshmallow import post_load <EOL> from marshmallow_jsonapi import Schema , SchemaOpts , fields <EOL> from app . framework . errors import make_marshmallow_error_output , make_simple_error_output <EOL> inflect_engine = inflect . engine ( ) <EOL> class ReferenceField ( fields . Field ) : <EOL> def __init__ ( self , entity , * args , ** kwargs ) : <EOL> self . entity = entity <EOL> fields . Field . __init__ ( self , * args , ** kwargs ) <EOL> def _serialize ( self , value , attr , obj ) : <EOL> if value is None : <EOL> return '<STR_LIT>' <EOL> return value . id <EOL> def _deserialize ( self , value , attr , obj ) : <EOL> result = self . entity . objects . get ( id = str ( value ) ) <EOL> return result <EOL> class BaseSchemaOpts ( SchemaOpts ) : <EOL> def __init__ ( self , meta ) : <EOL> self . envelope_key = '<STR_LIT:data>' <EOL> self . entity = getattr ( meta , '<STR_LIT>' ) <EOL> if ( self . entity and not hasattr ( meta , '<STR_LIT>' ) ) : <EOL> setattr ( <EOL> meta , <EOL> '<STR_LIT>' , <EOL> inflect_engine . plural ( self . entity . __name__ ) . lower ( ) <EOL> ) <EOL> SchemaOpts . __init__ ( self , meta ) <EOL> class BaseSchema ( Schema ) : <EOL> OPTIONS_CLASS = BaseSchemaOpts <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> self . transform_entity = kwargs . pop ( '<STR_LIT>' , True ) <EOL> Schema . __init__ ( self , * args , ** kwargs ) <EOL> @ post_load <EOL> def parse ( self , data ) : <EOL> if self . transform_entity : <EOL> return self . opts . entity ( ** data ) <EOL> else : <EOL> return data <EOL> class Meta : <EOL> entity = None <EOL> strict = True <EOL> def input_schema ( schema ) : <EOL> def upper_wrapper ( fn ) : <EOL> def inner_wrapper ( self , * args , ** kwargs ) : <EOL> request_data = request . get_json ( ) <EOL> if not request_data : <EOL> return make_simple_error_output ( <EOL> '<STR_LIT>' , <EOL> <NUM_LIT> <EOL> ) <EOL> data , err = schema . load ( request_data ) <EOL> if err : <EOL> return make_marshmallow_error_output ( err ) <EOL> return fn ( self , data , * args , ** kwargs ) <EOL> return inner_wrapper <EOL> return upper_wrapper <EOL> def output_schema ( schema ) : <EOL> def upper_wrapper ( fn ) : <EOL> def inner_wrapper ( self , * args , ** kwargs ) : <EOL> resp = fn ( self , * args , ** kwargs ) <EOL> if isinstance ( resp , tuple ) : <EOL> data , code , headers = unpack ( resp ) <EOL> return schema . dump ( data ) [ <NUM_LIT:0> ] , code , headers <EOL> else : <EOL> return schema . dump ( resp ) [ <NUM_LIT:0> ] <EOL> return inner_wrapper <EOL> return upper_wrapper </s>
