Ejemplo n.º 1
0
def form():
    Form = NameForm()
    name = None
    if Form.validate_on_submit():
        username = Form.name.data
        user = User.query.filter_by(username=username).first()
        if not user:
            user = User(username=username)
            db.session.add(user)
            db.session.commit()
            session["known"] = False
            if app.config.get("FLASKY_ADMIN"):
                result = send_email(app.config["FLASKY_ADMIN"],
                                    "New User",
                                    "mail/user",
                                    user=user)
                print("result", result)
        else:
            session["known"] = True
        session["name"] = name
        Form.name.data = ""
        # 使用重定向可以再刷新页面时不提示是否提交表单数据
        return redirect(url_for("form"))
    return render_template("form.html",
                           form=Form,
                           name=session.get("name"),
                           known=session.get("known"))
Ejemplo n.º 2
0
    def validate_on_submit(self):

        if not Form.validate_on_submit(self):
            return False
        failed = False
        user = User.query.filter_by(email=session["email"]).first()

        try:
            int(self.expenseID.data)

            if int(self.expenseID.data) < 1 and not failed:
                self.expenseID.errors.append(
                    "Expense ID must be greater than 0")
                failed = True

            expenseId = int(self.expenseID.data)
            #expense must be part of your household (can't delete other households expenses)
            if expenseId not in [
                    expense.id
                    for expense in db.session.query(Expense).join(User).filter(
                        User.hid == user.hid, Expense.uid == User.id).all()
            ] and not failed:
                self.expenseID.errors.append(
                    "Expense does not exist. Please enter an Expense ID on this page."
                )
                failed = True

        except ValueError:
            self.expenseID.errors.append("Expense ID must be an integer.")
            failed = True

        self.errors.append(self.expenseID.errors)
        return not failed
Ejemplo n.º 3
0
 def validate_on_submit(self):
     if not Form.validate_on_submit(self):
         return False
     user = User.query.filter_by(user_name = self.username.data).first()
     if user:
         self.username.errors.append('That username is already taken')
         return False
     return True
Ejemplo n.º 4
0
def index():
    name = None
    form = Form()
    if form.validate_on_submit():
        name = form.name.data
        form.name.data = ''

    return render_template('index.html', form=form, name=name)
Ejemplo n.º 5
0
def delete(id):
    item = Transcript.query.get_or_404(id)
    form = Form()

    if form.validate_on_submit():
        db.session.delete(item)
        db.session.commit()
        return redirect_for('transcript.index')

    return render_template('transcript/delete.html', item=item, form=form)
Ejemplo n.º 6
0
def index():
    form = Form()
    if form.validate_on_submit():
        send(dest_ip=form.destination_ip.data,
             port=form.port.data,
             src_ip=form.source_ip.data,
             payload=form.payload.data,
             count=form.count.data)
        return "Sent %d packet(s)." % form.count.data
    return render_template("index.html", form=form)
Ejemplo n.º 7
0
    def validate_on_submit(self):
        if not Form.validate_on_submit(self):
            return False

        user = User.query.filter_by(email=self.email.data.lower()).first()
        if user and user.check_password(self.password.data):
            return True
        else:
            self.email.errors.append("Invalid e-mail or password.")
            return False
Ejemplo n.º 8
0
def register():
    # 2.实例化表单类对象
    form = Form()
    print form.validate_on_submit()  # 表单验证+csrf
    if form.validate_on_submit():
        # 获取表单数据
        user = form.user.data # wtf 表单获取form.user.data form.表单对象的字段.data
        ps = form.pswd.data
        ps2 = form.pswd2.data
        print("*" * 50)
        print user, ps, ps2
        print("*" * 50)
    else:
        if request.method == 'POST':
            print(u'验证失败!!')
            flash(u'验证失败!!')
    flash(u'验证成功!!')
    flash(u'验证成功2!!')
    flash(u'验证成功23!!')
    return render_template('register.html', form=form) # 3.传表单对象给模板视图 WTF表单
Ejemplo n.º 9
0
def delete(title):
    page = WikiPage.query.filter(WikiPage.title == title).first_or_404()
    form = Form()

    if form.validate_on_submit():
        db.session.delete(page)
        db.session.commit()

        return redirect_for('wiki.index')

    return render_template('wiki/delete.html', page=page, form=form)
