Graham Patrick
Posted on January 19, 2024
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!"
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
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
This will start the server and display the URL where we can access our app. You should see something like this:
- Running on http://127.0.0.1:5000/ If we open this URL in a web browser, we should see our welcome message:
Congratulations, you have created and run your first Flask app! 🎉
Original Post: https://enceladus-software.com/post/152
Posted on January 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.