Building a Flask Application
Flask is a popular Python web framework that is lightweight, flexible, and easy to use. In this section, we'll walk through the process of building a simple Flask application.
Setting up the Development Environment
First, let's set up the development environment. We'll be using Python 3.9 and Flask 2.0.2 for this example.
## Install Python 3.9
sudo apt-get update
sudo apt-get install -y python3.9
## Install Flask
pip3 install flask==2.0.2
Creating a Flask Application
Now, let's create a simple Flask application. Create a new file called app.py
and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello, LabEx!'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
In this example, we import the Flask
class from the flask
module, create a new Flask
instance, and define a route for the root URL (/
) that returns the string "Hello, LabEx!". Finally, we run the application using the app.run()
method.
Running the Flask Application
To run the Flask application, execute the following command in your terminal:
python3 app.py
This will start the Flask development server and make your application available at http://localhost:5000/
.
Adding Functionality
You can easily add more functionality to your Flask application by defining additional routes and adding business logic. For example, you can create a route that accepts user input, performs some processing, and returns a response.
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello, LabEx!'
@app.route('/greet', methods=['POST'])
def greet():
name = request.form['name']
return f'Hello, {name}!'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
In this example, we've added a new route /greet
that accepts a POST
request with a name
parameter. The application then returns a greeting message with the provided name.