top of page

How to create a web app using Flask in Python (Part 2)


Using a VR headset to become part of "the code"
Actual image of what my Mom imagines when I say "I'm coding"

If you haven't already, read Part 1 in our Flask series. This tutorial is going to pick up where Part 1 left off. If you followed the instructions correctly, you should have a Python file with the following code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home_page():
    return "<h1>This is my web app.</h1>"

And when you run the following command from the terminal, your web app should be served at http://127.0.0.1:5000:

flask --app flask_web_app run

At the moment, our web app is incredibly simple. All the home_page() function does is return one line of content to be displayed. What happens if we want something more complex? Like images, fields, buttons, etc? Well, thankfully, Flask makes it pretty easy to load an entire HTML file of our choosing using the render_template module.


First thing, change the first line of our file to:

from flask import Flask, render_template

Next, change the return call in home_page() to:

return render_template('index.html')

Cool, now what this will do is search the current directory for a templates folder, and look inside of that folder for a file called index.html. If that folder or file don't exist, we'll get an error. So, let's add them.


Just create a folder inside of whatever directly you're working in called templates and create a new file called index.html. Inside the HTML file, add the following lines:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CodeConda Web App</title>
</head>
<body>
    <h1>Welcome to the CodeConda Web App!</h1>
    <p>This web app is still in progress.</p>
</body>
</html>

Perfect, now save everything and execute the flask run command to make sure it's working properly. This webpage is not too much more complex than the one that we had previously, but we now have a full HTML file to work with. This gives us a lot more flexibility than we had before.


If you're a beginner programmer and video/text tutorials just aren't doing it for you, consider signing up for one of our many lessons on CodeConda. There, you'll be able to attend live classes taught by an experienced software engineer on Zoom. And, unlike videos or articles, your instructor will make sure you actually understand what is being taught and help you along.


Commentaires


bottom of page