Lone Creation
Lone Creation

Reputation: 69

How to change routes in Flask?

I have watched a tutorial on Flask and I can't seem to understand how does this code work

def my_home():
    return render_template("./index.html")

@app.route('/<string:page_name>')
def html_page(page_name):
    return render_template(page_name)```

Specifically /<string:page_name> is confusing to me, how does it understand what is page_name and redirect to that page? Thank you!

Upvotes: 0

Views: 4263

Answers (2)

Maximilian Kromer
Maximilian Kromer

Reputation: 11

/<string:page_name>

means that Flask expects a customised string after your domain i.e.

www.yourdomain.com/anycustomisedstring

/<data_type:your_variable_name>  i.e. /<integer:page_number>

in this case, your variable is passed as a parameter to your function. This function returns the site that is passed in the URL as a string

Upvotes: 1

justahuman
justahuman

Reputation: 637

The answer to this is in the magic of decorators and not flask itself. A decorator is a high level function which accepts a function and manipulates it accordingly. See the following example:

def route(func, user_path):
    # internal flask mechanisms here
    def callback(user_path):
        return http.route(user_path, func)
    return callback

@route("hello_world")
def render():
    return "Hello World"

The decorator is taking your function as an input and performing some actions to correlate the path with your given input. This can obviously be used for many other purposes. For example, flask also allows an additional decorator to define the type of request allowed for the function, such as GET, POST, etc.

To answer your question, flask is accepting a URL parameter and generating the page based on that given parameter. This is known as dynamic routing and is used for database query purposes based on the route (though the given example is trivial). So if someone goes to page_name "John", you can use that value and template it in your html to dynamically say hi to John (and whomever else).

Upvotes: 3

Related Questions