DEV Community

KetanIP
KetanIP

Posted on • Updated on • Originally published at ketaniralepatil.com

Routing In Flask. 🍾

In this post we will learn about routing in flask. Its pretty easy.

Fixed Routes

To create routes for your pages like about , contact and so on, we use this kind of routing when we have a permanent route.

@app.route('/contact-us')
def ContactUs():
    return "Contact Us Page"

@app.route('/about-us/')
def ContactUs():
    return "About Us Page"
Enter fullscreen mode Exit fullscreen mode

Creating fixed URLs is so damn simple. You might have spotted that in contact us page there was no trailing slash but in contact us we used it. We can use both, but keep in mind when we don't use trailing slash it will give a 404 error to people who visit the traling slash page . For Example it will give a 404 when a person visits \contact-us\ but will server page on \contact-us.

If you use the one URL pattern with trailing backlash like \about-us\ it will redirect users from \about-us to \about-us\ and thus preventing mess.

Dynamic Routes

In this section we will learn about dynamic routing. Dynamic routing means getting dynamic data in URL and then using it.

In Flask you can have use following converters to convert dynamic input from the URL.

  1. string
  2. int
  3. float
  4. path ( It is simple a string but also accepts shashles in the URL)
  5. uuid

You may get data from URL without this parameters but is recommended to use.

Let's now see some examples:

@app.route('dynamicurl/<varible_name>/')
def DynamicUrl(varible_name):
    return str(varible_name)
Enter fullscreen mode Exit fullscreen mode

In above you may have seen that we pass the varible used in dynamic URL to the function and its how it is done, and previously I have talked about converters lets see how to use them,

@app.route('dynamicurl/<str:varible_name>/')
def DynamicUrl(varible_name):
    return varible_name
Enter fullscreen mode Exit fullscreen mode

It will convert the given input in string and will pass it to the function. You may try and use other converters on your own.

Hope you like it. 😊

Bye. 😍


Read it on my new website Routing in Flask it will really support me.

Top comments (0)