<s> from mongoengine . base import get_document <EOL> from werkzeug . datastructures import FileStorage <EOL> from wtforms import fields <EOL> try : <EOL> from wtforms . fields . core import _unset_value as unset_value <EOL> except ImportError : <EOL> from wtforms . utils import unset_value <EOL> from . import widgets <EOL> from flask_admin . model . fields import InlineFormField <EOL> def is_empty ( file_object ) : <EOL> file_object . seek ( <NUM_LIT:0> ) <EOL> first_char = file_object . read ( <NUM_LIT:1> ) <EOL> file_object . seek ( <NUM_LIT:0> ) <EOL> return not bool ( first_char ) <EOL> class ModelFormField ( InlineFormField ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , model , view , form_class , form_opts = None , ** kwargs ) : <EOL> super ( ModelFormField , self ) . __init__ ( form_class , ** kwargs ) <EOL> self . model = model <EOL> if isinstance ( self . model , str ) : <EOL> self . model = get_document ( self . model ) <EOL> self . view = view <EOL> self . form_opts = form_opts <EOL> def populate_obj ( self , obj , name ) : <EOL> candidate = getattr ( obj , name , None ) <EOL> if candidate is None : <EOL> candidate = self . model ( ) <EOL> setattr ( obj , name , candidate ) <EOL> self . form . populate_obj ( candidate ) <EOL> self . view . on_model_change ( self . form , candidate ) <EOL> class MongoFileField ( fields . FileField ) : <EOL> """<STR_LIT>""" <EOL> widget = widgets . MongoFileInput ( ) <EOL> def __init__ ( self , label = None , validators = None , ** kwargs ) : <EOL> super ( MongoFileField , self ) . __init__ ( label , validators , ** kwargs ) <EOL> self . _should_delete = False <EOL> def process ( self , formdata , data = unset_value ) : <EOL> if formdata : <EOL> marker = '<STR_LIT>' % self . name <EOL> if marker in formdata : <EOL> self . _should_delete = True <EOL> return super ( MongoFileField , self ) . process ( formdata , data ) <EOL> def populate_obj ( self , obj , name ) : <EOL> field = getattr ( obj , name , None ) <EOL> if field is not None : <EOL> if self . _should_delete : <EOL> field . delete ( ) <EOL> return <EOL> if isinstance ( self . data , FileStorage ) and not is_empty ( self . data . stream ) : <EOL> if not field . grid_id : <EOL> func = field . put <EOL> else : <EOL> func = field . replace <EOL> func ( self . data . stream , <EOL> filename = self . data . filename , <EOL> content_type = self . data . content_type ) <EOL> class MongoImageField ( MongoFileField ) : <EOL> """<STR_LIT>""" <EOL> widget = widgets . MongoImageInput ( ) </s>
