Search code examples
pythonflaskurl-routing

How create friendly url in Flask?


How create friendly url in Flask?

What would be written in the route

/

And the user received(Url is constructed by categories from the database) /machines/cars/modern/Lexus LX570

Is it possible to do this and how to write this?

Solution1:

Redirect 302

/product/<int:id_product> redirect to second route(get in databases) /machines/cars/modern/Lexus LX570

Solution2: Three url and one function for get id product and other data of database

@app.route('/')
def index():
    #use function for get data in database

@app.route('/<productName>')
def product(productName):
    #use function for get data in database


@app.route('/<path:fullPath>/<productName>')
def product_with_categories(fullPath,productName):
    #use function for get data in database

Solution

  • You can try something like that :

    from flask import make_response, url_for, redirect, abort
    
    @app.route('/<int:id_product>')
    def product(id_product):
        # Load you path with id_product to get nice url (in database)
        if id_product == 123:
            path = '/machines/cars/modern/Lexus LX570'
        else:
            abort(404)
        return redirect(url_for('product_friendly_url', product_category_hierarchy=path))
    
    @app.route('/<path:product_category_hierarchy>')
    def product_friendly_url(product_category_hierarchy):
        # Retrieve product from his product_category_hierarchy (in database)
        product_item = {'id': 123, 'product_category_hierarchy': product_category_hierarchy, 'blabla': 'test'}
        return make_response(str(product_item))
    

    Call /123 in your browser will redirect (302) you to '/machines/cars/modern/Lexus LX570' and print :

    {'id': 123, 'product_category_hierarchy': 'machines/cars/modern/Lexus LX570', 'blabla': 'test'}