Build your first Flask Web App; Part 2

Photo by David Clode on Unsplash

Build your first Flask Web App; Part 2

setting up dynamic routes in flask

ยท

2 min read

Table of contents

It's been some time since the first part of building a simple web app with Flask went live, but it's finally here. Let's get right into it!

Before we get started though, I'd like to point out that the previous code has been refactored and the datetime expressions are now grouped into one function which are then called by individual routes. The function is show below:

def dateTime():
    hour = datetime.datetime.now().hour
    minute = datetime.datetime.now().minute
    second = datetime.datetime.now().second
    day = datetime.datetime.now().isoweekday()
    month = datetime.datetime.now().month
    year = datetime.datetime.now().year
    current = datetime.datetime.now().year
    return hour, minute, second, day, month, year, current

With that out of the way, let's get to learning how we can set up dynamic routing on our web app. Python's Flask allows for dynamic routes to be set up when we use special angle brackets (< and >) in the app decorator. This would look something like so:

@app.route('/user/<name>')
def greet(name):
    ...

The string contained in the decorator is a variable and that variable can then be inputted into our function in order to set up dynamic functionality based on the given input. Our new route decorator with the code refactored would look something like this:

@app.route('/user/<name>')
def greet(name):
    x = dateTime()
    return render_template('index.html', name=name, hour=x[0], current=x, day=x, 
    date=date, month=x, days=days, months=months, year=x, minute=x, second=x, 
    suffix=dateSuffix)

What this means is that whenever a user navigates to /user/alice or /user/bob, the user sees a dynamic content rendered in response to the value of that variable.

Additional resources

๐Ÿ”— Check out Flask's official documentation: https://flask.palletsprojects.com/en/2.1.x/

๐Ÿ”— Reading- Flask Web Development: Developing Web Applications with Python

๐Ÿ”— Video demo

Thank you for reading my post. If you are interested, here is a link to my other blog:
๐Ÿ•ธ How the web works ๐Ÿ•ธ Building your first web app with Flask

Lastly, I have summarized the code snippets we learned today in this GitHub repository.

Finally, the outro! I hope you were able to get a basic understanding of how dynamic routes work in Flask in this short and sweet example. Unto the next one! ๐Ÿฅ‚

ย