Python: How are Flask dynamic routes implemented?

Asked

Viewed 558 times

0

I started to study a little bit about web development with Flask. The framework treats dynamic components of the URL as follows:

@app.route('/<comp_dinamico>')
def page(comp_dinamico):
    # codigo
    return '%s' % comp_dinamico

What I wanted to understand is how to substring in '/<comp_dinamico>' becomes a variable. Or if this is not a variable, I would like to understand what it is. I thank you already.

  • You want to create your own framework is that it? Because if it’s not there’s no point in understanding how the nucleus works until it gets to this point, now if it’s got any sense.

  • "Doesn’t it make sense to understand how it works"? Wrong - one should not use things "why yes" - it is good to understand why it works yes - only it is not necessary to know how to do the same.

  • I just wanted to understand how it works out of curiosity

1 answer

1


Flask breaks down your URL into parts for functions that match it. For example, let’s say you have a URL to view a user’s data which is /user/1.

Declare a match match match for that URL would look like this:

@app.route('/user/<user_id>')
def my_user(user_id):
    pass

Knowing that this developer is a match for your route, he injects the URL part with the dynamic value into its parameters.

This pattern is found in various frameworks like, Django, Laravel, etc.

Usually it is use of regular expressions that provide this functionality.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.