LearninBits

Understanding Flask Routes and URLs

Hello there, awesome people! 👋

Remember building your first Flask web app? You know, the one that greeted the whole world with a “Hello, World!” message? Today, we’re going to make that app even smarter and more interactive. We’ll talk about Flask routes and URLs.

Curious? Let’s get started!

What Are Routes?

Picture a road map. You have starting points, destinations, and routes that connect them. In a Flask app, routes are like those roads, guiding users from one page to another. A URL (Uniform Resource Locator) is like a specific address on that road map.

Basic Routing in Flask

Remember the @app.route(“/”) line in our first Flask app? That was a route! It told Flask what to display when someone visits the homepage. Here’s how it looks:

@app.route("/")

def home():

    return "This is the home page."

Just like you can have many roads in a city, you can have many routes in a Flask app. Want a page for blog posts? Easy!

@app.route("/blog")

def blog():

    return "Welcome to my blog!"

Route Parameters

Let’s say you have a blog, and you want each post to have its own page. You don’t need to create a new route for every post. That would be like building a new road for every house! Instead, you can use route parameters:

@app.route("/post/<post_id>")

def show_post(post_id):

    return f"Showing blog post {post_id}"

Now, if you visit `/post/1`, it will display “Showing blog post 1”. Go to `/post/42`, and it shows “Showing blog post 42”. Cool, right?

HTTP Methods

Think of HTTP methods like different types of interactions you can have with a webpage. The most common ones are GET (viewing a page) and POST (submitting data).

Here’s how to handle these in Flask:

@app.route("/login", methods=['GET', 'POST'])

def login():

    if request.method == 'POST':

        return "Logging in..."

    else:

        return "This is the login page."

URL Converters

Remember the /post/<post_id> route? What if post_id should only be a number? You can specify that with URL converters:

@app.route("/post/<int:post_id>")

def show_post(post_id):

    return f"Showing blog post {post_id}"

Now, /post/abc won’t work, but /post/123 will!

Practical Example: Building a Simple Bookstore Web App

Alright, enough theory. Let’s put our new routing knowledge to the test by creating a basic bookstore web app. We’ll use Flask routes to create different pages for our app.

Step 1: Setting Up the Basic Structure

First, create a new Python file named `bookstore_app.py`. We’ll add the initial code to get our Flask app up and running.

from flask import Flask

app = Flask(__name__)

@app.route("/")

def home():

    return "Welcome to our Bookstore!"

if __name__ == "__main__":

    app.run()

Step 2: Adding More Pages

Let’s add an “About” page to provide some info about our bookstore.

@app.route("/about")

def about():

    return "We've been selling books since 1999!"

Step 3: Creating Dynamic Book Pages

Now, for the fun part! Let’s create a dynamic page that displays information about a book based on its ID.

@app.route("/book/<int:book_id>")

def book(book_id):

    return f"You're viewing details for book {book_id}."

Step 4: Complete Code

Here’s how your complete bookstore_app.py should look:

from flask import Flask

app = Flask(__name__)

@app.route("/")

def home():

    return "Welcome to our Bookstore!"

@app.route("/about")

def about():

    return "We've been selling books since 1999!"

@app.route("/book/<int:book_id>")

def book(book_id):

    return f"You're viewing details for book {book_id}."

if __name__ == "__main__":

    app.run()

Step 5: Running the App

Navigate to the folder where your bookstore_app.py is located. Run the following command:

python bookstore_app.py

Visit http://localhost:5000 in your web browser. You should see the welcome message. Try navigating to /about and /book/1 to see the other pages in action!

Conclusion

There you have it—your Flask app now knows how to handle different routes, parameters, and HTTP methods! 🎉

In our next episode, we’ll explore how to make our web pages dynamic and interactive using templates.

Leave a Reply

Layer 1