Cooperate with Flask/Django backend
In the field of modern web development, front-end separation has become a popular architectural model.
As a lightweight, high-performance front-end framework, combined with back-end frameworks like Flask or Django, it can build powerful and scalable web applications.
This article will introduce in detail how to use it with Flask or Django backend to achieve separation of front and backend.
Overview of front-end separation
The core idea of front-end separation is to separate the front-end interface of web applications from back-end services to issue, deploy and maintain.
Under this architecture, the front-end is mainly responsible for the rendering and interaction logic of the user interface, while the back-end is responsible for handling business logic, database interaction, etc.
Both communicate data through APIs (usually RESTful APIs or GraphQL). This architectural pattern brings many advantages, including:
- Efficient development: The front-end and back-end can be developed in parallel, without dependence on each other, and speed up the development speed.
- Strong reusability: The API can serve multiple clients such as the Web and mobile terminal at the same time.
- Good maintenance: The front-end and back-end code are separated, making the code easier to maintain.
- Improve user experience: The front-end can focus on the user interface and interactive experience to improve user satisfaction.
Technology stack
- front end:
- rear end: Flask or Django
- Data communication: RESTful API (requested using Axios)
Project structure
A typical front-end and back-end separation project structure is roughly as follows:
my_project/ ├── backend/ # Backend code directory (Flask or Django)│ ├── # Flask application portal│ ├── # Django API views │ └── ... ├── frontend/ # Front-end code directory (project)│ ├── src/ │ ├── public/ │ └── ... └── # Project description
Setting the front end
1. Install Vue CLI
First, make sure you have and npm installed, and then install the Vue CLI:
npm install -g @vue/cli
2. Create a Vue project
Create a new Vue project in the project root directory:
vue create frontend
Follow the prompts to set up the Vue project.
3. Install Axios
Install Axios in Vue project to initiate API requests:
cd frontend npm install axios
4. Create Vue Components
existfrontend/src/components
Create Vue components in the directory, for example, used to display the data obtained from the backend interface.
<template> <div> <h1>{{ message }}</h1> <ul> <li v-for="item in data" :key="item">{{ item }}</li> </ul> </div> </template> <script> import axios from 'axios'; export default { data() { return { message: '', data: [] }; }, mounted() { ('http://localhost:5000/api/data') .then(response => { = ; = ; }) .catch(error => { ('API Error:', error); }); } } </script>
Set up Flask backend
1. Create a Flask project
existbackend
In the directory, create a new Flask project.
mkdir backend cd backend python -m venv venv source venv/bin/activate # Linux/Mac # venv\Scripts\activate # Windows pip install Flask
2. Write Flask application
existbackend
Created in the directoryand write a simple Flask API.
from flask import Flask, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) @('/api/data', methods=['GET']) def get_data(): return jsonify({'message': 'Hello from Flask!', 'data': [1, 2, 3, 4, 5]}) if __name__ == '__main__': (debug=True)
This code creates a simple Flask API that returns a message and a set of data.
Run Flask server
existbackend
Execute in the directory:
python
Setting up Django backend
Create a Django project
existbackend
In the directory, create a new Django project.
mkdir backend cd backend python -m venv venv source venv/bin/activate # Linux/Mac # venv\Scripts\activate # Windows pip install django djangorestframework django-admin startproject myproject
Create API app
Create a new Django app as an API within the project.
python startapp api
Configuring Django REST framework
existmyproject/
Added inrest_framework
arriveINSTALLED_APPS
middle.
INSTALLED_APPS = [ ... 'rest_framework', 'api', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.', ] }
Writing API views
existapi/
Write API views in
from rest_framework.views import APIView from rest_framework.response import Response class DataView(APIView): def get(self, request): return Response({'message': 'Hello from Django!', 'data': [1, 2, 3, 4, 5]})
Configure routing
existapi/
Set the route inmyproject/
Include it in.
# api/ from import path from .views import DataView urlpatterns = [ path('data/', DataView.as_view()), ] # myproject/ from import admin from import path, include urlpatterns = [ path('admin/', ), path('api/', include('')), ]
Install CORS support
Installdjango-cors-headers
And inConfigure in.
pip install django-cors-headers
existAdded in:
INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ ... '', ... ] CORS_ALLOW_ALL_ORIGINS = True # Or set a specific whitelist
Run Django server
existmyproject
Execute in the directory:
python runserver
Integrate the front and back ends
During the development process, you can start Flask or Django backend server and front-end server respectively, and call the back-end API through Axios.
Ensure that the API interface and data format of the front-end and back-end are consistent, so that smooth communication is performed.
Production environment configuration
Build a Vue application
- Execute in the Vue project directory:
npm run build
This willfrontend/dist
Generate compiled static files in the directory.
Deploy Vue applications
- For Flask, you can
frontend/dist
Copy the files in the directory to Flaskstatic
In the directory, and modify the route of Flask to return。
- For Django,
frontend/dist
Files in the directory (except) Copy to Django
static
In the directory, andPlaced in Django
templates
In the directory, then modify the Django view to return to the template.
Configure reverse proxy
- In production environments, Nginx or Apache is usually used as a reverse proxy server to provide static file services and forward requests to the backend server.
in conclusion
Combining with Flask or Django can form a powerful front-end separation architecture suitable for building modern web applications. Through reasonable division of labor and technical selection, development efficiency can be improved and application maintainability and scalability can be enhanced. Front and back end
The above is personal experience. I hope you can give you a reference and I hope you can support me more.