def post(self, obj_id=None): self.set_object(obj_id) self.extra() current_app.logger.info( 'POSTED========================================') if self.form.validate_on_submit(): current_app.logger.info( 'VALIDATED========================================') if self.action == 'Edit': log_orig = log_change(self.obj) self.pre_post() self.form.populate_obj(self.obj) self.post_post() log_change(log_orig, self.obj, self.log_msg) else: self.pre_post() self.form.populate_obj(self.obj) self.post_post() db.session.add(self.obj) log_new(self.obj, self.log_msg) db.session.commit() self.post_submit() flash(self.success_msg, 'success') if self.redirect: return redirect(url_for(**self.redirect)) log_form(self.form) flash_form_errors(self.form) return render_template(self.template, **self.context)
def add_page(): form = AddPageForm() for field in form: print(f"{field.name}: {field.data}") form.parent_id.choices = [(0, '---')] + [(p.id, f"{p.title} ({p.path})") for p in Page.query.all()] form.user_id.choices = [(u.id, u.username) for u in User.query.all()] form.notify_group.choices = [ ('', ''), ('all', 'All') ] + current_app.config['SUBSCRIPTION_GROUPS'] + [ ('discord', 'Discord Only') ] if form.validate_on_submit(): parentid = form.parent_id.data if form.parent_id.data else None page = Page( title=form.title.data, slug=form.slug.data, template=form.template.data, parent_id=parentid, cover=form.cover.data, banner=form.banner.data, body=form.body.data, notes=form.notes.data, summary=form.summary.data, author_note=form.author_note.data, author_note_location=form.author_note_location.data, sidebar=form.sidebar.data, tags=form.tags.data, user_id=current_user.id, notify_group=form.notify_group.data, published=form.published.data, ) pdate = form.pub_date.data ptime = form.pub_time.data local_tz = form.timezone.data if form.timezone.data else current_user.timezone if pdate and ptime: page.set_local_pub_date(f"{pdate} {ptime}", local_tz) page.set_path() db.session.add(page) db.session.commit() if form.notify_subs.data: page.notify_subscribers(form.notify_group.data) flash("Page added successfully.", "success") log_new(page, 'added a page') Page.set_nav() return redirect(url_for('admin.edit_page', id=page.id)) if form.errors: flash("<b>Error!</b> Please fix the errors below.", "danger") return render_template('admin/page-edit.html', form=form, tab='pages', action='Add', page=Page.query.filter_by(slug='admin').first())
def post(self): self.extra() self.form = DeleteObjForm() if self.form.validate_on_submit(): self.obj = self.model.query.filter_by( id=self.form.obj_id.data).first() log_new(self.obj, self.log_msg) db.session.delete(self.obj) db.session.commit() flash(self.success_msg, 'success') else: flash('Failed to delete {self.model.__name__}!', 'danger') log_form(self.form) #flash_form_errors(self.form) return redirect(url_for(**self.redirect))
def add_tag(): page = Page.query.filter_by(slug='admin').first() form = AddTagForm() if form.validate_on_submit(): if form.validate_tag(form.name.data): tag = Tag(name=form.name.data) db.session.add(tag) db.session.commit() flash("Tag added successfully.", "success") log_new(tag, 'added a tag') return redirect(url_for('admin.tags')) else: flash("<b>Error!</b> That tag already exists.", "danger") return render_template('admin/tag-edit.html', form=form, tab='tags', action='Add', page=page)
def add_user(): page = Page.query.filter_by(slug='home').first() form = AddUserForm() form.timezone.choices = [(t, t) for t in pytz.common_timezones] if form.validate_on_submit(): user = User() form.populate_obj(user) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash(f"{user.username.upper()} was added successfully!", "success") log_new(user, 'added a user') return redirect(url_for('admin.users')) return render_template('admin/user-edit.html', form=form, tab='users', action='Add', page=page)
def records(day=None): form = RecordForm() if form.validate_on_submit(): record = Record() current_app.logger.debug('VALIDATED') for field in form: current_app.logger.debug(f'{field.name}: {field.data}') form.populate_obj(record) record.words = form.end_words.data - form.start_words.data record.words_per_minute = int( record.words / record.minutes) if record.minutes else None current_app.logger.debug(repr(record)) db.session.add(record) db.session.commit() log_new(record, 'added a record') flash('Record added!', 'success') return redirect(url_for('admin.records', day=day)) page = Page.query.filter_by(slug='admin').first() today = datetime(int(day[0:4]), int(day[4:6]), int( day[-2:])) if day else datetime.utcnow() current_app.logger.debug(f'here is day: {today}') today = datetime.combine(today, time(0, 0, 0)) end_date = today.date() prev_month = today + relativedelta(months=-1) start_date = prev_month.date() chart_records = [] #records = Record.query.filter(Record.date >= day, Record.date < next_month).order_by(desc('created')).all() records = Record.query.filter(Record.date >= prev_month, Record.date <= today).order_by( desc('created')).all() total_query = db.session.query(Record, db.func.sum(Record.words).label('data')) stats = { 'week': total_query.filter(Record.date >= (today - timedelta(days=7)), Record.date <= today).all()[0].data, 'month': total_query.filter(Record.date >= (today - timedelta(days=30)), Record.date <= today).all()[0].data, 'year': total_query.filter(Record.date >= (today - timedelta(days=365)), Record.date <= today).all()[0].data, } #stats['week'] = stats['week'].data if stats['week'] else 0 #stats['month'] = stats['month'].data if stats['month'] else 0 #stats['year'] = stats['year'].data if stats['year'] else 0 stats['week_avg'] = int(stats['week'] / 7) if stats['week'] else 0 stats['month_avg'] = int(stats['month'] / 30) if stats['month'] else 0 stats['year_avg'] = int(stats['year'] / 365) if stats['year'] else 0 best_query = db.session.query(Record, db.func.sum( Record.words).label('best')).group_by( Record.date).order_by(desc('best')) stats['week_best'] = best_query.filter( Record.date >= (today - timedelta(days=7)), Record.date <= today).first() stats['week_best'] = stats['week_best'].best if stats['week_best'] else 0 stats['month_best'] = best_query.filter( Record.date >= (today - timedelta(days=30)), Record.date <= today).first() stats[ 'month_best'] = stats['month_best'].best if stats['month_best'] else 0 stats['year_best'] = best_query.filter( Record.date >= (today - timedelta(days=365)), Record.date <= today).first() stats['year_best'] = stats['year_best'].best if stats['year_best'] else 0 current_app.logger.debug(datetime.utcnow().date()) stats['today'] = Record.words_by_day(today.date()) while (prev_month <= today): chart_records += [Record.words_by_day(prev_month)] prev_month += timedelta(days=1) return render_template( 'admin/records.html', tab='records', chart_records=chart_records, records=records, page=page, form=form, start_date=start_date, end_date=end_date, stats=stats, )
def submit_comment(): form = AuthenticatedCommentForm( ) if current_user.is_authenticated else CommentForm() if form.validate_on_submit(): current_app.logger.debug(request.form) captcha_data = { 'secret': current_app.config['RECAPTCHA_SECRET'], 'response': request.form.get('token'), } resp = requests.post('https://www.google.com/recaptcha/api/siteverify', captcha_data) response_data = resp.json() current_app.logger.debug(response_data) if current_app.config.get('DEVELOPMENT'): response_data['success'] = True #REMOVE if response_data.get('success'): form.reply_id.data = form.reply_id.data if form.reply_id.data else None form.page_id.data = form.page_id.data if form.page_id.data else None form.product_id.data = form.product_id.data if form.product_id.data else None comment = Comment() form.populate_obj(comment) current_app.logger.debug(f'REPLY ID: {comment.reply_id}') comment.ip = request.remote_addr if current_user.is_authenticated: comment.user_id = current_user.id comment.name = current_user.display_name() comment.email = current_user.email db.session.add(comment) db.session.commit() log_new(comment, 'added a comment') flash('Comment added.', 'success') comment.notify() # notify admin if comment.email: subscriber = Subscriber.query.filter_by( email=comment.email).first() if not subscriber: subscriber = Subscriber(first_name=comment.name, email=comment.email, subscription=',Comment Replies,') if form.subscribe.data: subscriber.subscription += ','.join([ i[0] for i in current_app.config['SUBSCRIPTION_GROUPS'] ]) + ',' db.session.add(subscriber) db.session.commit() if form.subscribe.data: log_new(subscriber, 'subscribed') flash('Subscribed!', 'success') subscriber.welcome() else: log_orig = log_change(subscriber) subscriber.subscription = ',Comment Replies,' if form.subscribe.data: subscriber.subscription += ','.join([ i[0] for i in current_app.config['SUBSCRIPTION_GROUPS'] ]) + ',' log_change(log_orig, subscriber, 'updated subscriptions') db.session.commit() flash('You are already subscribed!', 'info') else: if form.subscribe.data: flash( 'You must provide an email address to subscribe. Please <a href="/subscribe">subscribe here</a> instead.', 'info') comment.notify_reply() # Notify commenter replied to else: flash( 'Unable to save comment. Recaptcha flagged you as a bot. If you are not a bot, please try submitting your comment again.', 'danger') return redirect(request.referrer)