I am a newbie to FLASK.
I am creating an e-commerce site in flask and I want to create multiple routes dynamically for same function and pass data which is fetched on the basis of Unique ID to single template in FLASK.
Let me explain it.
I have a table in DB as below:
id | category | slug |
---|---|---|
1 | cat1 | slug1 |
2 | cat2 | slug2 |
3 | cat3 | slug3 |
4 | cat4 | slug4 |
my python code is:
for (data in db):
@app.route('/data["slug"]')
def product_display(data["id"]):
id = data["id"]
products = fetch_products(id)
return render_template('products.html', products=products)
Please let me know if this code will work or not. If no then what should be the logic?
Thanks in advance.
Advertisement
Answer
I think your asking for how to use variables in routes?
@app.route('/<slug>')
def product_display(slug):
category = Category.query.filter_by(slug=slug).first_or_404()
products = Product.query.filter_by(category_id=category.id).all()
return render_template('products.html', category=category, products=products
Read up more on route variables in the docs
Generating links to all categories
You comment mentions ‘ that variable should be coming from for loop of data fetched from DB’ the best way I can parse that you want, say, a listing of all current categories (like a navigation bar in an online shop)
You might add a second route:
@app.route('/all-categories')
def all_categories():
categories = Category.query.all()
return render_template('all_categories.html', categories=categories)
Then in your all_categories.html
you would ‘build’ the urls to the first route:
<ul>
{% for category in categories %}
<li><a href="{{ url_for('product_display', slug=category.slug) }}">{{ category.slug }} (or title )</li>
{% endfor %}
</ul>
So both routes work together to get that ‘looped data’ from the database