Ejemplo n.º 10
0
def index():
    form = Form()
    if form.validate_on_submit():
        userid = request.form["user"]
        if verify_user(userid):
            return redirect("/bookfood")
        else:
            flash("请注册")
            return render_template("login.html", form=form)
    else:
        return render_template("login.html", form=form)
Ejemplo n.º 11
0
 def validate_on_submit(self):
     if not Form.validate_on_submit(self):
         return False
     user = User.query.filter_by(user_name = self.username.data).first()
     if user is None:
         self.username.errors.append('Invalid username')
         return False
     if not user.check_password(self.password.data):
         self.password.errors.append('Invalid password')
         return False
     return True
Ejemplo n.º 12
0
def delete(id):
    item = Salad.query.get_or_404(id)
    form = Form()

    if form.validate_on_submit():
        item.delete()
        db.session.commit()

        return redirect_for('salad.index')

    return render_template('salad/delete.html', item=item, form=form)
Ejemplo n.º 13
0
def delete(id):
    page = WikiPage.query.get_or_404(id)
    form = Form()

    if form.validate_on_submit():
        db.session.delete(page)
        db.session.commit()

        return redirect_for('wiki.index')

    return {'page': page, 'form': form}
Ejemplo n.º 14
0
def delete(id):
    item = Salad.query.get_or_404(id)
    form = Form()

    if form.validate_on_submit():
        item.delete()
        db.session.commit()

        return redirect_for('salad.index')

    return render_template('salad/delete.html', item=item, form=form)
Ejemplo n.º 15
0
def delete(title):
    page = WikiPage.query.filter(WikiPage.title == title).first_or_404()
    form = Form()

    if form.validate_on_submit():
        db.session.delete(page)
        db.session.commit()

        return redirect_for('wiki.index')

    return render_template('wiki/delete.html', page=page, form=form)
Ejemplo n.º 16
0
def delete(id):
    item = CanonItem.query.get_or_404(id)
    form = Form()

    if form.validate_on_submit():
        db.session.delete(item)
        db.session.commit()

        return redirect_for('canon.index')

    return {'item': item, 'form': form}
Ejemplo n.º 17
0
def delete(id):
    item = CanonItem.query.get_or_404(id)
    form = Form()

    if form.validate_on_submit():
        db.session.delete(item)
        db.session.commit()

        return redirect_for('canon.index')

    return render_template('canon/delete.html', item=item, form=form)
Ejemplo n.º 18
0
def confirm_friend_request(id):
    form = Form()
    if form.validate_on_submit():
        profile = Profile.query.get_or_404(id)
        try:
            current_user.confirm_request(profile)
        except ValueError:
            abort(BAD_REQUEST_STATUS_CODE)
        db.session.commit()
        return redirect(url_for('bro.view_profile', id=id))
    abort(BAD_REQUEST_STATUS_CODE)
Ejemplo n.º 19
0
def delete(id):
    item = Salad.query.get_or_404(id)
    form = Form()

    if form.validate_on_submit():
        item.delete()
        db.session.commit()

        return redirect_for('salad.index')

    return {'item': item, 'form': form}
Ejemplo n.º 20
0
def index():
    form = Form()
    if form.validate_on_submit():
        send(
            dest_ip=form.destination_ip.data,
            port=form.port.data,
            src_ip=form.source_ip.data,
            payload=form.payload.data,
            count=form.count.data
        )
        return "Sent %d packet(s)." % form.count.data
    return render_template("index.html", form=form)
Ejemplo n.º 21
0
def logout():
    form = Form()
    if form.validate_on_submit():
        logout_user()
        if 'redirect_to' in session:
            redirect_to = session['redirect_to']
            session.pop('redirect_to', None)
        flash(gettext('Signed out successfully.'))
    else:
        flash(gettext('Invalid Action'), 'error')

    return redirect(url_for('index'))
Ejemplo n.º 22
0
    def validate_on_submit(self):
        if not Form.validate_on_submit(self):
            return False

        if self.to.data == -1:
            self.to.errors.append("Please choose a user to send to.")
            return False

        if len(self.memo.data) == 0 or len(self.memo.data) > 128:
            self.memo.errors.append(
                "Please enter a message of 128 characters or less.")
            return
