def get_gallery_items(): """Gets all gallery items.""" if app.config.get('USE_SESSIONSTORE_NOT_DB'): if session.get('gallery_item') is None: session['gallery_item'] = [''] for id, o in enumerate(session.get('gallery_item', [])): if o: filepath = os.path.join( app.config['MEDIA_FOLDER'], session['gallery_item'][id]['image']) # If the placeholder image defined in session storage # doesn't exist on the filesystem (e.g. if Heroku has # wiped the filesystem due to app restart), set a new # image for this model. if not os.path.exists(filepath): session['gallery_item'][id]['image'] = ( placeholder_or_random_sample_image()) gallery_items = [] for id, o in enumerate(session['gallery_item']): if o: model = GalleryItem(**o) model.id = id model.weight = id-1 gallery_items.append(model) else: gallery_items = ( GalleryItem.query .filter_by(active=True) .order_by(GalleryItem.weight)) return gallery_items
def get_db_ic_blocks(ic_blocks): """Gets image blocks from the database.""" for slug, o in ic_blocks.items(): if not(ImageContentBlock.query .filter_by(slug=slug) .first()): # If this model isn't currently saved to the DB, # set its image now (could be a random sample) and save. model = o['model'] model.image = placeholder_or_random_sample_image() try: model.save() except IntegrityError as e: db.session.rollback() raise e for o in ( ImageContentBlock.query .filter_by(active=True) .all()): ic_blocks[o.slug] = { 'title': o.title, 'image': o.image} return ic_blocks
def get_gallery_items(): """Gets all gallery items.""" if app.config.get('USE_SESSIONSTORE_NOT_DB'): if session.get('gallery_item') is None: session['gallery_item'] = [''] for id, o in enumerate(session.get('gallery_item', [])): if o: filepath = os.path.join(app.config['MEDIA_FOLDER'], session['gallery_item'][id]['image']) # If the placeholder image defined in session storage # doesn't exist on the filesystem (e.g. if Heroku has # wiped the filesystem due to app restart), set a new # image for this model. if not os.path.exists(filepath): session['gallery_item'][id]['image'] = ( placeholder_or_random_sample_image()) gallery_items = [] for id, o in enumerate(session['gallery_item']): if o: model = GalleryItem(**o) model.id = id model.weight = id - 1 gallery_items.append(model) else: gallery_items = (GalleryItem.query.filter_by(active=True).order_by( GalleryItem.weight)) return gallery_items
def get_sessionstore_ic_blocks(ic_blocks): """Gets image blocks from the session store.""" for slug, o in ic_blocks.items(): if session.get('image_content_block') is None: session['image_content_block'] = {} if session.get('image_content_block', {}).get(slug, None): filepath = os.path.join( app.config['MEDIA_FOLDER'], session['image_content_block'][slug]['image']) # If the placeholder image defined in session storage # doesn't exist on the filesystem (e.g. if Heroku has # wiped the filesystem due to app restart), clear this # model's session storage. if not os.path.exists(filepath): del session['image_content_block'][slug] if not (session.get('image_content_block', {}) .get(slug, None)): # If this model isn't currently saved to session storage, # set its image now (could be a random sample) and save. session['image_content_block'][slug] = { 'title': o['title'], 'image': placeholder_or_random_sample_image()} for slug, o in session.get('image_content_block', {}).items(): ic_blocks[slug] = { 'title': o['title'], 'image': o['image']} return ic_blocks
def get_sessionstore_ic_blocks(ic_blocks): """Gets image blocks from the session store.""" for slug, o in ic_blocks.items(): if session.get('image_content_block') is None: session['image_content_block'] = {} if session.get('image_content_block', {}).get(slug, None): filepath = os.path.join( app.config['MEDIA_FOLDER'], session['image_content_block'][slug]['image']) # If the placeholder image defined in session storage # doesn't exist on the filesystem (e.g. if Heroku has # wiped the filesystem due to app restart), clear this # model's session storage. if not os.path.exists(filepath): del session['image_content_block'][slug] if not (session.get('image_content_block', {}).get(slug, None)): # If this model isn't currently saved to session storage, # set its image now (could be a random sample) and save. session['image_content_block'][slug] = { 'title': o['title'], 'image': placeholder_or_random_sample_image() } for slug, o in session.get('image_content_block', {}).items(): ic_blocks[slug] = {'title': o['title'], 'image': o['image']} return ic_blocks
def get_default_gallery_items(): """Gets the default gallery items.""" default_gallery_items = GalleryItem.default_content() if app.config.get('USE_SESSIONSTORE_NOT_DB'): session['gallery_item'] = [''] for o in default_gallery_items: # If this model isn't currently saved to session storage, # set its image and text content now (could be random # samples) and save. session['gallery_item'].append({ 'title': o.title, 'image': placeholder_or_random_sample_image(), 'content': placeholder_or_random_sample_text(), 'date_taken': o.date_taken }) else: curr_weight = 0 for o in default_gallery_items: # If this model isn't currently saved to the DB, # set its image and text content now (could be random # samples) and save. o.image = placeholder_or_random_sample_image() o.content = placeholder_or_random_sample_text() o.weight = curr_weight try: o.save() curr_weight += 1 except IntegrityError as e: db.session.rollback() raise e return default_gallery_items
def get_default_gallery_items(): """Gets the default gallery items.""" default_gallery_items = GalleryItem.default_content() if app.config.get('USE_SESSIONSTORE_NOT_DB'): session['gallery_item'] = [''] for o in default_gallery_items: # If this model isn't currently saved to session storage, # set its image and text content now (could be random # samples) and save. session['gallery_item'].append({ 'title': o.title, 'image': placeholder_or_random_sample_image(), 'content': placeholder_or_random_sample_text(), 'date_taken': o.date_taken}) else: curr_weight = 0 for o in default_gallery_items: # If this model isn't currently saved to the DB, # set its image and text content now (could be random # samples) and save. o.image = placeholder_or_random_sample_image() o.content = placeholder_or_random_sample_text() o.weight = curr_weight try: o.save() curr_weight += 1 except IntegrityError as e: db.session.rollback() raise e return default_gallery_items
def test_sample_image_when_scrape_configured(): app = create_app(ImageScrapeTestConfig) with app.app_context(): sample_image = placeholder_or_random_sample_image() assert sample_image is not None assert len(sample_image) assert sample_image != app.config[ 'EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH'] sample_image_filepath = os.path.abspath( os.path.join(app.config['MEDIA_FOLDER'], sample_image)) assert os.path.exists(sample_image_filepath) os.remove(sample_image_filepath)
def test_sample_image_when_scrape_configured(): app = create_app(ImageScrapeTestConfig) with app.app_context(): sample_image = placeholder_or_random_sample_image() assert sample_image is not None assert len(sample_image) assert sample_image != app.config[ 'EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH'] sample_image_filepath = os.path.abspath(os.path.join( app.config['MEDIA_FOLDER'], sample_image)) assert os.path.exists(sample_image_filepath) os.remove(sample_image_filepath)
def get_db_ic_blocks(ic_blocks): """Gets image blocks from the database.""" for slug, o in ic_blocks.items(): if not (ImageContentBlock.query.filter_by(slug=slug).first()): # If this model isn't currently saved to the DB, # set its image now (could be a random sample) and save. model = o['model'] model.image = placeholder_or_random_sample_image() try: model.save() except IntegrityError as e: db.session.rollback() raise e for o in (ImageContentBlock.query.filter_by(active=True).all()): ic_blocks[o.slug] = {'title': o.title, 'image': o.image} return ic_blocks
def test_placeholder_when_no_sample_images_configured(app): sample_image = placeholder_or_random_sample_image() assert sample_image == app.config[ 'EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH']
def add_func(model_name, is_autosave=False): try: v = app.config['EDITABLE_MODELS'][model_name] except KeyError: abort(404) if not (('is_createable' in v) and v['is_createable']): abort(404) try: model_classpath = v['classpath'] except KeyError: raise ValueError( ('No class path defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format(model_name)) try: title_field_name = v['title_field'] except KeyError: raise ValueError( ('No title field defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format(model_name)) try: weight_field_name = v['weight_field'] except KeyError: weight_field_name = None model_class = get_model_class(model_classpath, model_name) form = Form() if form.validate_on_submit(): model_name_friendly = model_name.replace('_', ' ').title() model = model_class.new_item() if ('image_fields' in v) and v['image_fields']: for k in v['image_fields']: setattr(model, k, placeholder_or_random_sample_image()) if ('long_text_fields' in v) and v['long_text_fields']: for k in v['long_text_fields']: setattr(model, k, placeholder_or_random_sample_text()) if (((not app.config.get('USE_SESSIONSTORE_NOT_DB')) and weight_field_name)): max_weight = model_class.max_weight() setattr(model, weight_field_name, (max_weight is not None and (max_weight + 1) or 0)) try: if app.config.get('USE_SESSIONSTORE_NOT_DB'): if not session.get(model_name, None): session[model_name] = [] fields_to_save = [] for k in ('text_fields', 'long_text_fields', 'image_fields'): if (k in v) and v[k]: fields_to_save.extend(v[k]) values_to_save = {} for k in fields_to_save: values_to_save[k] = getattr(model, k) if ('date_fields' in v) and v['date_fields']: for k in v['date_fields']: val = getattr(model, k, '') if val: val = val.strftime('%Y-%m-%d') values_to_save[k] = val if ('time_fields' in v) and v['time_fields']: for k in v['time_fields']: val = getattr(model, k, '') if val: val = val.strftime('%H:%M:%S') values_to_save[k] = val session[model_name].append(values_to_save) else: model.save() app.logger.info('{0} added: {1}; user: {2}'.format( model_name_friendly, model, current_user)) if is_autosave: return Response('OK') else: flash( '"{0}" has been added.'.format( getattr(model, title_field_name)), 'success') except IntegrityError as e: db.session.rollback() if is_autosave: return Response('ERROR') else: msg = (('violates unique constraint' in e.message) and (('Error: a {0} with title "{1}" ' 'already exists.').format( model_name_friendly, getattr(model, title_field_name))) or "Error adding {0}.".format( getattr(model, title_field_name))) flash(msg, 'danger') else: if is_autosave: return Response('ERROR') else: flash_errors(form) return redirect(url_for("public.home"))
def image_update_func(model_name, field_name, model_identifier, is_dropzone=False): try: v = app.config['EDITABLE_MODELS'][model_name] except KeyError: abort(404) if not (('image_fields' in v) and (field_name in v['image_fields'])): abort(404) try: model_classpath = v['classpath'] except KeyError: raise ValueError( ('No class path defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format(model_name)) try: identifier_field_name = v['identifier_field'] except KeyError: raise ValueError( ('No identifier field defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format(model_name)) try: title_field_name = v['title_field'] except KeyError: raise ValueError( ('No title field defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format(model_name)) try: image_relative_path = v['image_relative_path'] except KeyError: raise ValueError( ('No image relative path defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format(model_name)) model_class = get_model_class(model_classpath, model_name) try: model_identifier_int = int(model_identifier) except ValueError: model_identifier_int = None filter_by_kwargs = { identifier_field_name: model_identifier, 'active': True } model = None if app.config.get('USE_SESSIONSTORE_NOT_DB'): model_store = session.get(model_name, None) model_dict = None if model_store and (type(model_store).__name__ == 'list'): try: model_dict = model_store[model_identifier_int] except KeyError: pass elif model_store and (type(model_store).__name__ == 'dict'): model_dict = model_store.get(model_identifier, None) if model_dict: model = model_class(**model_dict) else: model = (model_class.query.filter_by(**filter_by_kwargs).first()) if not model: try: model = model_class.default_content()[model_identifier] except KeyError: abort(404) if request.files: request.form = request.form.copy() request.form.update(request.files) form = ImageEditForm() if form.validate_on_submit(): image_orig = None if app.config.get('USE_SESSIONSTORE_NOT_DB'): image = placeholder_or_random_sample_image() else: image_orig = getattr(model, field_name) filehandle = form.image.data parts = os.path.splitext(filehandle.filename) filename = '%s%s/%s' % ( image_relative_path, getattr(model, identifier_field_name), secure_filename('{0}-{1}{2}'.format( parts[0], datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S'), parts[1]))) filepath = os.path.abspath( os.path.join(app.config['MEDIA_FOLDER'], filename)) if not os.path.exists(os.path.dirname(filepath)): os.makedirs(os.path.dirname(filepath)) Transfer().save(filehandle, destination=filepath) image = filename ret = update_submit_handler(model_name=model_name, model_identifier=model_identifier, model_identifier_int=model_identifier_int, title_field_name=title_field_name, content=image, model=model, field_name=field_name, is_autosave=is_dropzone, image_orig=image_orig) if ret: return ret else: if is_dropzone: return Response('ERROR') else: flash_errors(form) return redirect(url_for("public.home"))
def add_func(model_name, is_autosave=False): try: v = app.config['EDITABLE_MODELS'][model_name] except KeyError: abort(404) if not(('is_createable' in v) and v['is_createable']): abort(404) try: model_classpath = v['classpath'] except KeyError: raise ValueError(( 'No class path defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format( model_name)) try: title_field_name = v['title_field'] except KeyError: raise ValueError(( 'No title field defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format( model_name)) try: weight_field_name = v['weight_field'] except KeyError: weight_field_name = None model_class = get_model_class(model_classpath, model_name) form = Form() if form.validate_on_submit(): model_name_friendly = model_name.replace('_', ' ').title() model = model_class.new_item() if ('image_fields' in v) and v['image_fields']: for k in v['image_fields']: setattr(model, k, placeholder_or_random_sample_image()) if ('long_text_fields' in v) and v['long_text_fields']: for k in v['long_text_fields']: setattr(model, k, placeholder_or_random_sample_text()) if ( ( (not app.config.get('USE_SESSIONSTORE_NOT_DB')) and weight_field_name)): max_weight = model_class.max_weight() setattr( model, weight_field_name, (max_weight is not None and (max_weight+1) or 0)) try: if app.config.get('USE_SESSIONSTORE_NOT_DB'): if not session.get(model_name, None): session[model_name] = [] fields_to_save = [] for k in ('text_fields', 'long_text_fields', 'image_fields'): if (k in v) and v[k]: fields_to_save.extend(v[k]) values_to_save = {} for k in fields_to_save: values_to_save[k] = getattr(model, k) if ('date_fields' in v) and v['date_fields']: for k in v['date_fields']: val = getattr(model, k, '') if val: val = val.strftime('%Y-%m-%d') values_to_save[k] = val if ('time_fields' in v) and v['time_fields']: for k in v['time_fields']: val = getattr(model, k, '') if val: val = val.strftime('%H:%M:%S') values_to_save[k] = val session[model_name].append(values_to_save) else: model.save() app.logger.info('{0} added: {1}; user: {2}'.format( model_name_friendly, model, current_user)) if is_autosave: return Response('OK') else: flash('"{0}" has been added.'.format( getattr(model, title_field_name)), 'success') except IntegrityError as e: db.session.rollback() if is_autosave: return Response('ERROR') else: msg = ( ('violates unique constraint' in e.message) and (( 'Error: a {0} with title "{1}" ' 'already exists.').format( model_name_friendly, getattr(model, title_field_name))) or "Error adding {0}.".format( getattr(model, title_field_name))) flash(msg, 'danger') else: if is_autosave: return Response('ERROR') else: flash_errors(form) return redirect(url_for("public.home"))
def image_update_func(model_name, field_name, model_identifier, is_dropzone=False): try: v = app.config['EDITABLE_MODELS'][model_name] except KeyError: abort(404) if not(('image_fields' in v) and (field_name in v['image_fields'])): abort(404) try: model_classpath = v['classpath'] except KeyError: raise ValueError(( 'No class path defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format( model_name)) try: identifier_field_name = v['identifier_field'] except KeyError: raise ValueError(( 'No identifier field defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format( model_name)) try: title_field_name = v['title_field'] except KeyError: raise ValueError(( 'No title field defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format( model_name)) try: image_relative_path = v['image_relative_path'] except KeyError: raise ValueError(( 'No image relative path defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format( model_name)) model_class = get_model_class(model_classpath, model_name) try: model_identifier_int = int(model_identifier) except ValueError: model_identifier_int = None filter_by_kwargs = { identifier_field_name: model_identifier, 'active': True} model = None if app.config.get('USE_SESSIONSTORE_NOT_DB'): model_store = session.get(model_name, None) model_dict = None if model_store and (type(model_store).__name__ == 'list'): try: model_dict = model_store[model_identifier_int] except KeyError: pass elif model_store and (type(model_store).__name__ == 'dict'): model_dict = model_store.get(model_identifier, None) if model_dict: model = model_class(**model_dict) else: model = ( model_class.query .filter_by(**filter_by_kwargs) .first()) if not model: try: model = model_class.default_content()[model_identifier] except KeyError: abort(404) if request.files: request.form = request.form.copy() request.form.update(request.files) form = ImageEditForm() if form.validate_on_submit(): image_orig = None if app.config.get('USE_SESSIONSTORE_NOT_DB'): image = placeholder_or_random_sample_image() else: image_orig = getattr(model, field_name) filehandle = form.image.data parts = os.path.splitext(filehandle.filename) filename = '%s%s/%s' % ( image_relative_path, getattr(model, identifier_field_name), secure_filename( '{0}-{1}{2}'.format( parts[0], datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S'), parts[1]))) filepath = os.path.abspath( os.path.join( app.config['MEDIA_FOLDER'], filename)) if not os.path.exists(os.path.dirname(filepath)): os.makedirs(os.path.dirname(filepath)) Transfer().save(filehandle, destination=filepath) image = filename ret = update_submit_handler( model_name=model_name, model_identifier=model_identifier, model_identifier_int=model_identifier_int, title_field_name=title_field_name, content=image, model=model, field_name=field_name, is_autosave=is_dropzone, image_orig=image_orig) if ret: return ret else: if is_dropzone: return Response('ERROR') else: flash_errors(form) return redirect(url_for("public.home"))