Top Node.js Development Companies in India
November 15, 2024
Home >> Full Stack >> How to Build a Full-Stack Web Application with Python and Vue.js
Quick Summary
Pairing Python’s robust backend capabilities with Vue.js’s dynamic frontend framework allows developers to create web applications that are highly interactive and feature-rich.
Python is well-regarded for its simplicity and versatility, making it an ideal choice for backend tasks such as data processing, managing databases, and integrating APIs. Meanwhile, Vue.js, a modern JavaScript framework, empowers developers to craft responsive and user-friendly interfaces on the front end.
In this tutorial, we will guide you through the process of developing a full-stack web application. We’ll begin by setting up the backend using Flask, a lightweight Python web framework known for its flexibility and ease of use. Then, we’ll move on to configuring the front end with Vue.js and leveraging Vue CLI for efficient project setup.
Throughout this tutorial, our focus will be on creating a seamless development environment and ensuring effective communication between the backend and frontend components.
By the end of this guide, you’ll have gained the skills necessary to build your full-stack web applications, leveraging the strengths of Python and Vue.js.
Whether you’re an experienced developer looking to expand your skill set or a newcomer eager to explore web development, this tutorial provides a clear introduction to full-stack development with Python and Vue.js.
Let’s dive into this journey together and create compelling and functional web applications!
Before beginning, ensure that your system meets the following prerequisites:
npm install -g @vue/cli
After installing the required tools, we’ll use Flask, a web framework, to build our API.
Step 1: Create a Project Directory
First, we’ll create a directory for our backend code. Open your terminal or command prompt and run the following commands:
mkdir backend
cd backend
Step 2: Initialise a virtual environment
Creating a virtual environment allows you to isolate your Python project from the system’s Python installation and other projects. This ensures that your project’s dependencies are managed independently, making it easier to maintain and reproduce. To set up a virtual environment, run the following command:
python -m venv venv
Step 3: Activate the Virtual Environment
To begin using your virtual environment, activate it with the following commands based on your operating system:
For Windows:
venv\Scripts\activate
For macOS and Linux:
source venv/bin/activate
Step 4: Install ‘Flask’
After activating the virtual environment, install Flask by running:
pip install Flask
Step 5: Create the Flask App
Begin by creating a file named app.py within your backend directory. Inside app.py, set up a basic Flask application using the following code:
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello from Flask!'
Step 6: Run the Flask App
Execute the Flask application by entering the following command in your terminal:
python app.py
Upon successful execution, you will see the following message:
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
This indicates that your Flask backend is now operational and accessible at http://127.0.0.1:5000/.
Now that we’ve completed setting up the backend, let’s proceed with configuring the front end using Vue.js.
Step 1: Create a Vue.js Project
Begin by opening your terminal or command prompt. Navigate to the main directory of your project (where the backend setup is located) and execute the following command to create a new Vue.js project named ‘frontend’:
vue create frontend
This command initiates the Vue CLI wizard, allowing you to select a preset. You can choose the default preset or customize features as needed for your project.
Step 2: Run the Vue.js Development Server
Once the Vue.js project is created, navigate into the ‘frontend’ directory using:
cd frontend
Start the development server by running:
npm run serve
After the server successfully starts, you’ll see output similar to the following in your terminal:
App running at:
– Local: http://localhost:8080/
– Network: http://192.168.0.101:8080/
This indicates that your Vue.js frontend is running locally and can be accessed through http://localhost:8080/.
Step 3: Update Vue.js to Fetch Data from Backend
To enable your Vue.js application to fetch data from the Flask backend, follow these steps:
Open the frontend/src/App.vue file and replace its current content with the following code:
<template>
<div>
<h1>{{ message }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
message: "",
};
},
mounted() {
fetch("http://localhost:5000/")
.then(response => response.text())
.then(data => {
this.message = data;
});
},
};
</script>
Explanation:
– Vue Component Structure: The <template> section defines the structure of the component, displaying the message fetched from the backend.
– Data Property: The data() method initializes the component’s message property as an empty string, which will later hold the fetched data from the backend.
– Mounted Lifecycle Hook: The mounted() hook is called when the component is mounted onto the DOM. Within this hook:
– The fetch() function sends a GET request to http://localhost:5000/, which represents the endpoint of your Flask backend.
– Using promises (then() method), the response from the backend is handled:
– The first then() extracts the response data as text.
– The second then() updates the message property with the retrieved data, thereby updating the component’s state.
This setup ensures that your Vue.js application successfully retrieves data from the Flask backend and displays it in the template.
Now that both the backend and frontend setups are complete, the next step is to establish communication between them to ensure the effective operation of the application.
In the frontend/src/App.vue file, we are currently fetching data from the backend using the URL http://localhost:5000/, where our Flask backend is hosted.
Given that the Vue.js development server operates on a different port (typically http://localhost:8080/ by default), it’s necessary to configure Vue.js to proxy API requests to the Flask backend during the development phase.
Step 1: Configure Vue.js Proxy
Create or edit the vue.config.js file in the frontend directory with the following content:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:5000',
changeOrigin: true,
},
},
},
};
Step 2: Update Vue.js App to Use Proxy
Modify the fetch URL in the frontend/src/App.vue file to utilize the /api prefix, which will automatically proxy requests to the Flask backend during development:
<template>
<div>
<h1>{{ message }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
message: "",
};
},
mounted() {
fetch("/api")
.then((response) => response.text())
.then((data) => {
this.message = data;
});
},
};
</script>
Step 3: Restart the Vue.js Development Server
Restart the Vue.js development server. If it’s currently running, stop it using CTRL+C in the terminal, then start it again with:
npm run serve
After restarting, navigate to http://localhost:8080/ in your browser. Your Vue.js application should now fetch data from the Flask backend and display it on the page.
Now that we’ve completed the installation, and development setup, and established the connection between the backend and frontend, we’re ready to add a new feature to our full-stack web application. This feature will serve as a demonstration of integrating Python (Flask) with Vue.js by creating a simple to-do list app.
The to-do list app will allow users to add and remove tasks dynamically. Tasks will be stored on the backend using a list structure, while Vue.js will handle the front end to display and manage these tasks. We’ll begin by implementing the backend functionality:
Step 1: Modify the Backend API
In your backend/app.py file, update the backend API to manage tasks. Add the following code:
from flask import Flask, jsonify, request
app = Flask(__name__)
tasks = [ ]
@app.route('/api/tasks', methods=['GET'])
def get_tasks():
return jsonify(tasks)
@app.route('/api/tasks', methods=['POST'])
def add_task():
data = request.get_json()
task = data.get('task', '')
tasks.append(task)
return jsonify({'message': 'Task added successfully!'})
@app.route('/api/tasks/', methods=['DELETE'])
def remove_task(index):
if 0 <= index < len(tasks):
del tasks[index]
return jsonify({'message': 'Task removed successfully!'})
else:
return jsonify({'error': 'Invalid index!'}), 400
Note: These endpoints allow the frontend to interact with the backend to manage tasks.
- GET /api/tasks: Returns a JSON response containing all tasks.
- POST /api/tasks: Adds a new task to the tasks list.
- DELETE /api/tasks/<int:index>: Removes a task by its index from the tasks list.
Step 2: Update the Vue.js App
Modify the frontend/src/App.vue file to display tasks, enable adding new tasks, and allow removing tasks:
<template>
<div>
<h1>Tagline’s To-Do List</h1>
<div v-for="(task, index) in tasks" :key="index">
{{ task }}
<button @click="removeTask(index)">Remove</button>
</div>
<input v-model="newTask" @keydown.enter="addTask" placeholder="Add a new task" />
<button @click="addTask">Add</button>
</div>
</template>
<script>
export default {
data() {
return {
tasks: [ ],
newTask: "",
};
},
mounted() {
this.fetchTasks();
},
methods: {
fetchTasks() {
fetch("/api/tasks")
.then(response => response.json())
.then(data => {
this.tasks = data;
});
},
addTask() {
if (this.newTask.trim() !== "") {
fetch("/api/tasks", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ task: this.newTask }),
})
.then(() => {
this.newTask = "";
this.fetchTasks();
});
}
},
removeTask(index) {
fetch(`/api/tasks/${index}`, {
method: "DELETE",
})
.then(() => {
this.fetchTasks();
});
},
},
};
</script>
Explanation:
- Displaying Tasks: Iterates over tasks array and displays each task with a "Remove" button.
- Adding New Task: Binds newTask to an input field for adding new tasks. Users can either press "Enter" or click "Add" to add a task.
- Removing Task: Sends a DELETE request to remove a task by its index.
This Vue.js app now functions as a to-do list, allowing users to manage tasks dynamically. Tasks are fetched from and updated on the Flask backend seamlessly.
Congratulations on completing your full-stack web application! You've utilized Python for the backend and Vue.js for the front end. With Flask as your backend API and Vue.js handling the front end, you've successfully implemented a practical to-do list feature.
Consider expanding your application by integrating databases, implementing user authentication, and adding more features to enhance its functionality.
For detailed guidance and advanced features, consult the official Flask (https://flask.palletsprojects.com/) and Vue.js (https://vuejs.org/) documentation.
At Tagline Infotech, we develop robust and intuitive websites and applications. Feel free to discuss how we can collaborate on your next project!
Digital Valley, 423, Apple Square, beside Lajamni Chowk, Mota Varachha, Surat, Gujarat 394101
D-401, titanium city center, 100 feet anand nagar road, Ahmedabad-380015
+91 9913 808 2851133 Sampley Ln Leander, Texas, 78641
52 Godalming Avenue, wallington, London - SM6 8NW