The first Flask web application
In the previous lesson we met Flask – one of the most popular Python frameworks for web programming.
Now we will make our first Flask web application, which starts a small web server and shows content in the browser.
The structure of the simplest Flask application
Every Flask application has a few basic parts:
- creating the Flask application
- defining URL routes
- functions that return the server's response
- starting the web server
An example of a first Flask application
Create a new file called app.py.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello from the Flask server!"
if __name__ == "__main__":
app.run(debug=True)
This program starts a small web server on your computer.
Running the application
In the terminal run the following command:
python app.py
If everything is installed correctly, you will see a message that the server has started.
Open the browser and go to the address:
http://127.0.0.1:5000
How does this code work?
- Flask(__name__) creates the application
- @app.route("/") defines the starting URL address
- the function home() returns the text that the server sends to the browser
- app.run() starts the web server
Mini project – A site with two pages
Let us make a small application with two pages: a home page and a page about the author.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "<h1>Welcome to my Python website!</h1>"
@app.route("/author")
def author():
return "The author of the website is a Python programmer."
app.run()
How does this project work?
- we define two URL routes
- each route has its own function
- the browser shows different content for each address
Example URL addresses
- http://127.0.0.1:5000
- http://127.0.0.1:5000/author
Each address runs a different Python function.
Related lessons
Frequently asked questions
How do you run a Flask application?
A Flask application is started with the command python app.py.
Which port does the Flask server use?
The default port is 5000.
Can Flask show HTML pages?
Yes. Flask can return HTML content or use a template system.
Is Flask good for small projects?
Yes. Flask is excellent for small and medium web applications.
