<s> import logging <EOL> from django . core . urlresolvers import reverse , NoReverseMatch <EOL> from django . utils . timezone import now <EOL> from rest_framework import serializers <EOL> from . import models <EOL> logger = logging . getLogger ( __name__ ) <EOL> class MetricSerializer ( serializers . ModelSerializer ) : <EOL> source = serializers . CharField ( source = '<STR_LIT>' , required = False ) <EOL> value = serializers . FloatField ( source = '<STR_LIT>' ) <EOL> timestamp = serializers . DateTimeField ( source = '<STR_LIT>' , <EOL> required = False ) <EOL> class Meta : <EOL> model = models . Metric <EOL> fields = ( '<STR_LIT:source>' , '<STR_LIT:name>' , '<STR_LIT:value>' , '<STR_LIT>' ) <EOL> def validate_source ( self , attrs , source ) : <EOL> if source in attrs : <EOL> try : <EOL> reverse ( "<STR_LIT>" , args = [ attrs [ source ] ] ) <EOL> except NoReverseMatch : <EOL> raise serializers . ValidationError ( "<STR_LIT>" ) <EOL> return attrs <EOL> def restore_object ( self , attrs , instance = None ) : <EOL> kwargs = { '<STR_LIT:name>' : attrs [ '<STR_LIT:name>' ] } <EOL> if '<STR_LIT>' in attrs : <EOL> source , created = models . Source . objects . get_or_create ( <EOL> name = attrs [ '<STR_LIT>' ] ) <EOL> if created : <EOL> logger . debug ( '<STR_LIT>' , source . name ) <EOL> kwargs [ '<STR_LIT>' ] = source . pk <EOL> try : <EOL> instance = self . opts . model . objects . get ( ** kwargs ) <EOL> except self . opts . model . DoesNotExist : <EOL> instance = self . opts . model ( ** kwargs ) <EOL> instance . latest_value = attrs [ '<STR_LIT>' ] <EOL> instance . last_updated = attrs . get ( '<STR_LIT>' , now ( ) ) <EOL> return instance <EOL> def save_object ( self , obj , ** kwargs ) : <EOL> if '<STR_LIT>' in kwargs : <EOL> del ( kwargs [ '<STR_LIT>' ] ) <EOL> super ( MetricSerializer , self ) . save_object ( obj , ** kwargs ) <EOL> obj . add_latest_to_archive ( ) </s>
