Home > Courses > Flask: Python Web Development > First Flask program

First Flask program

Subject: Flask: Python Web Development
In this first flask program we will create a web application to display "Hello, TEA Learn!" on the web browser.

Follow these steps:
Step1. Create the web application folder e.g myweb
Step 2. Start VS Code and Open the "myweb" folder in VS Code
Step 3. Create a Python file app.py in the "myweb" folder
Step 4. Have the code in Example 1 in your app.py file

Example 1

#import the Flask class from flask framework
from flask import Flask
#create the app instance from Flask class
app = Flask(__name__)
#define a route
@app.route('/')
def index():
    return 'Hello, TEA Learn!'
if __name__ == '__main__':
    app.run(debug=True)


Step 5. Run the app.py program in VS Code.

Step 6. Open your web browser and visit http://localhost:5000/myweb/

This will display the message"Hello, TEA Learn!" on web browser.

Explanations
The code in Example 1 is the standard and basic structure of a flask web application, the following is worth noting:

1. Create the application object (app) from the Flask class:
app = Flask(__name__)


2. Define a route and view function:
When a user try to access your web application, they usually use a web browser program e.g Google chrome or Mozilla Firefox.
And here is the communication activity that occurs (also called hypertext transfer protocol -http)
a. The browser send a request (called http request) to the webserver (Often a computer in a remote location that host your website or application, but in our example it's hosted locally - localhost).
b. In return, the webserver response to the user will require it to send the request to the Flask application object. (app instance)
c. The app instance will then map or direct the URL (e.g tealearn.org/ OR localhost:5000/myapp/) to the function @app.route('/') that will handle such request (by executing the code in it e.g return 'Hello, TEA Learn!')
d. The response will then be sent back to the user's web browser by the web server.

We learn more about route interaction as we progress on this course.

Create a folder name myweb




Open the myweb folder in VS Code




Create a Python file app.py in the myweb folder




Have the code in Example 1 in your app.py file




Run the app.py program in VS Code (Click the run > icon at the top right)




It will show "Running on http://127.0.0.1:5000/" in the perminal window below...




Open your web browser and visit http://localhost:5000/myweb/





By: Benjamin Onuorah

Comments

Joshua Fasinu (learner)
Date commented: 20-Jul-2024 06:30:38pm

Kind of easy and ...

Login to comment or ask question on this topic


Previous Topic Next Topic

Supported by