def new(): """Create a new blog post. **Route:** ``/admin/posts/new`` **Methods:** ``POST`` """ form = CreateBlogPostForm(request.form) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects()] form.author.data = str(g.user.id) upload_form = UploadImageForm() if form.validate_on_submit(): author = User.objects().get(id=ObjectId(form.author.data)) post = BlogPost(title=form.title.data, slug=form.slug.data, images=[Image.objects().get(filename=fn) for fn in form.images.data], markdown_content=form.body.data, author=author, posted_by=g.user, tags=form.tags.data) post.save() if form.published.data: post.publish() else: post.unpublish() return redirect(url_for('.index')) images = Image.objects() return render_template('admin/posts/edit.html', user=g.user, form=form, images=images, upload_form=upload_form)
def import_from_directory(path_to_images): connect("eventum") creator = User.objects().get(gplus_id="super") filenames = os.listdir(path_to_images) filenames = [fn for fn in filenames if not fn.startswith(".")] failures = [] for filename in filenames: if Image.objects(filename=filename).count() > 0: img = Image.objects().get(filename=filename) img.delete() old_path = os.path.join(path_to_images, filename) shutil.copy(old_path, config["UPLOAD_FOLDER"]) default_path = config["RELATIVE_UPLOAD_FOLDER"] + filename image = Image(filename=filename, default_path=default_path, creator=creator) try: image.save() except ValidationError as e: failures.append(filename) print "FAIL: %s" % filename print e print "Processed %s images." % len(filenames) print "%s success." % (len(filenames) - len(failures)) print "%s failures." % len(failures)
def import_from_directory(path_to_images): connect('eventum') creator = User.objects().get(gplus_id='super') filenames = os.listdir(path_to_images) filenames = [fn for fn in filenames if not fn.startswith('.')] failures = [] for filename in filenames: if Image.objects(filename=filename).count() > 0: img = Image.objects().get(filename=filename) img.delete() old_path = os.path.join(path_to_images, filename) shutil.copy(old_path, config['UPLOAD_FOLDER']) default_path = config['RELATIVE_UPLOAD_FOLDER'] + filename image = Image(filename=filename, default_path=default_path, creator=creator) try: image.save() except ValidationError as e: failures.append(filename) print "FAIL: %s" % filename print e print "Processed %s images." % len(filenames) print "%s success." % (len(filenames) - len(failures)) print "%s failures." % len(failures)
def new(): """Create a new blog post. **Route:** ``/admin/posts/new`` **Methods:** ``POST`` """ form = CreateBlogPostForm(request.form) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects()] form.author.data = str(g.user.id) upload_form = UploadImageForm() if form.validate_on_submit(): author = User.objects().get(id=ObjectId(form.author.data)) post = BlogPost(title=form.title.data, slug=form.slug.data, images=[Image.objects().get(filename=fn) for fn in form.images.data], markdown_content=form.body.data, author=author, posted_by=g.user) post.save() if form.published.data: post.publish() else: post.unpublish() return redirect(url_for('.index')) images = Image.objects() return render_template('admin/posts/edit.html', user=g.user, form=form, images=images, upload_form=upload_form)
def delete(filename): if Image.objects(filename=filename).count() == 1: image = Image.objects().get(filename=filename) image.delete() else: flash('Invalid filename') pass return redirect(url_for('.index'))
def edit(post_id): try: object_id = ObjectId(post_id) except InvalidId: return abort(404) try: post = BlogPost.objects().with_id(object_id) except (DoesNotExist, ValidationError): flash('Cannot find blog post with id %s.' % post_id) return redirect(url_for('.index')) if request.method == 'POST': form = CreateBlogPostForm(request.form) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects()] form.author.default = str(g.user.id) if form.validate_on_submit(): was_published = post.published should_be_published = form.published.data post.title = form.title.data post.author = User.objects.get(id=ObjectId(form.author.data)) post.slug = form.slug.data post.markdown_content = form.body.data post.images = [Image.objects().get(filename=fn) for fn in form.images.data] if form.featured_image.data: post.featured_image = Image.objects().get(filename=form.featured_image.data) else: post.featured_image = None post.save() if was_published != should_be_published: if was_published: set_published_status(post.id, False) else: set_published_status(post.id, True) return redirect(url_for('.index')) upload_form = UploadImageForm() featured_image = post.featured_image.filename if post.featured_image else None form = CreateBlogPostForm(request.form, title=post.title, slug=post.slug, published=post.published, body=post.markdown_content, images=[image.filename for image in post.images], author=str(post.author.id), featured_image=featured_image) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects()] form.author.default = str(g.user.id) images = [image for image in Image.objects() if image not in post.images] return render_template('admin/posts/edit.html', user=g.user, form=form, post=post, images=images, upload_form=upload_form)
def delete(filename): """View all of the uploaded images. **Route:** ``/admin/media/delete/<filename>`` **Methods:** ``POST`` """ if Image.objects(filename=filename).count() == 1: image = Image.objects().get(filename=filename) image.delete() else: flash('Invalid filename', ERROR_FLASH) return redirect(url_for('.index'))
def create(): """Create a new event. **Route:** ``/admin/events/create`` **Methods:** ``GET, POST`` """ form = CreateEventForm(request.form) if form.validate_on_submit(): try: EventsHelper.create_event(form, g.user) except EventumError.GCalAPI as e: flash(e.message, ERROR_FLASH) return redirect(url_for('.index')) if form.errors: for error in form.errors: for message in form.errors[error]: flash(message, ERROR_FLASH) upload_form = UploadImageForm() delete_form = DeleteEventForm() images = Image.objects() return render_template('admin/events/create.html', form=form, delete_form=delete_form, upload_form=upload_form, images=images)
def add(): """Add `email` to the whitelist.""" form = AddToWhitelistForm(request.form) if form.user_type.data == 'fake_user': if form.validate_on_submit(): fake_id = str(uuid.uuid4()) fake_email = fake_id[:10] + "@fake-users.com" filename = form.fake_user_image.data try: fake_image = Image.objects().get(filename=filename) fake_user = User(email=fake_email, gplus_id=fake_id, name=form.name.data, user_type=form.user_type.data, image=fake_image) except Image.DoesNotExist: fake_user = User(email=fake_email, gplus_id=fake_id, name=form.name.data, user_type=form.user_type.data) fake_user.save() else: app.logger.warning(form.errors) else: user_exists = User.objects(email=form.email.data).count() != 0 if form.validate_on_submit() and not user_exists: wl = Whitelist(email=form.email.data, user_type=form.user_type.data) wl.save() else: app.logger.warning(form.errors) return redirect(url_for('users.index'))
def edit(event_id): """""" try: event = Event.objects().get(id=event_id) except (DoesNotExist, ValidationError): flash('Cannont find event with id "%s"' % event_id) return redirect(url_for('.index')) form = EditEventForm(request.form) if request.method == 'POST' else \ EventsHelper.create_form(event, request) if form.validate_on_submit(): try: EventsHelper.update_event(event, form) except GoogleCalendarAPIError as e: flash(e.message) return redirect(url_for('.index')) if form.errors: for error in form.errors: for message in form.errors[error]: flash(message) delete_form = DeleteEventForm() upload_form = UploadImageForm() images = Image.objects() return render_template('admin/events/edit.html', form=form, event=event, delete_form=delete_form, upload_form=upload_form, images=images)
def _image(self): """Gets an image to associate with the event, from the database. :returns: The image. :rtype: :class:'~app.models.Image' """ return random.choice(Image.objects())
def view(): """Displays all uploaded images. **Route:** ``/admin/media/view`` **Methods:** ``GET`` """ images = Image.objects() return render_template('admin/media/view.html', images=images)
def _images(self): """Gets a list of images from the database if any exist. :returns: The images. :rtype: list(:class:`~app.models.Image`) """ # Fetch self.images if it hasn't been fetched if self.images is None: self.images = list(Image.objects().limit(5)) return self.images
def index(): """View all of the uploaded images. **Route:** ``/admin/media`` **Methods:** ``GET`` """ images = Image.objects() form = UploadImageForm() return render_template('admin/media/media.html', images=images, form=form)
def image_with_same_name(form, field): """A validator that ensures that there is an image in the database with the filename that is the same as the field's data. :param form: The parent form :type form: :class:`Form` :param field: The field to validate :type field: :class:`Field` """ if Image.objects(filename=field.data).count() != 1: return ValidationError( message="Can't find image '{}' in the database".format(field.data))
def create_images(num_images, superuser, printer): """Creates ``num_images`` image objects in the database. It will download sample images from http://lorempixel.com, and add database entries. :param int num_images: The number of images to create :param superuser: The superuser object to associate with the images. :type superuser: :class:`~app.models.User` :param printer: The object to manage progress printing. :type printer: :class:`~script.cli.ProgressPrinter` :returns: A list of images that now exist. :rtype: list(:class:`~app.models.Image`) """ print "Generating images..." printer.line() successes = [] failures = [] skips = [] for width in range(400, 1600, (1600 - 400) / num_images): height = width / 2 filename = BASE_FILENAME.format(width, height) path = config['UPLOAD_FOLDER'] + filename url = BASE_URL.format(width, height) printer.begin_status_line(filename) # Download image if it doesn't exist already if not exists(path): try: urllib.urlretrieve(url, path) except IOError: failures.append((filename, '')) printer.status_fail() continue # Failed to download, move on to the next image. # Insert or fetch image from database if Image.objects(filename=filename).count() == 0: image = Image(filename=filename, default_path=path, creator=superuser) image.save() successes.append((filename, path)) printer.status_success() else: skips.append((filename, path)) printer.status_skip() printer.line() printer.results(len(successes), len(skips), len(failures)) return successes + skips
def __call__(self, form, field): """Called internally by :mod:`wtforms` on validation of the field. :param form: The parent form :type form: :class:`Form` :param field: The field to validate :type field: :class:`Field` :raises: :class:`wtforms.validators.ValidationError` """ filename = '{}.'.format(field.data) if Image.objects(filename__startswith=filename).count(): raise ValidationError(self.message)
def index(): """View and manage users Whitelisted users are the only ones allowed to make user accounts. """ upload_form = UploadImageForm() whitelist_form = AddToWhitelistForm() return render_template('admin/users/users.html', whitelist_form=whitelist_form, upload_form=upload_form, whitelist=Whitelist.objects(redeemed=False), users=User.objects(), images=Image.objects(), current_user=g.user)
def event_data_from_form(klass, form, creator=None): if not form: return {} event_image = None filename = form.event_image.data if filename and Image.objects(filename=filename).count() == 1: event_image = Image.objects().get(filename=filename) event_data = { 'title': form.title.data, 'slug': form.slug.data, 'location': form.location.data, 'start_time': form.start_time.data, 'end_time': form.end_time.data, 'published': form.published.data, 'short_description_markdown': form.short_description.data, 'long_description_markdown': form.long_description.data, 'is_recurring': form.is_recurring.data, 'facebook_url': form.facebook_url.data, 'image': event_image } if creator: event_data['creator'] = creator return event_data
def event_data_from_form(cls, form, creator=None): """Translate a :class:`~app.forms.CreateEventForm` or a subclass into a dictionary of event data. :param form: The form to translate. :type form: :class:`~app.forms.CreateEventForm` or a subclasss :param creator: The creator of the event. :type creator: :class:`~app.models.User` :returns: Event data. :rtype: dict """ if not form: return {} event_image = None filename = form.event_image.data if filename and Image.objects(filename=filename).count() == 1: event_image = Image.objects().get(filename=filename) event_data = { 'title': form.title.data, 'slug': form.slug.data, 'location': form.location.data, 'start_time': form.start_time.data, 'end_time': form.end_time.data, 'published': form.published.data, 'short_description_markdown': form.short_description.data, 'long_description_markdown': form.long_description.data, 'is_recurring': form.is_recurring.data, 'facebook_url': form.facebook_url.data, 'image': event_image } if creator: event_data['creator'] = creator return event_data
def event_data_from_form(klass, form, creator=None): """Translate a :class:`~app.forms.CreateEventForm` or a subclass into a dictionary of event data. :param form: The form to translate. :type form: :class:`~app.forms.CreateEventForm` or a subclasss :param creator: The creator of the event. :type creator: :class:`~app.models.User` :returns: Event data. :rtype: dict """ if not form: return {} event_image = None filename = form.event_image.data if filename and Image.objects(filename=filename).count() == 1: event_image = Image.objects().get(filename=filename) event_data = { 'title': form.title.data, 'slug': form.slug.data, 'location': form.location.data, 'start_time': form.start_time.data, 'end_time': form.end_time.data, 'published': form.published.data, 'short_description_markdown': form.short_description.data, 'long_description_markdown': form.long_description.data, 'is_recurring': form.is_recurring.data, 'facebook_url': form.facebook_url.data, 'image': event_image } if creator: event_data['creator'] = creator return event_data
def edit(event_id): """Edit an existing event. **Route:** ``/admin/events/edit/<event_id>`` **Methods:** ``GET, POST`` :param str event_id: The ID of the event to edit. """ try: event = Event.objects().get(id=event_id) except (DoesNotExist, ValidationError): flash('Cannot find event with id "{}"'.format(event_id), ERROR_FLASH) return redirect(url_for('.index')) form = EditEventForm(event, request.form) if request.method == 'POST' else \ EventsHelper.create_form(event, request) if form.validate_on_submit(): try: EventsHelper.update_event(event, form) except EventumError.GCalAPI as e: flash(e.message, ERROR_FLASH) return redirect(url_for('.index')) if form.errors: for error in form.errors: for message in form.errors[error]: flash(message, ERROR_FLASH) delete_form = DeleteEventForm() upload_form = UploadImageForm() images = Image.objects() return render_template('admin/events/edit.html', form=form, event=event, delete_form=delete_form, upload_form=upload_form, images=images)
def index(): """View and manage users. Whitelisted users are the only ones allowed to make user accounts. **Route:** ``/admin/users`` **Methods:** ``GET`` """ upload_form = UploadImageForm() whitelist_form = AddToWhitelistForm() return render_template( "admin/users/users.html", whitelist_form=whitelist_form, upload_form=upload_form, whitelist=Whitelist.objects(redeemed=False), users=User.objects(), images=Image.objects(), current_user=g.user, )
def create(): """""" form = CreateEventForm(request.form) if form.validate_on_submit(): try: EventsHelper.create_event(form, g.user) except GoogleCalendarAPIError as e: flash(e.message) return redirect(url_for('.index')) if form.errors: for error in form.errors: for message in form.errors[error]: flash(message) upload_form = UploadImageForm() delete_form = DeleteEventForm() images = Image.objects() return render_template('admin/events/create.html', form=form, delete_form=delete_form, upload_form=upload_form, images=images)
def add(): """Add and email to the whitelist. **Route:** ``/admin/whitelist/add`` **Methods:** ``POST`` """ form = AddToWhitelistForm(request.form) if form.user_type.data == 'fake_user': if form.validate_on_submit(): fake_id = str(uuid.uuid4()) fake_email = fake_id[:10] + "@fake-users.com" filename = form.fake_user_image.data try: fake_image = Image.objects().get(filename=filename) fake_user = User(email=fake_email, gplus_id=fake_id, name=form.name.data, user_type=form.user_type.data, image=fake_image) except Image.DoesNotExist: fake_user = User(email=fake_email, gplus_id=fake_id, name=form.name.data, user_type=form.user_type.data) fake_user.save() else: app.logger.warning(form.errors) else: user_exists = User.objects(email=form.email.data).count() != 0 if form.validate_on_submit() and not user_exists: wl = Whitelist(email=form.email.data, user_type=form.user_type.data) wl.save() else: app.logger.warning(form.errors) return redirect(url_for('users.index'))
def index(): images =Image.objects() form = UploadImageForm() return render_template('admin/media/media.html', images=images, form=form)
def view(): return str(Image.objects())
def index(): images = Image.objects() form = UploadImageForm() return render_template('admin/media/media.html', images=images, form=form)
def edit(post_id): """Edit an existing blog post. **Route:** ``/admin/posts/edit/<post_id>`` **Methods:** ``GET, POST`` :param str post_id: The ID of the post to edit. """ try: object_id = ObjectId(post_id) except InvalidId: return abort(404) try: post = BlogPost.objects().with_id(object_id) except (DoesNotExist, ValidationError): flash('Cannot find blog post with id {}.'.format(post_id), ERROR_FLASH) return redirect(url_for('.index')) if request.method == 'POST': form = CreateBlogPostForm(request.form) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects()] form.author.default = str(g.user.id) if form.validate_on_submit(): post.title = form.title.data post.author = User.objects.get(id=ObjectId(form.author.data)) post.slug = form.slug.data post.markdown_content = form.body.data post.images = [ Image.objects().get(filename=fn) for fn in form.images.data ] post.post_tags = Tag.get_or_create_tags(form.tags.data) if form.featured_image.data: post.featured_image = Image.objects().get( filename=form.featured_image.data) else: post.featured_image = None post.save() if post.published != form.published.data: if form.published.data: post.publish() flash('Blogpost published', MESSAGE_FLASH) else: post.unpublish() flash('Blogpost unpublished', MESSAGE_FLASH) if form.preview.data is True: return redirect(url_for('.preview', slug=post.slug)) upload_form = UploadImageForm() feat_img = post.featured_image.filename if post.featured_image else None form = CreateBlogPostForm(request.form, title=post.title, slug=post.slug, published=post.published, body=post.markdown_content, images=[image.filename for image in post.images], author=str(post.author.id), featured_image=feat_img, tags=post.post_tags) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects() ] form.author.default = str(g.user.id) images = [image for image in Image.objects() if image not in post.images] return render_template('admin/posts/edit.html', user=g.user, form=form, post=post, images=images, upload_form=upload_form)
def __call__(self, form, field): filename = '%s.' % field.data if Image.objects(filename__startswith=filename).count() != 0: raise ValidationError(self.message)
def edit(post_id): """Edit an existing blog post. **Route:** ``/admin/posts/edit/<post_id>`` **Methods:** ``GET, POST`` :param str post_id: The ID of the post to edit. """ try: object_id = ObjectId(post_id) except InvalidId: return abort(404) try: post = BlogPost.objects().with_id(object_id) except (DoesNotExist, ValidationError): flash('Cannot find blog post with id {}.'.format(post_id)) return redirect(url_for('.index')) if request.method == 'POST': form = CreateBlogPostForm(request.form) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects()] form.author.default = str(g.user.id) if form.validate_on_submit(): post.title = form.title.data post.author = User.objects.get(id=ObjectId(form.author.data)) post.slug = form.slug.data post.markdown_content = form.body.data post.images = [Image.objects().get(filename=fn) for fn in form.images.data] post.tags = form.tags.data if form.featured_image.data: post.featured_image = Image.objects().get(filename=form.featured_image.data) else: post.featured_image = None post.save() if post.published != form.published.data: if form.published.data: post.publish() flash('Blogpost published') else: post.unpublish() flash('Blogpost unpublished') return redirect(url_for('.index')) upload_form = UploadImageForm() featured_image = post.featured_image.filename if post.featured_image else None form = CreateBlogPostForm(request.form, title=post.title, slug=post.slug, published=post.published, body=post.markdown_content, images=[image.filename for image in post.images], author=str(post.author.id), featured_image=featured_image, tags=post.tags) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects()] form.author.default = str(g.user.id) images = [image for image in Image.objects() if image not in post.images] return render_template('admin/posts/edit.html', user=g.user, form=form, post=post, images=images, upload_form=upload_form, tags=post.tags)
def image_with_same_name(form,field): if Image.objects(filename=field.data).count() != 1: return ValidationError( message="Can't find image `%s` in the database" % field.data)