Creating the Flask app and running it locally

pythonpat23

Graham Patrick

Posted on January 19, 2024

Creating the Flask app and running it locally

Now that we have installed Flask and created a virtual environment, we can start working on our Flask app. A Flask app is a Python object that represents the web application. To create a Flask app, we need to import the Flask class from the flask module and pass the name of the current module as an argument. This will help Flask locate the resources that we need for our app, such as templates and static files. We can also configure our app using various attributes and methods that the Flask class provides.

Let’s create a file called app.py in the current working directory and write the following code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello, world!"
Enter fullscreen mode Exit fullscreen mode

This code does the following:

Imports the Flask class from the flask module

Creates an instance of the Flask class and assigns it to the app variable

Defines a route for the root URL (“/”) using the app.route decorator

Defines a function called index that returns a string “Hello, world!” as the response

To run our Flask app locally, we need to set the FLASK_APP environment variable to the name of the file that contains our app. We can do this by running the following command in the terminal:

export FLASK_APP=app.py
Enter fullscreen mode Exit fullscreen mode

This will tell Flask where to find our app. To start the Flask development server, we can run the following command in the terminal:

flask run
Enter fullscreen mode Exit fullscreen mode

This will start the server and display the URL where we can access our app. You should see something like this:

Congratulations, you have created and run your first Flask app! 🎉

Original Post: https://enceladus-software.com/post/152

💖 💪 🙅 🚩
pythonpat23
Graham Patrick

Posted on January 19, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related