Ejemplo n.º 23
0
 def validate_on_submit(self):
     if not Form.validate_on_submit(self):
         return False
     user_to_check = models.User.query.filter_by(
         username=self.username.data).first()
     if not user_to_check:
         self.username.errors.append("No user with this username exists")
         return False
     if not user_to_check.check_password(self.password.data):
         self.password.errors.append("Authentication failed")
         return False
     return True
Ejemplo n.º 24
0
def user_del(user_id):
    from flask_wtf import Form
    from lightningwolf_smp.models.user_query import UserQuery
    uq = UserQuery(db=db)
    user_object = uq.get_user(user_id)
    if user_object is None:
        abort(404)
    form = Form()
    if form.validate_on_submit():
        user_object.delete()
    else:
        flash(u'An error occurred while deleting the user', 'error')

    return redirect(url_for('user.user_list'))
Ejemplo n.º 25
0
def deactivate(user_id):
    form = Form(request.form)
    if form.validate_on_submit():
        u = User.query.get_or_404(user_id)
        u.activated = False
        db.session.commit()

        newsletter.unsubscribe_all(u)

        flash(
            'User has been deactivated and unsubscribed from all newsletter.')
    else:
        flash('Invalid CSRF Token')
    return redirect_back()
Ejemplo n.º 26
0
    def validate_on_submit(self):
        if not Form.validate_on_submit(self):
            return False

        user = models.User.query.filter_by(email=self.email.data).first()
        if user:
            self.email.errors.append("This email is already registered")
            return False

        user = models.User.query.filter_by(username=self.username.data).first()
        if user:
            self.username.errors.append("This username is already registered")
            return False

        return True
Ejemplo n.º 27
0
    def validate_on_submit(self):
        if not Form.validate_on_submit(self):
            return False

        isError = False

        if User.query.filter_by(email=self.email.data).first():
            self.email.errors.append("This email is already in use.")
            isError = True

        if User.query.filter_by(username=self.username.data).first():
            self.username.errors.append("This username is already in use.")
            isError = True

        return not isError
Ejemplo n.º 28
0
def deleteProduct(product_id):
	currentUser = getCurrentUser()
	product = session.query(Product).filter(Product.id == product_id).one()
	# Only all product deletion if the seller is the current user
	if matchesLoginUser(product.seller):
		form = Form()
		if form.validate_on_submit():
			session.delete(product)
			session.commit()
			return redirect(url_for('userProfile', 
				user_id = product.seller.id))
		else:
			return render_template('delete-product.html', 
				currentUser = currentUser, form = form, product = product)
	else:
		return redirect(url_for('home'))
Ejemplo n.º 29
0
def deleteUser(user_id):
	user = session.query(User).filter(User.id == user_id).one()
	# Only delete user if it matches the current user
	if matchesLoginUser(user):
		products = session.query(Product).filter(Product.seller == user).all()
		form = Form()
		if form.validate_on_submit():
			session.delete(user)
			if 'user_id' in login_session:
				del login_session['user_id']
			session.commit()
			return redirect(url_for('home'))
		else:
			return render_template('delete-user.html', currentUser = user, 
				form = form, user = user, products = products)
	else:
		return redirect(render_template('home'))
Ejemplo n.º 30
0
def deleteProduct(product_id):
    currentUser = getCurrentUser()
    product = session.query(Product).filter(Product.id == product_id).one()
    # Only all product deletion if the seller is the current user
    if matchesLoginUser(product.seller):
        form = Form()
        if form.validate_on_submit():
            session.delete(product)
            session.commit()
            return redirect(url_for('userProfile', user_id=product.seller.id))
        else:
            return render_template('delete-product.html',
                                   currentUser=currentUser,
                                   form=form,
                                   product=product)
    else:
        return redirect(url_for('home'))
Ejemplo n.º 31
0
def deleteReview(product_id, review_id):
	currentUser = getCurrentUser()
	product = session.query(Product).filter(Product.id == product_id).one()
	review = session.query(Review).filter(Review.id == review_id).one()
	# Only allow review deletion if reviers is the current user
	if matchesLoginUser(review.user):
		form = Form()
		if form.validate_on_submit():
			session.delete(review)
			session.commit()
			return redirect(url_for('product', product_id = product_id))
		else:
			return render_template('delete-review.html', 
				currentUser = currentUser, form = form, product = product, 
				review= review)
	else:
		return redirect(url_for('home'))
