How to Use Python Flask to Build a Simple Web Application
Python Flask is a lightweight web framework that is popular for building simple web applications. It is easy to learn and use, and it can be used to create a variety of web applications, from simple static websites to more complex dynamic applications.
In this article, we will show you how to use Python Flask to build a simple web application. We will start by creating a new Flask project, and then we will create the routes and templates for our application. We will then put it all together and run our application.
Creating a New Flask Project
To create a new Flask project, we can use the flask new command. For example, to create a project called my-app, we would run the following command:
flask new my-app
This will create a new directory called my-app, which will contain the files for our Flask project.
Creating the Routes
The routes in a Flask application are what define the endpoints that can be accessed by users. To create a route, we use the @app.route() decorator. The decorator takes a URL path as its argument, and it returns a function that will be called when a request is made to that URL path.
For example, the following code creates a route that will be called when a request is made to the URL path/
@app.route(‘/’)
def index():
return ‘Hello, world!’
Creating the Templates
The templates in a Flask application are what are used to render the HTML pages for the application. To create a template, we use the render_template()function. The render_template() function takes the name of the template file as its argument, and it returns the rendered HTML page.
For example, the following code creates a template file called index.html and renders it when a request is made to the URL path /.
@app.route(‘/’)
def index():
return render_template(‘index.html’)
Putting it all together
Now that we have created the routes and templates for our application, we can put it all together. The following code shows the complete code for our application:
from flask import Flask
app = Flask(__name__)
@app.route(‘/’)
def index():
return render_template(‘index.html’)
if __name__ == ‘__main__’:
app.run()
To run our application, we can use the flask run command. For example, to run our application on port 8080, we would run the following command:
flask run –port 8080
This will start a local web server that will host our application. We can then open our browser and navigate to
http://localhost:8080 to view our application.
In this article, we showed you how to use Python Flask to build a simple web application. We started by creating a new Flask project, and then we created the routes and templates for our application. We then put it all together and ran our application.