Build Your First Flask Application in Easy Steps
Get ready to crack interviews of top MNCs with Placement-ready courses Learn More!
Flask is a popular web framework for building web applications using Python. It is known for its simplicity and flexibility, making it an excellent choice for beginners and experienced developers alike.
If you are new to Flask and want to get started with your first Flask application, this article is for you. We will walk you through the process of building a simple Flask application step-by-step, covering the basics of Flask, creating routes, handling requests and responses, and rendering templates.
Before we begin, make sure you have Python and Flask installed on your machine. If you haven’t installed Flask yet, please refer to our previous article on Flask environment setup for instructions on how to install Flask on Mac, Linux, or Windows.
Now let’s dive into building our first Flask application!
Build Your First Flask Application
Step 1: Create a Project Directory
To start with, we need to create a directory for our Flask project. This directory will contain all the files and folders related to our Flask application. Open your terminal or command prompt and navigate to the directory where you want to create your project. Then, run the following command to create a new directory for your Flask project:
mkdir pythongeeks
You can replace “pythongeeks” with the name you prefer for your project.
Step 2: Create a Virtual Environment
It’s a good practice to create a virtual environment for each Flask project to isolate its dependencies from the system-wide Python installation. If you have not created a virtual environment for your Flask project yet, you can follow the instructions in our previous article on Flask environment setup to create one.
Activate your virtual environment before proceeding to the next steps. On Mac and Linux, you can run the following command:
source pythongeeks/bin/activate
On Windows, you can run the following command:
pythongeeks\bin\activate
Make sure to replace “pythongeeks” with the name of your virtual environment.
Step 3: Install Flask
With your virtual environment activated, you can now install Flask. Run the following command to install Flask using pip:
pip install Flask
Step 4: Create a Flask Application
Now it’s time to create our first Flask application. In the directory of your Flask project, create a new file named app.py. This will be the main file where we will write our Flask application code.
Open app.py in a text editor or an integrated development environment (IDE) of your choice, and let’s start writing our Flask application code.
First, we need to import the Flask module and create an instance of the Flask class, which will represent our web application. Here’s an example of how you can do it:
from flask import Flask app = Flask(__name__)
In the code above, we imported the Flask module and created an instance of the Flask class named app. We passed __name__ as an argument to the Flask class, which is a special variable in Python that represents the name of the current module. This allows Flask to determine the root path of our application.
Step 5: Define Routes
In Flask, routes define the URLs that our web application can handle. When a user requests a URL, Flask maps it to a specific route function, which then handles the request and generates a response.
Let’s define our first route. Below the app instance creation code, add the following route function:
@app.route('/')
def hello():
return 'Hello, Pythongeeks!'
In the code above, we used the route decorator provided by Flask to define a route for the root URL (“/”) of our web application. The route function hello() is a Python function that will be called when a user accesses the root URL of our application. The function simply returns the string “Hello, Pythongeeks!” as the response.
Step 6: Run the Flask Application
Now that we have defined our first route, let’s run our Flask application and see it in action. In your terminal or command prompt, make sure you are in the directory of your Flask project where app.py is located. Then, run the following command:
python app.py
This will start the Flask development server and make your application accessible at http://127.0.0.1:5000/ in your web browser.
You should see the message “Hello, Pythongeeks!” displayed in your browser, indicating that your Flask application is up and running!
Step 7: Handling Requests and Responses
In our previous step, we saw how to define a route and generate a simple response. But web applications are all about handling different types of requests and generating appropriate responses. Let’s explore how we can handle different types of HTTP requests in Flask.
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, PythonGeeks!'
@app.route('/about')
def about():
return 'This is the About page.'
@app.route('/contact', methods=['GET', 'POST'])
def contact():
if request.method == 'POST':
# Handle the POST request
return 'You submitted a contact form.'
else:
# Handle the GET request
return 'This is the Contact page. Use the form to submit a message.'
In the code above, we defined three routes: one for the root URL (“/”), one for the “/about” URL, and one for the “/contact” URL. The route function contact() takes an optional argument methods, which specifies the allowed HTTP methods for that route. In this case, we specified both GET and POST methods.
Inside the contact() function, we used the request object from Flask to access the request object, which contains information about the current request. We checked the request.method attribute to determine if the request is a GET or POST request. If it’s a POST request, we return a response indicating that a contact form has been submitted. If it’s a GET request, we return a response with instructions on how to submit a contact form.
You can test these routes by accessing the corresponding URLs in your browser or by using a tool like cURL or Postman to send GET and POST requests to your Flask application.
Step 8: Rendering Templates
In a real-world web application, we often need to generate dynamic content that includes HTML templates. Flask provides a built-in template engine called Jinja2, which makes it easy to render templates in our Flask application.
Let’s create a template for our “About” page. In the directory of your Flask project, create a new folder named “templates”. Inside the “templates” folder, create a new file named “about.html”. This will be our template file for the “About” page.
Open “about.html” in a text editor, and let’s create a simple HTML template:
<!DOCTYPE html> <html> <head> <title>About</title> </head> <body> <h1>About</h1> <p>This is the About page of our PythonGeeks Flask application.</p> </body> </html>
In the code above, we have a basic HTML template with a title, a heading, and a paragraph.
Now, let’s modify our Flask application to render this template when the “/about” URL is accessed:
from flask import Flask, render_template
app = Flask(name)
@app.route('/')
def hello():
return 'Hello, PythonGeeks!'
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/contact', methods=['GET', 'POST'])
def contact():
if request.method == 'POST':
# Handle the POST request
return 'You submitted a contact form.'
else:
# Handle the GET request
return 'This is the Contact page. Use the form to submit a message.'
In the code above, we added the `render_template` function from Flask, which allows us to render HTML templates. Inside the `about()` function, we simply return the result of calling `render_template(‘about.html’)`, which tells Flask to render the “about.html” template and return it as the response to the client.
Note that Flask expects template files to be placed in a folder named “templates” at the root level of your project directory. This is why we created a “templates” folder and placed our “about.html” template inside it.
Step 9: Adding Forms
Web applications often require users to submit data through forms. Flask makes it easy to handle form submissions by providing a `request.form` object that allows us to access the data submitted by the user.
Let’s add a simple contact form to our Flask application. Modify the `contact()` function in your Flask application as follows:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, PythonGeeks!'
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/contact', methods=['GET', 'POST'])
def contact():
if request.method == 'POST':
# Handle the POST request
name = request.form['name']
email = request.form['email']
message = request.form['message']
# Process the form data, e.g., store it in a database
return f'Thank you for submitting the form, {name}!'
else:
# Handle the GET request
return render_template('contact.html')
In the code above, we modified the contact() function to handle both GET and POST requests. Inside the POST request handling block, we used the request.form object to access the data submitted by the user. In this case, we assumed that the form has three fields: “name”, “email”, and “message”. We accessed the values of these fields using the dictionary-like syntax request.form[‘field_name’].
We also modified the GET request handling block to render a new template called “contact.html”, which will be the template for our contact form.
Let’s create the “contact.html” template inside the “templates” folder:
<!DOCTYPE html>
<html>
<head>
<title>Contact</title>
</head>
<body>
<h1>Contact</h1>
<form method="post" action="/contact">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
<br />
<label for="email">Email:</label>
<input type="email" name="email" id="email" />
<br />
<label for="message">Message:</label>
<textarea name="message" id="message"></textarea>
<br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
In the code above, we have a basic HTML form with three fields: “name”, “email”, and “message”. The form has a POST method to submit the data to the “/contact” URL, which is the same URL that the contact() function in our Flask application is listening for. The action attribute in the form specifies the URL to which the form data will be submitted.
When the user submits the form, the contact() function in our Flask application will be triggered with a POST request. The data submitted by the user will be available in the request.form object, and we can access the values of the fields using the request.form[‘field_name’] syntax, as we did in our Flask application code.
Step 10: Adding Error Handling
Error handling is an important aspect of web applications to provide meaningful feedback to users when something goes wrong. Flask allows us to handle errors easily by defining error handler functions.
Let’s add basic error-handling functionality to our Flask application. Modify your Flask application code as follows:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, PythonGeeks!'
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/contact', methods=['GET', 'POST'])
def contact():
if request.method == 'POST':
# Handle the POST request
name = request.form['name']
email = request.form['email']
message = request.form['message']
# Process the form data, e.g., store it in a database
return f'Thank you for submitting the form, {name}!'
else:
# Handle the GET request
return render_template('contact.html')
# Error handling functions
@app.errorhandler(404)
def page_not_found(error):
return 'Page not found', 404
@app.errorhandler(500)
def internal_server_error(error):
return 'Internal server error', 500
In the code above, we defined two error handling functions: page_not_found() and internal_server_error(). These functions are decorated with @app.errorhandler() decorator, which tells Flask that these functions are error handlers for the specified error codes.
The page_not_found() function will be triggered when a 404 error (page not found) occurs, and it will return the message “Page not found” with a 404 status code.
The internal_server_error() function will be triggered when a 500 error (internal server error) occurs, and it will return the message “Internal server error” with a 500 status code.
These error handler functions can be expanded to handle other types of errors and provide custom error messages or perform specific error handling logic, depending on the requirements of your web application.
Step 11: Deploying the Flask Application
Once you have developed your Flask application and tested it locally, you may want to deploy it to a production server so that it can be accessed by users from anywhere on the internet.
There are several ways to deploy a Flask application, depending on your requirements and preferences. Here are some popular options:
a. Flask’s built-in development server: Flask comes with a built-in development server that is suitable for development and testing purposes only. It is not recommended to use the built-in server for production deployments, as it is not optimized for performance and security.
b. Production-ready web servers: There are several production-ready web servers, such as Gunicorn, uWSGI, and mod_wsgi, that can be used to deploy Flask applications. These servers are optimized for performance and security and are suitable for production deployments. They can also be used in combination with reverse proxies, such as Nginx or Apache, for improved performance and security.
c. Platform-as-a-Service (PaaS) providers: PaaS providers are cloud-based platforms that offer pre-configured environments for hosting web applications, including Flask applications. Examples of popular PaaS providers include Heroku, Google App Engine, and Microsoft Azure. These platforms provide easy deployment options for Flask applications with automated scaling, monitoring, and management features.
d. Containerization platforms: Containerization platforms, such as Docker, provide a way to package an application and its dependencies into a single container that can run anywhere, regardless of the underlying infrastructure. Flask applications can be containerized and deployed to containerization platforms, such as Docker Swarm or Kubernetes, for scalable and flexible deployments.
e. Cloud-based virtual machines: Cloud-based virtual machines, such as Amazon EC2 or Google Compute Engine, provide a scalable and customizable environment for deploying Flask applications. With virtual machines, you can configure your own server environment and deploy your Flask application as needed.
The deployment process may vary depending on the method or platform you choose. You may need to configure the server environment, install dependencies, set up a database, and configure security settings. It’s important to follow best practices for securing your Flask application, such as using HTTPS, securing sensitive data, and keeping your software up to date with the latest security patches.
Conclusion
Flask is a powerful web framework for building web applications in Python. In this article, we covered the basics of how to build a Flask application, from setting up a Flask project, defining routes, rendering templates, handling forms, and adding error handling.
We also discussed deployment options for Flask applications, including using Flask’s built-in development server, production-ready web servers, PaaS providers, containerization platforms, and cloud-based virtual machines.
As you continue to develop your Flask application, you can explore more advanced features, such as authentication and authorization, database integration, API development, and performance optimization. Flask provides a flexible and extensible framework that can be tailored to your specific needs, making it a popular choice among developers for building web applications in Python.
Remember to always follow best practices for web development, including proper error handling, input validation, and security measures, to ensure that your Flask application is secure and reliable. Happy Flask coding!