Ejemplo n.º 32
0
    def validate_on_submit(self):
        """

        :rtype: bool
        """
        if not Form.validate_on_submit(self):
            return False

        email = User.query.filter_by(email=self.email.data.lower()).first()
        username = User.query.filter_by(
            username=self.username.data.lower()).first()
        if username:
            self.username.errors.append("That username is already taken")
            return False
        if email:
            self.email.errors.append("That email is already taken")
            return False
        return True
Ejemplo n.º 33
0
    def validate_on_submit(self):
        """

        :rtype: bool
        """
        if not Form.validate_on_submit(self):
            return False

        email = User.query.filter_by(
            email=self.email.data.lower()).first()
        username = User.query.filter_by(
            username=self.username.data.lower()).first()
        if username:
            self.username.errors.append("That username is already taken")
            return False
        if email:
            self.email.errors.append("That email is already taken")
            return False
        return True
Ejemplo n.º 34
0
def deleteReview(product_id, review_id):
    currentUser = getCurrentUser()
    product = session.query(Product).filter(Product.id == product_id).one()
    review = session.query(Review).filter(Review.id == review_id).one()
    # Only allow review deletion if reviers is the current user
    if matchesLoginUser(review.user):
        form = Form()
        if form.validate_on_submit():
            session.delete(review)
            session.commit()
            return redirect(url_for('product', product_id=product_id))
        else:
            return render_template('delete-review.html',
                                   currentUser=currentUser,
                                   form=form,
                                   product=product,
                                   review=review)
    else:
        return redirect(url_for('home'))
Ejemplo n.º 35
0
def deleteUser(user_id):
    user = session.query(User).filter(User.id == user_id).one()
    # Only delete user if it matches the current user
    if matchesLoginUser(user):
        products = session.query(Product).filter(Product.seller == user).all()
        form = Form()
        if form.validate_on_submit():
            session.delete(user)
            if 'user_id' in login_session:
                del login_session['user_id']
            session.commit()
            return redirect(url_for('home'))
        else:
            return render_template('delete-user.html',
                                   currentUser=user,
                                   form=form,
                                   user=user,
                                   products=products)
    else:
        return redirect(render_template('home'))
Ejemplo n.º 36
0
    def validate_on_submit(self):
        if not Form.validate_on_submit(self):
            self.errors = self.consolidateErrorMessage()
            return False

        failed = False

        if self.receiver.data == -1:
            self.receiver.errors.append("Please choose a user to pay.")
            failed = True

        try:
            float(self.amount.data)

        except ValueError:
            self.amount.errors.append("Payment amount must be a number!")
            failed = True

        self.errors = self.consolidateErrorMessage()
        return not failed
Ejemplo n.º 37
0
def post_view(slug):
    q = filter_by_user(Post.query.filter(Post.slug==slug))
    post = q.one_or_none()
    if post is None:
        return render_page_template(
        context={"post": None},
        template="site/blog/post.html"
        )
    form = Form()
    if post.enable_comments and current_settings.enable_comments:
        form = create_comment_form()
        if form.validate_on_submit():
            post.comments.append(Comment(**form.data))
            db.session.commit()
            flash("Your comment was sent")
            return redirect(url_for('canella-blog.post', slug=post.slug))
    return render_page_template(
        context={"post": post, 'comment_form':form},
        template="site/blog/post.html"
    )
Ejemplo n.º 38
0
def activate(user_id):
    ''' Activates the user account and sends a welcome message '''

    form = Form(request.form)
    if form.validate_on_submit():
        u = User.query.get_or_404(user_id)
        u.activated = True
        db.session.commit()

        msg = Message("Welcome to the QFin Club!", recipients=[u.email])
        msg.html = render_template('members/email_welcome.html', user=u)
        mail.send(msg)

        # Subscribe to mailinglists
        newsletter.subscribe_all(u)

        flash(
            'User has been activated, a welcome message has been sent and he has been subscribed to all newsletters.'
        )
    else:
        flash('Invalid CSRF Token')
    return redirect_back()
