Flask is a lightweight and flexible Python web framework that allows developers to build web applications with ease. This guide provides a comprehensive example of a simple Flask application that incorporates both frontend and backend components. By following these steps, you'll create a functional web app that can serve HTML pages and handle backend logic seamlessly.
Organizing your project with a clear structure is crucial for maintaining and scaling your application. Here's how to set up your project directory:
flask_app/
├── app.py
├── requirements.txt
├── templates/
│ └── index.html
└── static/
├── style.css
└── script.js
Open your terminal and execute the following commands to create and enter the project directory:
mkdir flask_app
cd flask_app
Setting up a virtual environment isolates your project dependencies:
python3 -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
Install Flask using pip:
pip install Flask
Freeze your dependencies into a requirements.txt
file:
pip freeze > requirements.txt
app.py
The app.py
file contains the backend logic of your application. Here's a simple example:
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/greet', methods=['POST'])
def greet():
name = request.form.get('name')
return render_template('index.html', greeting=f'Hello, {name}!')
@app.route('/api/data', methods=['GET'])
def get_data():
data = {
"message": "Hello from Flask!",
"items": ["Item 1", "Item 2", "Item 3"]
}
return jsonify(data)
if __name__ == '__main__':
app.run(debug=True)
@app.route('/')
: Serves the main HTML page.@app.route('/greet', methods=['POST'])
: Handles form submissions and returns a personalized greeting.@app.route('/api/data', methods=['GET'])
: Provides a JSON API endpoint.The frontend is built using HTML, CSS, and JavaScript. Flask looks for HTML templates in the templates
directory.
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Flask App</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Welcome to the Simple Flask App</h1>
{% if greeting %}
<p>{{ greeting }}</p>
{% endif %}
<form action="{{ url_for('greet') }}" method="POST">
<label for="name">Enter your name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Greet Me</button>
</form>
<hr />
<h2>Fetch Data from API</h2>
<button id="fetchButton">Fetch Data</button>
<div id="dataResponse"></div>
<script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>
{{ url_for('static', filename='style.css') }}
: Links the CSS file.{{ greeting }}
: Displays personalized greeting if available.{{ url_for('greet') }}
: Sets the form action to the /greet
route.static/style.css
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
form {
margin-top: 20px;
}
input {
padding: 8px;
width: 200px;
}
button {
padding: 8px 16px;
margin-left: 10px;
}
#dataResponse {
margin-top: 20px;
font-weight: bold;
}
static/script.js
document.addEventListener("DOMContentLoaded", () => {
const fetchButton = document.getElementById("fetchButton");
const dataResponse = document.getElementById("dataResponse");
fetchButton.addEventListener("click", async () => {
try {
const response = await fetch("/api/data");
const data = await response.json();
if (response.ok) {
dataResponse.innerHTML = `<p>${data.message}</p>
<ul>${data.items.map(item => `<li>${item}</li>`).join('')}</ul>`;
} else {
dataResponse.textContent = "Error fetching data.";
}
} catch (error) {
dataResponse.textContent = "An error occurred!";
console.error(error);
}
});
});
/api/data
endpoint.Ensure all dependencies are installed by running:
pip install -r requirements.txt
Run the Flask application using the following command:
python app.py
Open your web browser and navigate to http://127.0.0.1:5000/. You should see the homepage with a welcome message and a form to enter your name. Submitting the form will display a personalized greeting. Additionally, clicking the "Fetch Data" button will retrieve and display data from the backend API.
By following this guide, you've set up a simple yet functional Flask application that integrates both frontend and backend components. This foundation can be expanded with additional features such as user authentication, database interactions, and more complex frontend frameworks like React or Vue.js. Flask's flexibility and simplicity make it an excellent choice for building scalable web applications.