Friday, July 30, 2021

How can we set restrictions on page in flask app?

 if we want to the user had to login to view the page.

we can use this decorator   @login_required to enforce only login user can access the page.

@app.route('/private')
@login_required
def private_page():
purchase_form = PurchaseItemForm()
if request.method == "POST":
purchased_item = request.form.get('purchased_item')
p_item_object = Item.query.filter_by(name=purchased_item).first()
if p_item_object:
if current_user.can_purchase(p_item_object):
p_item_object.buy(current_user)
flash(f"Congratulations! You purchased {p_item_object.name} for {p_item_object.price}$", category='success')
else:
flash(f"Unfortunately, you don't have enough money to purchase {p_item_object.name}!", category='danger')
return redirect(url_for('private_page'))
if request.method == "GET":
items = Item.query.filter_by(owner=None)
for item in items:
print(item.name)
return render_template('market.html', items=items, purchase_form=purchase_form)

No comments:

Post a Comment