Ejemplo n.º 39
0
def user_filter():
    from lightningwolf_smp.models.user_pager import UserPager
    from lightningwolf_smp.blueprints.configs.user import configuration
    pager = UserPager(page=1)
    pager.initialize(configuration=configuration)

    action = request.args.get('action', '')
    if action == '_reset':
        from flask_wtf import Form
        form = Form()
    else:
        from lightningwolf_smp.forms.user import FormUsernameFilter
        form = FormUsernameFilter()

    if form.validate_on_submit():
        if action == '_reset':
            pager.reset_filter_data()
        else:
            pager.set_filter_data({'username': form.data['username']})
    else:
        flash(u'An error occurred in filter form', 'error')

    return redirect(url_for('user.user_list'))
Ejemplo n.º 40
0
    def validate_on_submit(self):
        if not Form.validate_on_submit(self):
            self.errors = self.consolidateErrorMessage()
            return False

        failed = False

        if self.pwd.data != self.confirmPwd.data:
            self.pwd.errors.append("Your passwords don't match.")
            failed = True

        if not bool(self.key.data) and not bool(self.householdName.data):
            self.key.errors.append(
                "You must either join a household or create a new one.")
            failed = True

        if bool(self.key.data) and bool(self.householdName.data):
            self.key.errors.append(
                "You cannot both join and create a household, choose one.")
            failed = True

        # Ensure the provided user exists if user opts to join:
        if bool(self.key.data) and not bool(self.householdName.data):
            household = Household.query.filter_by(
                key=self.key.data.lower()).first()
            if not household:
                self.key.errors.append(
                    "That household association key is invalid.")
                failed = True

        user = User.query.filter_by(email=self.email.data.lower()).first()
        if user:
            self.email.errors.append("That email is already taken.")
            failed = True

        self.errors = self.consolidateErrorMessage()
        return not failed
Ejemplo n.º 41
0
    def validate_on_submit(self):
        if not Form.validate_on_submit(self):
            self.errors = self.consolidateErrorMessage()
            return False
        failed = False
        #name field
        if len(self.name.data) > 64:
            self.name.errors.append("Expense name must not exceed 64 characters.")
            failed = True
        #amount field
        try:
            #amount must be a number
            float(self.amount.data)
            #amount field positive, non-zero
            if float(self.amount.data) <= 0:
                self.amount.errors.append("Expense amount must be greater than 0.")
        except ValueError:
            self.amount.errors.append("Expense amount must be a number.")
            failed = True

        #date field
        try:
            minDate = datetime.date(2000, 1, 1)
            dateVal = datetime.datetime.strptime(self.date.data, "%Y-%m-%d")

            if dateVal.date() < minDate:
                self.date.errors.append("Expense date must be after " + str(minDate) + ".")
                failed = True

        except ValueError:
            self.date.errors.append("Invalid expense date format. Please use YYYY-MM-DD.")
            failed = True

        #participant field
        #make sure there is at least one non expense owner (current user) participant
        nonOwnerParticipant = False
        user = User.query.filter_by(email=session["email"]).first()
        householdMembers = User.query.filter(User.hid == user.hid).all()
        i = 0 #index for household members
        for participant in self.participant.data:
            if participant["checkBox"] == True:
                if user.id != householdMembers[i].id:
                    nonOwnerParticipant = True
                    break
            i += 1
        if not nonOwnerParticipant:
            self.participant.errors.append("You must add at least one participant besides the currently logged in user.")
            failed = True

        try:
            #make sure all participant amount values can be cast as float
            for participant in self.participant.data:
                if participant["checkBox"] == True:
                    float(participant["amount"])

            #make sure all participants amounts are greater than 0.00
            amounts = []
            negativeParticipantAmountFlag = False
            for participant in self.participant.data:
                if participant["checkBox"] == True:
                    if float(participant["amount"]) <= 0.0:
                        negativeParticipantAmountFlag = True
                    amounts.append(round(float(participant["amount"]), 2))
            if negativeParticipantAmountFlag:
                self.participant.errors.append("All Participant amounts must be greater than 0.")
                failed = True

            #sum of participant amounts must equal expense amount
            total = 0.00
            for amount in amounts:
                total += round(float(amount), 2)
            if round(float(self.amount.data), 2) != round(float(total), 2):
                self.participant.errors.append("Participant amounts must add up to the expense total. Please correct the amounts or use the auto-split button.")
                failed = True
        except ValueError:
            self.participant.errors.append("Participant amount must be a number.")
            failed = True

        self.errors = self.consolidateErrorMessage()
        return not failed
