[Flask] Creating table only if its not created for user already

Ziirish ziirish at ziirish.info
Tue Mar 7 11:21:38 EST 2017


It would be better if you showed us some of your tries and/or error messages.
Regarding the latest emails you sent it looks like you want us to do your job...

Anyway, the "if" you are looking for is probably something like:


    package = Package.query.filter_by(
        student_id=student_id, stripe_id = customer.id,
        student_email=request.form['stripeEmail'], is_active=True,
        package_type='yearlyrec', subscription_id=subscription.id
    ).first()

    if not package:
        package = Package(...)
        dbase.session.add(package)
        dbase.session.commit()



* On Tuesday, March 07, 2017 at 04:01 PM +0000, Anonymous Coder <anonymouscodar at gmail.com> wrote:
> I was trying to find a way to process/commit a model table for view only if
> it doesn't exists already. But I couldn't find the way to do it. I tried
> if/else but it doesn't create model at all if I try it that way. Following
> is view and I need to create sqlalchymy table only if it doesn't exist
> alrady.
> 
> @app.route('/yearlychargedrec', methods=['GET', 'POST'])
> def yearly_charged_rec():
>     if not user_authorized():
>         return redirect('/')
> 
>     current_package = Package.query.all()
> 
>     if request.method == 'POST':
>         data = get_profile_data(session['auth_token'])
>         profile_data = data['StudentProfile']
>         student = get_profile_data(session['auth_token'])['StudentProfile']
> 
>         stripe_token = request.form['stripeToken']
>         email = request.form['stripeEmail']
>         customer = stripe.Customer.create(
>             email=email,
>             source=request.form['stripeToken']
>         )
>         try:
>             subscription = stripe.Subscription.create(
>                 customer=customer.id,
>                 plan="yearlyrec",
>             )
>             student_id = profile_data.id
>             student.stripe_customer_id = customer.id
>             student.stripe_subscription_id = subscription.id
> 
>             package = Package(
>                 student_id=student_id,
>                 stripe_id = customer.id,
>                 student_email=request.form['stripeEmail'],
>                 is_active=True,
>                 package_type='yearlyrec',
>                 subscription_id=subscription.id
>             )
>             dbase.session.add(package)
>             dbase.session.commit()
> 
>         except stripe.error.CardError as e:
>             body = e.json_body
>             err = body['error']
> 
>     return render_template('/profile/charge/monthlycharge.html',
> current_package=current_package)
> 
> Please advise.


More information about the Flask mailing list