Ejemplo n.º 42
0
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"))
Ejemplo n.º 43
0
def delete_func(model_name, model_identifier, is_bootbox=False):
    try:
        model_identifier_int = int(model_identifier)
    except ValueError:
        abort(404)

    try:
        v = app.config['EDITABLE_MODELS'][model_name]
    except KeyError:
        abort(404)

    if not(('is_deleteable' in v) and v['is_deleteable']):
        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))

    model_class = get_model_class(model_classpath, model_name)

    filter_by_kwargs = {
        identifier_field_name: model_identifier_int,
        'active': True}
    model = None

    if app.config.get('USE_SESSIONSTORE_NOT_DB'):
        model_dict = ((
            session.get(model_name, [])
            and len(session[model_name]) >= (model_identifier_int+1))
            and session[model_name][model_identifier_int]
            or None)

        if model_dict:
            model = model_class(**model_dict)
    else:
        model = (
            model_class.query
                       .filter_by(**filter_by_kwargs)
                       .first())

    if not model:
        abort(404)

    form = Form()

    if form.validate_on_submit():
        title = getattr(model, title_field_name)
        model_name_friendly = model_name.replace('_', ' ').title()

        try:
            if app.config.get('USE_SESSIONSTORE_NOT_DB'):
                del session[model_name][model_identifier_int]
            else:
                model.delete()

            app.logger.info('{0} deleted: {1}; user: {2}'.format(
                model_name_friendly, title, current_user))

            if is_bootbox:
                return Response('OK')
            else:
                flash(
                    "{0} has been deleted.".format(title),
                    'success')
        except IntegrityError:
            db.session.rollback()

            if is_bootbox:
                return Response('ERROR')
            else:
                flash("Error deleting {0}.".format(title), 'danger')
    else:
        if is_bootbox:
            return Response('ERROR')
        else:
            flash_errors(form)

    return redirect(url_for("public.home"))
Ejemplo n.º 44
0
def audioArchiv():
    form = Form()
    if form.validate_on_submit():
        return form.dt.data.strftime('%Y-%m-%d')
    return render_template('audioArchiv.html', form=form,shows=shows)
Ejemplo n.º 45
0
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"))
Ejemplo n.º 46
0
def delete_func(model_name, model_identifier, is_bootbox=False):
    try:
        model_identifier_int = int(model_identifier)
    except ValueError:
        abort(404)

    try:
        v = app.config['EDITABLE_MODELS'][model_name]
    except KeyError:
        abort(404)

    if not (('is_deleteable' in v) and v['is_deleteable']):
        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))

    model_class = get_model_class(model_classpath, model_name)

    filter_by_kwargs = {
        identifier_field_name: model_identifier_int,
        'active': True
    }
    model = None

    if app.config.get('USE_SESSIONSTORE_NOT_DB'):
        model_dict = (
            (session.get(model_name, []) and len(session[model_name]) >=
             (model_identifier_int + 1))
            and session[model_name][model_identifier_int] or None)

        if model_dict:
            model = model_class(**model_dict)
    else:
        model = (model_class.query.filter_by(**filter_by_kwargs).first())

    if not model:
        abort(404)

    form = Form()

    if form.validate_on_submit():
        title = getattr(model, title_field_name)
        model_name_friendly = model_name.replace('_', ' ').title()

        try:
            if app.config.get('USE_SESSIONSTORE_NOT_DB'):
                del session[model_name][model_identifier_int]
            else:
                model.delete()

            app.logger.info('{0} deleted: {1}; user: {2}'.format(
                model_name_friendly, title, current_user))

            if is_bootbox:
                return Response('OK')
            else:
                flash("{0} has been deleted.".format(title), 'success')
        except IntegrityError:
            db.session.rollback()

            if is_bootbox:
                return Response('ERROR')
            else:
                flash("Error deleting {0}.".format(title), 'danger')
    else:
        if is_bootbox:
            return Response('ERROR')
        else:
            flash_errors(form)

    return redirect(url_for("public.home"))