mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-10-04 01:10:36 +00:00
feat(docs): 重构文档结构并更新内容
refactor(docs): 迁移文档到src目录并优化配置 style(docs): 统一代码格式和样式 chore(docs): 移除不必要的配置文件和依赖 fix(docs): 修正锁屏对话框的翻译和占位符 feat(components): 添加ElDescriptions组件支持 perf(docs): 优化文档图片加载和缩放功能
This commit is contained in:
@@ -0,0 +1,440 @@
|
||||
---
|
||||
outline: "deep"
|
||||
title: API Documentation
|
||||
---
|
||||
# API Documentation
|
||||
|
||||
## 📚 API Documentation Overview
|
||||
|
||||
The FastapiAdmin project provides comprehensive API documentation to help developers understand and use the system's interfaces. This document will detail how to use and call these APIs.
|
||||
|
||||
## 🔧 Backend API Documentation
|
||||
|
||||
### 1. Access Methods
|
||||
|
||||
The backend API documentation is automatically generated based on FastAPI, supporting both Swagger and Redoc formats:
|
||||
|
||||
- **Swagger UI**: <http://localhost:8001/api/v1/docs> (local development environment)
|
||||
- **Redoc**: <http://localhost:8001/api/v1/redoc> (local development environment)
|
||||
- **Online Demo**: <https://service.fastapiadmin.com/api/v1/docs> (production environment)
|
||||
|
||||
### 2. Usage Methods
|
||||
|
||||
#### 2.1 Authentication and Login
|
||||
|
||||
1. Open the Swagger UI documentation page
|
||||
2. Click the "Authorize" button in the top right corner of the page
|
||||
3. Enter your username and password in the dialog box that appears
|
||||
4. Click the "Authorize" button to complete authentication
|
||||
5. After successful authentication, all API calls will automatically carry authentication information
|
||||
|
||||
#### 2.2 API Testing
|
||||
|
||||
1. Find the API you want to test in Swagger UI
|
||||
2. Click the API name to expand detailed information
|
||||
3. Click the "Try it out" button
|
||||
4. Fill in the necessary parameters
|
||||
5. Click the "Execute" button to execute the request
|
||||
6. View the response results
|
||||
|
||||
### 3. API Interface Classification
|
||||
|
||||
Backend API interfaces are mainly divided into the following categories:
|
||||
|
||||
- **System Management**: User, role, menu, department, position, and other management interfaces
|
||||
- **Monitoring Management**: Online users, server monitoring, cache monitoring, and other interfaces
|
||||
- **Task Management**: Scheduled task management interfaces
|
||||
- **Log Management**: Operation log query interfaces
|
||||
- **Development Tools**: Code generation, form building, and other interfaces
|
||||
|
||||
## 📱 Frontend API Calls
|
||||
|
||||
### 1. Frontend API Encapsulation
|
||||
|
||||
The frontend project uses TypeScript to encapsulate API calls, mainly located in the `frontend/src/api` directory, organized by module:
|
||||
|
||||
```
|
||||
frontend/src/api/
|
||||
├── module_example/ # Example module
|
||||
│ └── demo.ts
|
||||
├── module_monitor/ # Monitoring module
|
||||
│ ├── cache.ts
|
||||
│ ├── online.ts
|
||||
│ └── server.ts
|
||||
└── module_system/ # System module
|
||||
├── auth.ts
|
||||
├── dept.ts
|
||||
├── dict.ts
|
||||
├── log.ts
|
||||
├── menu.ts
|
||||
├── notice.ts
|
||||
├── params.ts
|
||||
├── role.ts
|
||||
└── user.ts
|
||||
```
|
||||
|
||||
### 2. API Call Examples
|
||||
|
||||
#### 2.1 Import API Modules
|
||||
|
||||
```typescript
|
||||
import { authApi } from '@/api/module_system/auth';
|
||||
import { userApi } from '@/api/module_system/user';
|
||||
```
|
||||
|
||||
#### 2.2 Call Login API
|
||||
|
||||
```typescript
|
||||
import { authApi } from '@/api/module_system/auth';
|
||||
import { useUserStore } from '@/store/modules/user.store';
|
||||
|
||||
const userStore = useUserStore();
|
||||
|
||||
const login = async (username: string, password: string) => {
|
||||
try {
|
||||
const res = await authApi.login({
|
||||
username,
|
||||
password
|
||||
});
|
||||
|
||||
// Save token
|
||||
userStore.setToken(res.data.token);
|
||||
|
||||
// Get user info
|
||||
await userStore.getUserInfo();
|
||||
|
||||
// Navigate to home page
|
||||
router.push('/');
|
||||
} catch (error) {
|
||||
console.error('Login failed:', error);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### 2.3 Call User Management API
|
||||
|
||||
```typescript
|
||||
import { userApi } from '@/api/module_system/user';
|
||||
|
||||
// Get user list
|
||||
const getUserList = async () => {
|
||||
try {
|
||||
const res = await userApi.getList({
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
username: 'admin'
|
||||
});
|
||||
console.log('User list:', res.data);
|
||||
} catch (error) {
|
||||
console.error('Failed to get user list:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Get user detail
|
||||
const getUserDetail = async (userId: number) => {
|
||||
try {
|
||||
const res = await userApi.getDetail(userId);
|
||||
console.log('User detail:', res.data);
|
||||
} catch (error) {
|
||||
console.error('Failed to get user detail:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Create user
|
||||
const createUser = async (userData: any) => {
|
||||
try {
|
||||
const res = await userApi.create(userData);
|
||||
console.log('User created successfully:', res.data);
|
||||
} catch (error) {
|
||||
console.error('Failed to create user:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Update user
|
||||
const updateUser = async (userId: number, userData: any) => {
|
||||
try {
|
||||
const res = await userApi.update(userId, userData);
|
||||
console.log('User updated successfully:', res.data);
|
||||
} catch (error) {
|
||||
console.error('Failed to update user:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Delete user
|
||||
const deleteUser = async (userId: number) => {
|
||||
try {
|
||||
const res = await userApi.delete(userId);
|
||||
console.log('User deleted successfully:', res.data);
|
||||
} catch (error) {
|
||||
console.error('Failed to delete user:', error);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## 📱 FastApp Mobile API Calls
|
||||
|
||||
### 1. Mobile API Encapsulation
|
||||
|
||||
The FastApp mobile project also encapsulates API calls, mainly located in the `src/api` directory:
|
||||
|
||||
```
|
||||
FastApp/src/api/
|
||||
├── auth.ts # Authentication related interfaces
|
||||
├── file.ts # File related interfaces
|
||||
└── user.ts # User related interfaces
|
||||
```
|
||||
|
||||
### 2. API Call Examples
|
||||
|
||||
#### 2.1 Import API Modules
|
||||
|
||||
```typescript
|
||||
import { authApi } from '@/api/auth';
|
||||
import { userApi } from '@/api/user';
|
||||
```
|
||||
|
||||
#### 2.2 Call Login API
|
||||
|
||||
```typescript
|
||||
import { authApi } from '@/api/auth';
|
||||
import { useUserStore } from '@/store/modules/user.store';
|
||||
|
||||
const userStore = useUserStore();
|
||||
|
||||
const login = async (username: string, password: string) => {
|
||||
try {
|
||||
const res = await authApi.login({
|
||||
username,
|
||||
password
|
||||
});
|
||||
|
||||
// Save token
|
||||
userStore.setToken(res.data.token);
|
||||
|
||||
// Get user info
|
||||
await userStore.getUserInfo();
|
||||
|
||||
// Navigate to home page
|
||||
uni.switchTab({ url: '/pages/index/index' });
|
||||
} catch (error) {
|
||||
console.error('Login failed:', error);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### 2.3 Call User Info API
|
||||
|
||||
```typescript
|
||||
import { userApi } from '@/api/user';
|
||||
|
||||
// Get user info
|
||||
const getUserInfo = async () => {
|
||||
try {
|
||||
const res = await userApi.getUserInfo();
|
||||
console.log('User info:', res.data);
|
||||
return res.data;
|
||||
} catch (error) {
|
||||
console.error('Failed to get user info:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Update user info
|
||||
const updateUserInfo = async (userData: any) => {
|
||||
try {
|
||||
const res = await userApi.updateUserInfo(userData);
|
||||
console.log('User info updated successfully:', res.data);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to update user info:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## 🛠️ API Call Best Practices
|
||||
|
||||
### 1. Error Handling
|
||||
|
||||
When calling APIs, you should properly handle possible errors:
|
||||
|
||||
```typescript
|
||||
try {
|
||||
const res = await apiCall();
|
||||
// Handle successful response
|
||||
} catch (error: any) {
|
||||
// Handle errors
|
||||
if (error.response) {
|
||||
// Server returned error status code
|
||||
console.error('Server error:', error.response.data);
|
||||
uni.showToast({
|
||||
title: error.response.data.message || 'Server error',
|
||||
icon: 'none'
|
||||
});
|
||||
} else if (error.request) {
|
||||
// Request was sent but no response received
|
||||
console.error('Network error:', error.request);
|
||||
uni.showToast({
|
||||
title: 'Network error, please check your connection',
|
||||
icon: 'none'
|
||||
});
|
||||
} else {
|
||||
// Request configuration error
|
||||
console.error('Request error:', error.message);
|
||||
uni.showToast({
|
||||
title: 'Request error',
|
||||
icon: 'none'
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Loading State
|
||||
|
||||
When calling APIs, you should display a loading state to improve user experience:
|
||||
|
||||
```typescript
|
||||
const loading = ref(false);
|
||||
|
||||
const fetchData = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await apiCall();
|
||||
// Process data
|
||||
} catch (error) {
|
||||
// Handle errors
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 3. Caching Strategy
|
||||
|
||||
For data that doesn't change frequently, you can use a caching strategy to reduce network requests:
|
||||
|
||||
```typescript
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { userApi } from '@/api/user';
|
||||
import { useStorage } from '@/utils/storage';
|
||||
|
||||
const userList = ref([]);
|
||||
const loading = ref(false);
|
||||
const storage = useStorage();
|
||||
|
||||
const fetchUserList = async () => {
|
||||
// Try to get from cache
|
||||
const cachedData = storage.get('userList');
|
||||
if (cachedData) {
|
||||
userList.value = cachedData;
|
||||
return;
|
||||
}
|
||||
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await userApi.getList({ page: 1, pageSize: 100 });
|
||||
userList.value = res.data.items;
|
||||
// Cache data, valid for 5 minutes
|
||||
storage.set('userList', res.data.items, 5 * 60 * 1000);
|
||||
} catch (error) {
|
||||
console.error('Failed to get user list:', error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
fetchUserList();
|
||||
});
|
||||
```
|
||||
|
||||
## 📝 API Design Standards
|
||||
|
||||
### 1. URL Standards
|
||||
|
||||
- API URLs use lowercase letters and underscores
|
||||
- Resource paths use plural forms
|
||||
- Version numbers are placed in the URL prefix (e.g., `/api/v1/`)
|
||||
|
||||
### 2. HTTP Methods
|
||||
|
||||
- `GET`: Retrieve resources
|
||||
- `POST`: Create resources
|
||||
- `PUT`: Update resources
|
||||
- `DELETE`: Delete resources
|
||||
- `PATCH`: Partially update resources
|
||||
|
||||
### 3. Response Format
|
||||
|
||||
All API responses use a unified format:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {...}
|
||||
}
|
||||
```
|
||||
|
||||
- `code`: Status code, 200 indicates success, others indicate failure
|
||||
- `message`: Response message, "success" when successful, error message when failed
|
||||
- `data`: Response data, returning different data structures based on the interface
|
||||
|
||||
### 4. Paginated Response
|
||||
|
||||
Response format for paginated interfaces:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"items": [...],
|
||||
"total": 100,
|
||||
"page": 1,
|
||||
"pageSize": 10,
|
||||
"pages": 10
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `items`: Data list for the current page
|
||||
- `total`: Total number of records
|
||||
- `page`: Current page number
|
||||
- `pageSize`: Page size
|
||||
- `pages`: Total number of pages
|
||||
|
||||
## 💡 Common Issues and Solutions
|
||||
|
||||
### 1. Authentication Failed
|
||||
|
||||
**Issue**: API call returns 401 error
|
||||
**Solution**: Check if you are logged in, if the login status has expired, and re-login to obtain new authentication information.
|
||||
|
||||
### 2. Insufficient Permissions
|
||||
|
||||
**Issue**: API call returns 403 error
|
||||
**Solution**: Check if the current user has sufficient permissions to perform the operation, and contact the administrator to assign permissions.
|
||||
|
||||
### 3. Parameter Error
|
||||
|
||||
**Issue**: API call returns 422 error
|
||||
**Solution**: Check if the request parameters are correct, if required parameters are missing, and if the parameter format meets the requirements.
|
||||
|
||||
### 4. Network Error
|
||||
|
||||
**Issue**: API call times out or cannot connect
|
||||
**Solution**: Check if the network connection is normal, if the API address is correct, and if the server is running normally.
|
||||
|
||||
### 5. Server Error
|
||||
|
||||
**Issue**: API call returns 500 error
|
||||
**Solution**: Check server logs, view the specific error cause, and contact backend developers to resolve.
|
||||
|
||||
## 📚 Reference Documentation
|
||||
|
||||
- [FastAPI Official Documentation](https://fastapi.tiangolo.com/)
|
||||
- [Swagger UI Official Documentation](https://swagger.io/docs/open-source-tools/swagger-ui/)
|
||||
- [Redoc Official Documentation](https://redocly.com/docs/redoc/)
|
||||
|
||||
Through the introduction of this document, you should now understand how to use and call the APIs of the FastapiAdmin project. If you encounter any issues during use, please refer to the common issues and solutions, or contact the project maintainers for help.
|
||||
@@ -0,0 +1,890 @@
|
||||
---
|
||||
outline: "deep"
|
||||
title: Backend Development Guide
|
||||
---
|
||||
# Backend Development Guide
|
||||
|
||||
## 📋Project Overview
|
||||
|
||||
The backend part of FastapiAdmin is based on **Python + FastAPI + SQLAlchemy + Redis + MySQL**, providing a high-performance, scalable, and maintainable backend system.
|
||||
|
||||
### Core Features
|
||||
|
||||
- **Asynchronous Framework**: Based on FastAPI, supporting asynchronous processing for high concurrency
|
||||
- **Automatic API Documentation**: Swagger UI and ReDoc automatically generated
|
||||
- **Type Hints**: Full TypeScript support with Pydantic models
|
||||
- **ORM Integration**: SQLAlchemy for database operations
|
||||
- **Cache Support**: Redis integration for performance optimization
|
||||
- **Authentication**: JWT OAuth2 authentication mechanism
|
||||
- **Permission Control**: RBAC-based fine-grained permission management
|
||||
- **Database Migration**: Alembic for database schema management
|
||||
- **Configuration Management**: Environment-based configuration system
|
||||
- **Logging**: Comprehensive logging system
|
||||
|
||||
## 🛠️Technology Stack
|
||||
|
||||
| Category | Technology | Version | Description |
|
||||
|---------|------------|---------|-------------|
|
||||
| **Language** | Python | >=3.10 | Programming language |
|
||||
| **Framework** | FastAPI | 0.109.0 | Asynchronous web framework |
|
||||
| **ORM** | SQLAlchemy | 2.0.23 | Object Relational Mapper |
|
||||
| **Cache** | Redis | 4.5.4 | In-memory data store |
|
||||
| **Database** | MySQL | 8.0+ | Relational database |
|
||||
| **Authentication** | PyJWT | 2.6.0 | JWT token generation and verification |
|
||||
| **Validation** | Pydantic | 2.5.0 | Data validation and settings management |
|
||||
| **Migration** | Alembic | 1.12.1 | Database schema migration |
|
||||
| **CORS** | FastAPI CORS | - | Cross-Origin Resource Sharing |
|
||||
| **Dependency Injection** | FastAPI DI | - | Dependency injection system |
|
||||
|
||||
## 📁Project Structure
|
||||
|
||||
```
|
||||
backend/
|
||||
├── app/
|
||||
│ ├── api/ # API routes and controllers
|
||||
│ │ └── v1/ # API version 1
|
||||
│ │ ├── controllers/ # Request handlers
|
||||
│ │ ├── cruds/ # Data access layer
|
||||
│ │ ├── models/ # Database models
|
||||
│ │ ├── params/ # Request parameters
|
||||
│ │ ├── schemas/ # Response schemas
|
||||
│ │ └── urls/ # Route definitions
|
||||
│ ├── core/ # Core functionality
|
||||
│ │ ├── config.py # Configuration management
|
||||
│ │ ├── database.py # Database connection
|
||||
│ │ ├── security.py # Security utilities
|
||||
│ │ └── utils.py # Common utilities
|
||||
│ ├── middleware/ # Middleware
|
||||
│ │ ├── cors.py # CORS middleware
|
||||
│ │ ├── jwt.py # JWT middleware
|
||||
│ │ └── logger.py # Logging middleware
|
||||
│ ├── plugins/ # Plugins and extensions
|
||||
│ │ ├── init_app.py # Application initialization
|
||||
│ │ └── redis.py # Redis plugin
|
||||
│ ├── scripts/ # Scripts
|
||||
│ │ ├── data/ # Initialization data
|
||||
│ │ ├── alembic/ # Database migrations
|
||||
│ │ ├── initialize.py # System initialization
|
||||
│ │ └── main.py # Main script
|
||||
│ └── services/ # Business logic services
|
||||
├── env/ # Environment configuration files
|
||||
│ ├── .env.dev # Development environment
|
||||
│ └── .env.prod # Production environment
|
||||
├── main.py # Application entry point
|
||||
├── requirements.txt # Python dependencies
|
||||
├── setup.py # Package setup
|
||||
└── README.md # Backend documentation
|
||||
```
|
||||
|
||||
## 🚀Getting Started
|
||||
|
||||
### Environment Setup
|
||||
|
||||
1. **Install Python**
|
||||
|
||||
```sh
|
||||
# macOS
|
||||
brew install python@3.10
|
||||
|
||||
# Ubuntu/Debian
|
||||
sudo apt update
|
||||
sudo apt install python3.10 python3.10-venv python3.10-dev
|
||||
|
||||
# CentOS/RHEL
|
||||
sudo dnf install python3.10 python3.10-venv python3.10-devel
|
||||
```
|
||||
|
||||
2. **Install MySQL and Redis**
|
||||
|
||||
```sh
|
||||
# macOS
|
||||
brew install mysql redis
|
||||
brew services start mysql redis
|
||||
|
||||
# Ubuntu/Debian
|
||||
sudo apt update
|
||||
sudo apt install mysql-server redis-server
|
||||
sudo systemctl start mysql redis
|
||||
```
|
||||
|
||||
### Project Setup
|
||||
|
||||
1. **Clone the repository**
|
||||
|
||||
```sh
|
||||
git clone https://github.com/fastapiadmin/FastapiAdmin.git
|
||||
cd FastapiAdmin/backend
|
||||
```
|
||||
|
||||
2. **Create virtual environment**
|
||||
|
||||
```sh
|
||||
python3 -m venv .venv
|
||||
|
||||
# Activate virtual environment
|
||||
# macOS/Linux
|
||||
source .venv/bin/activate
|
||||
# Windows
|
||||
.venv\Scripts\activate
|
||||
```
|
||||
|
||||
3. **Install dependencies**
|
||||
|
||||
```sh
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
4. **Configure environment variables**
|
||||
|
||||
```sh
|
||||
cp env/.env.dev.example env/.env.dev
|
||||
# Edit env/.env.dev file
|
||||
```
|
||||
|
||||
5. **Initialize database**
|
||||
|
||||
```sh
|
||||
# Generate migration files
|
||||
python main.py revision "Initial migration" --env=dev
|
||||
|
||||
# Apply migration
|
||||
python main.py upgrade --env=dev
|
||||
|
||||
# Initialize system data
|
||||
python main.py init
|
||||
```
|
||||
|
||||
6. **Start development server**
|
||||
|
||||
```sh
|
||||
python main.py run --env=dev
|
||||
```
|
||||
|
||||
The backend API will be available at `http://localhost:8001`
|
||||
|
||||
API documentation will be available at:
|
||||
- Swagger UI: `http://localhost:8001/api/v1/docs`
|
||||
- ReDoc: `http://localhost:8001/api/v1/redoc`
|
||||
|
||||
## 📝Development Process
|
||||
|
||||
### 1. Creating a New Model
|
||||
|
||||
1. **Create model class** in `app/api/v1/models/` directory
|
||||
|
||||
```python
|
||||
# app/api/v1/models/demo/example_model.py
|
||||
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.core.database import Base
|
||||
from datetime import datetime
|
||||
|
||||
class Example(Base):
|
||||
__tablename__ = "example"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), nullable=False, index=True)
|
||||
description = Column(String(500), nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
# Relationships
|
||||
# relationship("OtherModel", back_populates="example")
|
||||
```
|
||||
|
||||
2. **Register model** in `app/scripts/alembic/env.py`
|
||||
|
||||
### 2. Creating CRUD Operations
|
||||
|
||||
1. **Create CRUD class** in `app/api/v1/cruds/` directory
|
||||
|
||||
```python
|
||||
# app/api/v1/cruds/demo/example_crud.py
|
||||
from sqlalchemy.orm import Session
|
||||
from app.api.v1.models.demo.example_model import Example
|
||||
from app.api.v1.schemas.demo.example_schema import ExampleCreate, ExampleUpdate
|
||||
|
||||
class ExampleCRUD:
|
||||
@staticmethod
|
||||
def get_by_id(db: Session, example_id: int):
|
||||
return db.query(Example).filter(Example.id == example_id).first()
|
||||
|
||||
@staticmethod
|
||||
def get_list(db: Session, skip: int = 0, limit: int = 100):
|
||||
return db.query(Example).offset(skip).limit(limit).all()
|
||||
|
||||
@staticmethod
|
||||
def create(db: Session, example: ExampleCreate):
|
||||
db_example = Example(**example.dict())
|
||||
db.add(db_example)
|
||||
db.commit()
|
||||
db.refresh(db_example)
|
||||
return db_example
|
||||
|
||||
@staticmethod
|
||||
def update(db: Session, example_id: int, example: ExampleUpdate):
|
||||
db_example = ExampleCRUD.get_by_id(db, example_id)
|
||||
if db_example:
|
||||
update_data = example.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(db_example, field, value)
|
||||
db.commit()
|
||||
db.refresh(db_example)
|
||||
return db_example
|
||||
|
||||
@staticmethod
|
||||
def delete(db: Session, example_id: int):
|
||||
db_example = ExampleCRUD.get_by_id(db, example_id)
|
||||
if db_example:
|
||||
db.delete(db_example)
|
||||
db.commit()
|
||||
return db_example
|
||||
|
||||
example_crud = ExampleCRUD()
|
||||
```
|
||||
|
||||
### 3. Creating Schemas
|
||||
|
||||
1. **Create schema classes** in `app/api/v1/schemas/` directory
|
||||
|
||||
```python
|
||||
# app/api/v1/schemas/demo/example_schema.py
|
||||
from pydantic import BaseModel, Field
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
class ExampleBase(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=100)
|
||||
description: Optional[str] = Field(None, max_length=500)
|
||||
|
||||
class ExampleCreate(ExampleBase):
|
||||
pass
|
||||
|
||||
class ExampleUpdate(BaseModel):
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
description: Optional[str] = Field(None, max_length=500)
|
||||
|
||||
class ExampleResponse(ExampleBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
class ExampleListResponse(BaseModel):
|
||||
items: list[ExampleResponse]
|
||||
total: int
|
||||
```
|
||||
|
||||
### 4. Creating Request Parameters
|
||||
|
||||
1. **Create parameter classes** in `app/api/v1/params/` directory
|
||||
|
||||
```python
|
||||
# app/api/v1/params/demo/example_param.py
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
|
||||
class ExampleListParams(BaseModel):
|
||||
page: int = Field(1, ge=1)
|
||||
page_size: int = Field(10, ge=1, le=100)
|
||||
name: Optional[str] = Field(None, max_length=100)
|
||||
```
|
||||
|
||||
### 5. Creating Controller
|
||||
|
||||
1. **Create controller class** in `app/api/v1/controllers/` directory
|
||||
|
||||
```python
|
||||
# app/api/v1/controllers/demo/example_controller.py
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from app.core.database import get_db
|
||||
from app.api.v1.cruds.demo.example_crud import example_crud
|
||||
from app.api.v1.schemas.demo.example_schema import ExampleCreate, ExampleUpdate, ExampleResponse, ExampleListResponse
|
||||
from app.api.v1.params.demo.example_param import ExampleListParams
|
||||
|
||||
router = APIRouter(prefix="/examples", tags=["examples"])
|
||||
|
||||
@router.get("", response_model=ExampleListResponse)
|
||||
def get_examples(
|
||||
params: ExampleListParams = Depends(),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
skip = (params.page - 1) * params.page_size
|
||||
examples = example_crud.get_list(db, skip=skip, limit=params.page_size)
|
||||
total = db.query(example_crud.model).count()
|
||||
return ExampleListResponse(items=examples, total=total)
|
||||
|
||||
@router.get("/{example_id}", response_model=ExampleResponse)
|
||||
def get_example(
|
||||
example_id: int,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
example = example_crud.get_by_id(db, example_id)
|
||||
if not example:
|
||||
raise HTTPException(status_code=404, detail="Example not found")
|
||||
return example
|
||||
|
||||
@router.post("", response_model=ExampleResponse, status_code=201)
|
||||
def create_example(
|
||||
example: ExampleCreate,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
return example_crud.create(db, example)
|
||||
|
||||
@router.put("/{example_id}", response_model=ExampleResponse)
|
||||
def update_example(
|
||||
example_id: int,
|
||||
example: ExampleUpdate,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
updated_example = example_crud.update(db, example_id, example)
|
||||
if not updated_example:
|
||||
raise HTTPException(status_code=404, detail="Example not found")
|
||||
return updated_example
|
||||
|
||||
@router.delete("/{example_id}", status_code=204)
|
||||
def delete_example(
|
||||
example_id: int,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
deleted_example = example_crud.delete(db, example_id)
|
||||
if not deleted_example:
|
||||
raise HTTPException(status_code=404, detail="Example not found")
|
||||
return None
|
||||
```
|
||||
|
||||
### 6. Registering Routes
|
||||
|
||||
1. **Create route file** in `app/api/v1/urls/` directory
|
||||
|
||||
```python
|
||||
# app/api/v1/urls/demo/example_url.py
|
||||
from fastapi import APIRouter
|
||||
from app.api.v1.controllers.demo.example_controller import router as example_router
|
||||
|
||||
router = APIRouter()
|
||||
router.include_router(example_router)
|
||||
```
|
||||
|
||||
2. **Register route** in `app/plugins/init_app.py`
|
||||
|
||||
```python
|
||||
# app/plugins/init_app.py
|
||||
from fastapi import FastAPI
|
||||
from app.api.v1.urls.demo.example_url import router as example_router
|
||||
|
||||
def init_routes(app: FastAPI):
|
||||
# ... existing routes
|
||||
app.include_router(example_router, prefix="/api/v1")
|
||||
```
|
||||
|
||||
### 7. Database Migration
|
||||
|
||||
1. **Generate migration file**
|
||||
|
||||
```sh
|
||||
python main.py revision "Add example table" --env=dev
|
||||
```
|
||||
|
||||
2. **Apply migration**
|
||||
|
||||
```sh
|
||||
python main.py upgrade --env=dev
|
||||
```
|
||||
|
||||
## 🔧Common Development Tasks
|
||||
|
||||
### 1. Adding a New API Endpoint
|
||||
|
||||
1. **Create model** (if needed)
|
||||
2. **Create CRUD operations** (if needed)
|
||||
3. **Create schemas** for request and response
|
||||
4. **Create controller** with endpoint logic
|
||||
5. **Register route** in URL configuration
|
||||
6. **Add to migration** (if database changes)
|
||||
7. **Test endpoint** using Swagger UI
|
||||
|
||||
### 2. Authentication and Authorization
|
||||
|
||||
#### JWT Authentication
|
||||
|
||||
```python
|
||||
# app/core/security.py
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Union
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
from app.core.config import settings
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
|
||||
to_encode = data.copy()
|
||||
if expires_delta:
|
||||
expire = datetime.utcnow() + expires_delta
|
||||
else:
|
||||
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
def verify_token(token: str, credentials_exception):
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
username: str = payload.get("sub")
|
||||
if username is None:
|
||||
raise credentials_exception
|
||||
return username
|
||||
except JWTError:
|
||||
raise credentials_exception
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str):
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
def get_password_hash(password: str):
|
||||
return pwd_context.hash(password)
|
||||
```
|
||||
|
||||
#### Dependency Injection for Authentication
|
||||
|
||||
```python
|
||||
# app/api/v1/controllers/user_controller.py
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from sqlalchemy.orm import Session
|
||||
from app.core.database import get_db
|
||||
from app.core.security import verify_token
|
||||
from app.api.v1.models.user_model import User
|
||||
from app.api.v1.cruds.user_crud import user_crud
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
|
||||
|
||||
async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
username = verify_token(token, credentials_exception)
|
||||
user = user_crud.get_by_username(db, username=username)
|
||||
if user is None:
|
||||
raise credentials_exception
|
||||
return user
|
||||
|
||||
@router.get("/me", response_model=UserResponse)
|
||||
def read_users_me(current_user: User = Depends(get_current_user)):
|
||||
return current_user
|
||||
```
|
||||
|
||||
### 3. Permission Control
|
||||
|
||||
#### RBAC Model
|
||||
|
||||
FastapiAdmin uses Role-Based Access Control (RBAC) for permission management:
|
||||
|
||||
1. **Roles**: Define roles with specific permissions
|
||||
2. **Permissions**: Define what actions can be performed
|
||||
3. **Users**: Assign roles to users
|
||||
4. **Resources**: Define protected resources (endpoints, data)
|
||||
|
||||
#### Permission Checker
|
||||
|
||||
```python
|
||||
# app/core/security.py
|
||||
def check_permission(current_user: User, required_permission: str) -> bool:
|
||||
"""Check if user has required permission"""
|
||||
# Check if user is admin
|
||||
if current_user.is_admin:
|
||||
return True
|
||||
|
||||
# Check user roles and permissions
|
||||
for role in current_user.roles:
|
||||
for permission in role.permissions:
|
||||
if permission.code == required_permission:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
# Usage in controller
|
||||
@router.get("/protected")
|
||||
def protected_route(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
if not check_permission(current_user, "protected_resource:read"):
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
return {"message": "Access granted"}
|
||||
```
|
||||
|
||||
### 4. Configuration Management
|
||||
|
||||
#### Environment Variables
|
||||
|
||||
FastapiAdmin uses environment variables for configuration management:
|
||||
|
||||
```python
|
||||
# app/core/config.py
|
||||
from pydantic_settings import BaseSettings
|
||||
from typing import Optional
|
||||
|
||||
class Settings(BaseSettings):
|
||||
# Project settings
|
||||
PROJECT_NAME: str = "FastapiAdmin"
|
||||
API_V1_STR: str = "/api/v1"
|
||||
|
||||
# Database settings
|
||||
DATABASE_URL: str
|
||||
|
||||
# Redis settings
|
||||
REDIS_URL: str
|
||||
|
||||
# Security settings
|
||||
SECRET_KEY: str
|
||||
ALGORITHM: str = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
|
||||
# CORS settings
|
||||
BACKEND_CORS_ORIGINS: list[str] = ["*"]
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
case_sensitive = True
|
||||
|
||||
settings = Settings()
|
||||
```
|
||||
|
||||
#### Environment Files
|
||||
|
||||
Environment variables are stored in `.env` files for different environments:
|
||||
|
||||
```
|
||||
# env/.env.dev
|
||||
# Database
|
||||
DATABASE_URL="mysql+aiomysql://admin:123456@localhost:3306/fastapiadmin_dev"
|
||||
|
||||
# Redis
|
||||
REDIS_URL="redis://localhost:6379/0"
|
||||
|
||||
# Security
|
||||
SECRET_KEY="your-secret-key-here"
|
||||
```
|
||||
|
||||
### 5. Logging
|
||||
|
||||
#### Logger Configuration
|
||||
|
||||
```python
|
||||
# app/core/logger.py
|
||||
import logging
|
||||
import sys
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from app.core.config import settings
|
||||
|
||||
# Create logger
|
||||
logger = logging.getLogger(settings.PROJECT_NAME)
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
# Create formatter
|
||||
formatter = logging.Formatter(
|
||||
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
|
||||
# Create console handler
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(logging.INFO)
|
||||
console_handler.setFormatter(formatter)
|
||||
|
||||
# Create file handler
|
||||
file_handler = RotatingFileHandler(
|
||||
"app.log", maxBytes=10485760, backupCount=5
|
||||
)
|
||||
file_handler.setLevel(logging.INFO)
|
||||
file_handler.setFormatter(formatter)
|
||||
|
||||
# Add handlers to logger
|
||||
logger.addHandler(console_handler)
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
export logger
|
||||
```
|
||||
|
||||
#### Usage
|
||||
|
||||
```python
|
||||
from app.core.logger import logger
|
||||
|
||||
logger.info("Application started")
|
||||
logger.error("An error occurred")
|
||||
logger.debug("Debug information")
|
||||
```
|
||||
|
||||
## 📡API Design
|
||||
|
||||
### 1. RESTful API Principles
|
||||
|
||||
FastapiAdmin follows RESTful API design principles:
|
||||
|
||||
- **Resource Naming**: Use nouns for endpoints (e.g., `/users`, `/products`)
|
||||
- **HTTP Methods**: Use appropriate HTTP methods for operations:
|
||||
- `GET`: Retrieve resources
|
||||
- `POST`: Create resources
|
||||
- `PUT`: Update resources
|
||||
- `DELETE`: Delete resources
|
||||
- **Status Codes**: Use standard HTTP status codes:
|
||||
- `200 OK`: Successful GET, PUT
|
||||
- `201 Created`: Successful POST
|
||||
- `204 No Content`: Successful DELETE
|
||||
- `400 Bad Request`: Invalid request
|
||||
- `401 Unauthorized`: Authentication required
|
||||
- `403 Forbidden`: Insufficient permissions
|
||||
- `404 Not Found`: Resource not found
|
||||
- `500 Internal Server Error`: Server error
|
||||
|
||||
### 2. API Response Format
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"id": 1,
|
||||
"name": "Example",
|
||||
"description": "This is an example"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Pagination
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"items": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Item 1"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "Item 2"
|
||||
}
|
||||
],
|
||||
"total": 100,
|
||||
"page": 1,
|
||||
"page_size": 10
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🔒Security Best Practices
|
||||
|
||||
### 1. Input Validation
|
||||
|
||||
- **Use Pydantic**: Validate all input data with Pydantic models
|
||||
- **Type Hints**: Use Python type hints for type safety
|
||||
- **Parameter Constraints**: Set constraints on parameters (min/max length, regex patterns)
|
||||
- **Sanitization**: Sanitize user input to prevent injection attacks
|
||||
|
||||
### 2. Authentication
|
||||
|
||||
- **JWT Tokens**: Use secure JWT tokens with proper expiration
|
||||
- **Password Hashing**: Use bcrypt for password hashing
|
||||
- **Token Rotation**: Implement token rotation for enhanced security
|
||||
- **Multi-factor Authentication**: Support MFA for sensitive operations
|
||||
|
||||
### 3. Authorization
|
||||
|
||||
- **RBAC**: Use Role-Based Access Control for granular permissions
|
||||
- **Least Privilege**: Assign minimum required permissions to users
|
||||
- **Permission Checks**: Verify permissions for every protected resource
|
||||
- **Audit Logs**: Log permission changes and access attempts
|
||||
|
||||
### 4. Data Protection
|
||||
|
||||
- **Encryption**: Encrypt sensitive data at rest and in transit
|
||||
- **HTTPS**: Use HTTPS for all communications
|
||||
- **CORS**: Configure CORS properly to restrict cross-origin requests
|
||||
- **CSRF Protection**: Implement CSRF protection for forms
|
||||
|
||||
### 5. Rate Limiting
|
||||
|
||||
- **API Rate Limits**: Limit requests per user/IP to prevent abuse
|
||||
- **Brute Force Protection**: Implement delays for failed login attempts
|
||||
- **Throttling**: Throttle sensitive operations (password resets, etc.)
|
||||
|
||||
## 📦Deployment
|
||||
|
||||
### 1. Docker Deployment
|
||||
|
||||
#### Dockerfile
|
||||
|
||||
```dockerfile
|
||||
# Dockerfile
|
||||
FROM python:3.10-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 8001
|
||||
|
||||
CMD ["python", "main.py", "run", "--env=prod"]
|
||||
```
|
||||
|
||||
#### Docker Compose
|
||||
|
||||
```yaml
|
||||
# docker-compose.yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
backend:
|
||||
build: ./backend
|
||||
ports:
|
||||
- "8001:8001"
|
||||
depends_on:
|
||||
- db
|
||||
- redis
|
||||
environment:
|
||||
- DATABASE_URL=mysql+aiomysql://admin:123456@db:3306/fastapiadmin
|
||||
- REDIS_URL=redis://redis:6379/0
|
||||
- SECRET_KEY=your-secret-key-here
|
||||
|
||||
db:
|
||||
image: mysql:8.0
|
||||
environment:
|
||||
- MYSQL_ROOT_PASSWORD=root
|
||||
- MYSQL_DATABASE=fastapiadmin
|
||||
- MYSQL_USER=admin
|
||||
- MYSQL_PASSWORD=123456
|
||||
volumes:
|
||||
- mysql_data:/var/lib/mysql
|
||||
|
||||
redis:
|
||||
image: redis:7.0
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
|
||||
volumes:
|
||||
mysql_data:
|
||||
redis_data:
|
||||
```
|
||||
|
||||
### 2. Manual Deployment
|
||||
|
||||
1. **Prepare server** with Python, MySQL, and Redis installed
|
||||
2. **Upload code** to server
|
||||
3. **Install dependencies** in virtual environment
|
||||
4. **Configure environment variables** for production
|
||||
5. **Set up Nginx** as reverse proxy
|
||||
6. **Use Gunicorn** with Uvicorn workers
|
||||
7. **Set up systemd service** for automatic startup
|
||||
|
||||
### 3. Cloud Deployment
|
||||
|
||||
FastapiAdmin can be deployed to various cloud platforms:
|
||||
|
||||
- **AWS**: EC2 + RDS + ElastiCache
|
||||
- **Azure**: App Service + Azure Database for MySQL + Azure Cache for Redis
|
||||
- **GCP**: Compute Engine + Cloud SQL + Memorystore
|
||||
- **Aliyun**: ECS + RDS + Redis
|
||||
- **Tencent Cloud**: CVM + TDSQL + Redis
|
||||
|
||||
## 🐛Common Issues and Solutions
|
||||
|
||||
### 1. Database Connection Issues
|
||||
|
||||
**Issue**: Database connection fails
|
||||
**Solution**: Check database credentials, ensure database service is running, verify network connectivity
|
||||
|
||||
### 2. Redis Connection Issues
|
||||
|
||||
**Issue**: Redis connection fails
|
||||
**Solution**: Check Redis URL, ensure Redis service is running, verify network connectivity
|
||||
|
||||
### 3. CORS Errors
|
||||
|
||||
**Issue**: Cross-Origin Resource Sharing errors
|
||||
**Solution**: Configure CORS properly in backend settings, ensure frontend URL is allowed
|
||||
|
||||
### 4. JWT Token Issues
|
||||
|
||||
**Issue**: Token validation fails
|
||||
**Solution**: Check SECRET_KEY consistency, verify token format, ensure token hasn't expired
|
||||
|
||||
### 5. Permission Denied Errors
|
||||
|
||||
**Issue**: 403 Forbidden errors
|
||||
**Solution**: Check user permissions, ensure role assignments are correct, verify permission strings
|
||||
|
||||
### 6. Database Migration Errors
|
||||
|
||||
**Issue**: Migration fails with SQL errors
|
||||
**Solution**: Check migration files, ensure models are correctly defined, verify database schema
|
||||
|
||||
### 7. Performance Issues
|
||||
|
||||
**Issue**: API response times are slow
|
||||
**Solution**: Use Redis caching, optimize database queries, implement pagination, consider async operations
|
||||
|
||||
## 📚Best Practices
|
||||
|
||||
### 1. Coding Standards
|
||||
|
||||
- **PEP 8**: Follow PEP 8 Python coding standards
|
||||
- **Type Hints**: Use type hints for better code clarity and type checking
|
||||
- **Docstrings**: Add docstrings for functions, classes, and modules
|
||||
- **Modularity**: Keep code modular and reusable
|
||||
- **Error Handling**: Implement proper error handling and logging
|
||||
|
||||
### 2. Database Best Practices
|
||||
|
||||
- **Indexing**: Add indexes for frequently queried columns
|
||||
- **Query Optimization**: Use efficient queries, avoid N+1 queries
|
||||
- **Transaction Management**: Use transactions for atomic operations
|
||||
- **Connection Pooling**: Use connection pooling for better performance
|
||||
- **Backup**: Implement regular database backups
|
||||
|
||||
### 3. Security Best Practices
|
||||
|
||||
- **Input Validation**: Validate all user input
|
||||
- **Password Hashing**: Never store plain text passwords
|
||||
- **HTTPS**: Use HTTPS for all communications
|
||||
- **Rate Limiting**: Implement rate limiting to prevent abuse
|
||||
- **Audit Logs**: Log security-related events
|
||||
|
||||
### 4. Performance Best Practices
|
||||
|
||||
- **Caching**: Use Redis for caching frequently accessed data
|
||||
- **Async Operations**: Use async/await for I/O operations
|
||||
- **Pagination**: Implement pagination for large datasets
|
||||
- **Compression**: Use gzip compression for API responses
|
||||
- **Load Balancing**: Use load balancing for high-traffic applications
|
||||
|
||||
### 5. Deployment Best Practices
|
||||
|
||||
- **Environment Separation**: Use separate environments for development, testing, and production
|
||||
- **Configuration Management**: Use environment variables for configuration
|
||||
- **Automated Deployment**: Implement CI/CD pipelines
|
||||
- **Monitoring**: Set up monitoring and alerting
|
||||
- **Rollback Plan**: Have a rollback plan for failed deployments
|
||||
|
||||
## 🎉Conclusion
|
||||
|
||||
The backend part of FastapiAdmin provides a robust, secure, and high-performance foundation for building enterprise-level applications. By following the guidelines in this document, you can develop maintainable, scalable backend systems that meet the needs of modern applications.
|
||||
|
||||
For more detailed information about FastAPI, SQLAlchemy, or other technologies used in FastapiAdmin, please refer to their official documentation:
|
||||
|
||||
- [FastAPI Documentation](https://fastapi.tiangolo.com/)
|
||||
- [SQLAlchemy Documentation](https://docs.sqlalchemy.org/)
|
||||
- [Redis Python Documentation](https://redis-py.readthedocs.io/)
|
||||
- [Pydantic Documentation](https://docs.pydantic.dev/)
|
||||
- [Alembic Documentation](https://alembic.sqlalchemy.org/)
|
||||
@@ -0,0 +1 @@
|
||||
# Custom Development Guide
|
||||
@@ -0,0 +1,715 @@
|
||||
---
|
||||
outline: "deep"
|
||||
title: Deployment Guide
|
||||
---
|
||||
# Deployment Guide
|
||||
|
||||
## 📋Deployment Overview
|
||||
|
||||
FastapiAdmin supports multiple deployment methods to meet different production environment needs, including Docker Compose, manual deployment, and cloud service deployment.
|
||||
|
||||
### Deployment Methods Comparison
|
||||
|
||||
| Method | Advantages | Disadvantages | Recommended Scenario |
|
||||
|--------|------------|---------------|---------------------|
|
||||
| **Docker Compose** | Easy deployment, consistent environment, easy scaling | Requires Docker knowledge | Production environment, testing environment |
|
||||
| **Manual Deployment** | Full control, no Docker dependency | Complex setup, environment inconsistencies | Specialized environments, small-scale deployment |
|
||||
| **Cloud Service** | Managed infrastructure, auto-scaling | Higher cost, less control | Enterprise production, rapid deployment |
|
||||
|
||||
## 🐳Docker Compose Deployment
|
||||
|
||||
### 1. Prerequisites
|
||||
|
||||
- **Docker** installed on the server
|
||||
- **Docker Compose** installed on the server
|
||||
- **Server ports** 80 (Nginx) and 8001 (backend) available
|
||||
- **Minimum server requirements**: 2GB RAM, 2 CPU cores, 20GB disk space
|
||||
|
||||
### 2. Deployment Steps
|
||||
|
||||
#### Step 1: Clone the repository
|
||||
|
||||
```sh
|
||||
git clone https://github.com/fastapiadmin/FastapiAdmin.git
|
||||
cd FastapiAdmin
|
||||
```
|
||||
|
||||
#### Step 2: Configure environment variables
|
||||
|
||||
```sh
|
||||
# Copy environment configuration files
|
||||
cp backend/env/.env.prod.example backend/env/.env.prod
|
||||
cp frontend/.env.production.example frontend/.env.production
|
||||
|
||||
# Edit environment configuration files
|
||||
# Backend: Set database connection, Redis connection, JWT secret key, etc.
|
||||
# Frontend: Set API base URL
|
||||
```
|
||||
|
||||
#### Step 3: Execute deployment script
|
||||
|
||||
```sh
|
||||
# Give script execution permission
|
||||
chmod +x start.sh
|
||||
|
||||
# Execute deployment script
|
||||
./start.sh
|
||||
|
||||
# Check deployment status
|
||||
docker compose ps
|
||||
|
||||
# View logs
|
||||
docker logs -f fastapiadmin-backend
|
||||
```
|
||||
|
||||
### 3. Docker Compose Configuration
|
||||
|
||||
```yaml
|
||||
# docker-compose.yaml
|
||||
version: '3.8'
|
||||
|
||||
networks:
|
||||
fastapiadmin-network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
mysql-data:
|
||||
redis-data:
|
||||
logs:
|
||||
|
||||
|
||||
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
container_name: fastapiadmin-mysql
|
||||
restart: always
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD:-root}"
|
||||
MYSQL_DATABASE: "${MYSQL_DATABASE:-fastapiadmin}"
|
||||
MYSQL_USER: "${MYSQL_USER:-admin}"
|
||||
MYSQL_PASSWORD: "${MYSQL_PASSWORD:-123456}"
|
||||
volumes:
|
||||
- mysql-data:/var/lib/mysql
|
||||
- ./devops/mysql/init.sql:/docker-entrypoint-initdb.d/init.sql
|
||||
ports:
|
||||
- "3306:3306"
|
||||
networks:
|
||||
- fastapiadmin-network
|
||||
|
||||
|
||||
redis:
|
||||
image: redis:7.0
|
||||
container_name: fastapiadmin-redis
|
||||
restart: always
|
||||
volumes:
|
||||
- redis-data:/data
|
||||
ports:
|
||||
- "6379:6379"
|
||||
networks:
|
||||
- fastapiadmin-network
|
||||
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: fastapiadmin-backend
|
||||
restart: always
|
||||
environment:
|
||||
- ENVIRONMENT=prod
|
||||
volumes:
|
||||
- ./backend:/app
|
||||
- logs:/app/logs
|
||||
ports:
|
||||
- "8001:8001"
|
||||
depends_on:
|
||||
- mysql
|
||||
- redis
|
||||
networks:
|
||||
- fastapiadmin-network
|
||||
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
container_name: fastapiadmin-frontend
|
||||
restart: always
|
||||
volumes:
|
||||
- ./frontend:/app
|
||||
ports:
|
||||
- "5173:5173"
|
||||
networks:
|
||||
- fastapiadmin-network
|
||||
|
||||
|
||||
nginx:
|
||||
build:
|
||||
context: ./devops/nginx
|
||||
dockerfile: Dockerfile
|
||||
container_name: fastapiadmin-nginx
|
||||
restart: always
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- ./devops/nginx/nginx.conf:/etc/nginx/nginx.conf
|
||||
- ./devops/nginx/ssl:/etc/nginx/ssl
|
||||
depends_on:
|
||||
- backend
|
||||
- frontend
|
||||
networks:
|
||||
- fastapiadmin-network
|
||||
```
|
||||
|
||||
### 4. Nginx Configuration
|
||||
|
||||
```nginx
|
||||
# devops/nginx/nginx.conf
|
||||
worker_processes 1;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
include mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
sendfile on;
|
||||
keepalive_timeout 65;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
|
||||
location / {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html index.htm;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://backend:8001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
|
||||
location /web/ {
|
||||
proxy_pass http://frontend:5173;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
|
||||
error_page 500 502 503 504 /50x.html;
|
||||
location = /50x.html {
|
||||
root /usr/share/nginx/html;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Common Docker Commands
|
||||
|
||||
```sh
|
||||
# View all containers
|
||||
docker compose ps
|
||||
|
||||
# Start all services
|
||||
docker compose up -d
|
||||
|
||||
# Stop all services
|
||||
docker compose down
|
||||
|
||||
# Restart all services
|
||||
docker compose restart
|
||||
|
||||
# View logs for a specific container
|
||||
docker logs -f fastapiadmin-backend
|
||||
|
||||
# View logs for all containers
|
||||
docker compose logs
|
||||
|
||||
# Enter a container
|
||||
docker exec -it fastapiadmin-backend bash
|
||||
|
||||
# Check container resource usage
|
||||
docker stats
|
||||
|
||||
# Remove unused containers, networks, images
|
||||
docker system prune -f
|
||||
```
|
||||
|
||||
## 🔧Manual Deployment
|
||||
|
||||
### 1. Prerequisites
|
||||
|
||||
- **Python 3.10+** installed
|
||||
- **Node.js 20+** installed
|
||||
- **MySQL 8.0+** installed and running
|
||||
- **Redis 7.0+** installed and running
|
||||
- **Nginx** installed (for reverse proxy)
|
||||
- **System dependencies**: build-essential, libpq-dev, etc.
|
||||
|
||||
### 2. Backend Deployment
|
||||
|
||||
#### Step 1: Install dependencies
|
||||
|
||||
```sh
|
||||
cd FastapiAdmin/backend
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
#### Step 2: Configure environment variables
|
||||
|
||||
```sh
|
||||
cp env/.env.prod.example env/.env.prod
|
||||
# Edit env/.env.prod file
|
||||
```
|
||||
|
||||
#### Step 3: Database initialization
|
||||
|
||||
```sh
|
||||
# Generate migration files
|
||||
python main.py revision "Initial migration" --env=prod
|
||||
|
||||
# Apply migration
|
||||
python main.py upgrade --env=prod
|
||||
|
||||
# Initialize system data
|
||||
python main.py init
|
||||
```
|
||||
|
||||
#### Step 4: Start backend service
|
||||
|
||||
```sh
|
||||
# Using Gunicorn with Uvicorn workers
|
||||
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app --bind 0.0.0.0:8001
|
||||
|
||||
# Or using systemd service (recommended for production)
|
||||
# Create systemd service file
|
||||
```
|
||||
|
||||
### 3. Frontend Deployment
|
||||
|
||||
#### Step 1: Install dependencies
|
||||
|
||||
```sh
|
||||
cd FastapiAdmin/frontend
|
||||
npm install -g pnpm
|
||||
pnpm install
|
||||
```
|
||||
|
||||
#### Step 2: Configure environment variables
|
||||
|
||||
```sh
|
||||
cp .env.production.example .env.production
|
||||
# Edit .env.production file
|
||||
```
|
||||
|
||||
#### Step 3: Build frontend
|
||||
|
||||
```sh
|
||||
pnpm run build
|
||||
# The built files will be in the dist directory
|
||||
```
|
||||
|
||||
#### Step 4: Deploy frontend files
|
||||
|
||||
```sh
|
||||
# Copy built files to Nginx web root
|
||||
cp -r dist/* /usr/share/nginx/html/
|
||||
```
|
||||
|
||||
### 4. Nginx Configuration
|
||||
|
||||
```nginx
|
||||
# /etc/nginx/sites-available/fastapiadmin
|
||||
server {
|
||||
listen 80;
|
||||
server_name your-domain.com;
|
||||
|
||||
location / {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html index.htm;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://localhost:8001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
|
||||
location /static/ {
|
||||
alias /usr/share/nginx/html/static/;
|
||||
expires 30d;
|
||||
}
|
||||
|
||||
error_page 500 502 503 504 /50x.html;
|
||||
location = /50x.html {
|
||||
root /usr/share/nginx/html;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Systemd Service Configuration
|
||||
|
||||
#### Backend Service
|
||||
|
||||
```ini
|
||||
# /etc/systemd/system/fastapiadmin-backend.service
|
||||
[Unit]
|
||||
Description=FastapiAdmin Backend Service
|
||||
After=network.target mysql.service redis.service
|
||||
|
||||
[Service]
|
||||
User=ubuntu
|
||||
WorkingDirectory=/path/to/FastapiAdmin/backend
|
||||
ExecStart=/path/to/FastapiAdmin/backend/venv/bin/gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app --bind 0.0.0.0:8001
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
#### Start and enable service
|
||||
|
||||
```sh
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl start fastapiadmin-backend
|
||||
sudo systemctl enable fastapiadmin-backend
|
||||
sudo systemctl status fastapiadmin-backend
|
||||
```
|
||||
|
||||
## ☁️Cloud Service Deployment
|
||||
|
||||
### 1. AWS Deployment
|
||||
|
||||
#### Architecture
|
||||
|
||||
- **EC2**: For running application containers
|
||||
- **RDS**: Managed MySQL database
|
||||
- **ElastiCache**: Managed Redis cache
|
||||
- **Elastic Load Balancing**: For distributing traffic
|
||||
- **Auto Scaling**: For automatic scaling based on load
|
||||
- **S3**: For storing static files and backups
|
||||
- **CloudWatch**: For monitoring and logging
|
||||
|
||||
#### Deployment Steps
|
||||
|
||||
1. **Create VPC**: Set up a Virtual Private Cloud
|
||||
2. **Launch EC2 Instances**: Create EC2 instances for application
|
||||
3. **Set up RDS**: Create MySQL database instance
|
||||
4. **Set up ElastiCache**: Create Redis cache cluster
|
||||
5. **Configure Security Groups**: Set up proper security rules
|
||||
6. **Deploy Application**: Use Docker Compose on EC2 instances
|
||||
7. **Set up Load Balancer**: Configure ELB for traffic distribution
|
||||
8. **Configure Auto Scaling**: Set up scaling policies
|
||||
9. **Set up CloudWatch**: Configure monitoring and alerts
|
||||
|
||||
### 2. Azure Deployment
|
||||
|
||||
#### Architecture
|
||||
|
||||
- **App Service**: For running application
|
||||
- **Azure Database for MySQL**: Managed MySQL database
|
||||
- **Azure Cache for Redis**: Managed Redis cache
|
||||
- **Azure Load Balancer**: For distributing traffic
|
||||
- **Azure Storage**: For storing static files
|
||||
- **Azure Monitor**: For monitoring and logging
|
||||
|
||||
#### Deployment Steps
|
||||
|
||||
1. **Create Resource Group**: Set up a resource group
|
||||
2. **Create App Service Plan**: Choose appropriate plan
|
||||
3. **Deploy App Service**: Deploy application to App Service
|
||||
4. **Create Azure Database for MySQL**: Set up managed database
|
||||
5. **Create Azure Cache for Redis**: Set up managed cache
|
||||
6. **Configure Connection Strings**: Set up environment variables
|
||||
7. **Set up Monitoring**: Configure Azure Monitor
|
||||
8. **Enable Auto Scaling**: Set up scaling rules
|
||||
|
||||
### 3. Google Cloud Deployment
|
||||
|
||||
#### Architecture
|
||||
|
||||
- **Compute Engine**: For running application containers
|
||||
- **Cloud SQL**: Managed MySQL database
|
||||
- **Memorystore**: Managed Redis cache
|
||||
- **Load Balancing**: For distributing traffic
|
||||
- **Auto Scaling**: For automatic scaling
|
||||
- **Cloud Storage**: For storing static files
|
||||
- **Cloud Monitoring**: For monitoring and logging
|
||||
|
||||
#### Deployment Steps
|
||||
|
||||
1. **Create Project**: Set up a Google Cloud project
|
||||
2. **Enable APIs**: Enable necessary APIs
|
||||
3. **Create Compute Engine Instances**: Set up VM instances
|
||||
4. **Create Cloud SQL Instance**: Set up managed MySQL database
|
||||
5. **Create Memorystore Instance**: Set up managed Redis cache
|
||||
6. **Deploy Application**: Use Docker Compose on Compute Engine
|
||||
7. **Set up Load Balancer**: Configure load balancing
|
||||
8. **Set up Auto Scaling**: Configure instance groups and scaling
|
||||
9. **Set up Monitoring**: Configure Cloud Monitoring
|
||||
|
||||
### 4. Aliyun Deployment
|
||||
|
||||
#### Architecture
|
||||
|
||||
- **ECS**: Elastic Compute Service for running application
|
||||
- **RDS**: Relational Database Service for MySQL
|
||||
- **Redis**: ApsaraDB for Redis
|
||||
- **SLB**: Server Load Balancer
|
||||
- **Auto Scaling**: Auto Scaling Service
|
||||
- **OSS**: Object Storage Service for static files
|
||||
- **CloudMonitor**: For monitoring and alerts
|
||||
|
||||
#### Deployment Steps
|
||||
|
||||
1. **Create ECS Instances**: Set up virtual servers
|
||||
2. **Create RDS Instance**: Set up managed MySQL database
|
||||
3. **Create Redis Instance**: Set up managed Redis cache
|
||||
4. **Configure Security Groups**: Set up network security
|
||||
5. **Deploy Application**: Use Docker Compose on ECS
|
||||
6. **Set up SLB**: Configure load balancing
|
||||
7. **Set up Auto Scaling**: Configure scaling rules
|
||||
8. **Set up OSS**: Configure object storage
|
||||
9. **Set up CloudMonitor**: Configure monitoring
|
||||
|
||||
## 📊Monitoring and Maintenance
|
||||
|
||||
### 1. Monitoring Tools
|
||||
|
||||
#### Server Monitoring
|
||||
|
||||
- **Prometheus + Grafana**: Comprehensive monitoring solution
|
||||
- **CloudWatch**: For AWS deployments
|
||||
- **Azure Monitor**: For Azure deployments
|
||||
- **Cloud Monitoring**: For GCP deployments
|
||||
- **Nagios**: Open-source monitoring
|
||||
|
||||
#### Application Monitoring
|
||||
|
||||
- **New Relic**: Application performance monitoring
|
||||
- **Datadog**: Comprehensive monitoring platform
|
||||
- **Sentry**: Error tracking and monitoring
|
||||
- **ELK Stack**: Log management and analysis
|
||||
|
||||
### 2. Key Monitoring Metrics
|
||||
|
||||
#### Server Metrics
|
||||
|
||||
- **CPU Usage**: Monitor CPU utilization
|
||||
- **Memory Usage**: Monitor memory consumption
|
||||
- **Disk Usage**: Monitor disk space and I/O
|
||||
- **Network Traffic**: Monitor network throughput
|
||||
- **Load Average**: Monitor system load
|
||||
|
||||
#### Application Metrics
|
||||
|
||||
- **Response Time**: Monitor API response times
|
||||
- **Request Rate**: Monitor number of requests
|
||||
- **Error Rate**: Monitor error rates
|
||||
- **Database Queries**: Monitor database performance
|
||||
- **Cache Hit Rate**: Monitor Redis cache performance
|
||||
|
||||
#### Business Metrics
|
||||
|
||||
- **Active Users**: Monitor number of active users
|
||||
- **Transaction Volume**: Monitor business transactions
|
||||
- **Conversion Rates**: Monitor conversion metrics
|
||||
- **Revenue**: Monitor business revenue
|
||||
|
||||
### 3. Log Management
|
||||
|
||||
#### Centralized Logging
|
||||
|
||||
- **ELK Stack**: Elasticsearch, Logstash, Kibana
|
||||
- **Graylog**: Log management platform
|
||||
- **Fluentd**: Log collector and aggregator
|
||||
- **Splunk**: Enterprise log management
|
||||
|
||||
#### Log Rotation
|
||||
|
||||
```sh
|
||||
# Configure log rotation for application logs
|
||||
# /etc/logrotate.d/fastapiadmin
|
||||
/path/to/FastapiAdmin/backend/logs/*.log {
|
||||
daily
|
||||
rotate 7
|
||||
compress
|
||||
delaycompress
|
||||
missingok
|
||||
notifempty
|
||||
create 644 ubuntu ubuntu
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Backup and Recovery
|
||||
|
||||
#### Database Backup
|
||||
|
||||
- **Automated Backups**: Enable automated RDS/Azure SQL/Cloud SQL backups
|
||||
- **Manual Backups**: Schedule regular manual backups
|
||||
- **Point-in-Time Recovery**: Set up for critical data
|
||||
- **Off-site Backups**: Store backups in separate location
|
||||
|
||||
#### Application Backup
|
||||
|
||||
- **Code Repository**: Use Git for code versioning
|
||||
- **Configuration Files**: Back up configuration files
|
||||
- **Static Files**: Back up user-uploaded files
|
||||
- **Docker Images**: Store Docker images in registry
|
||||
|
||||
#### Recovery Plan
|
||||
|
||||
- **Disaster Recovery Plan**: Document recovery procedures
|
||||
- **Regular Testing**: Test backup restoration process
|
||||
- **Recovery Time Objective**: Define acceptable downtime
|
||||
- **Recovery Point Objective**: Define acceptable data loss
|
||||
|
||||
### 5. Security Maintenance
|
||||
|
||||
#### Regular Updates
|
||||
|
||||
- **Operating System**: Keep OS updated
|
||||
- **Application Dependencies**: Update dependencies regularly
|
||||
- **Security Patches**: Apply security patches promptly
|
||||
- **Docker Images**: Use official, updated images
|
||||
|
||||
#### Security Scanning
|
||||
|
||||
- **Vulnerability Scanning**: Regularly scan for vulnerabilities
|
||||
- **Penetration Testing**: Periodic penetration testing
|
||||
- **Security Audits**: Regular security audits
|
||||
- **Compliance Checks**: Ensure compliance with standards
|
||||
|
||||
#### Access Control
|
||||
|
||||
- **Least Privilege**: Follow least privilege principle
|
||||
- **Access Reviews**: Regularly review user access
|
||||
- **Multi-factor Authentication**: Enable MFA for admin access
|
||||
- **SSH Key Management**: Properly manage SSH keys
|
||||
|
||||
## 🐛Common Issues and Solutions
|
||||
|
||||
### 1. Deployment Issues
|
||||
|
||||
#### Docker Compose Issues
|
||||
|
||||
**Issue**: Docker Compose fails to start
|
||||
**Solution**: Check Docker logs, ensure ports are available, verify environment variables
|
||||
|
||||
**Issue**: Database connection fails
|
||||
**Solution**: Check MySQL service status, verify database credentials, ensure network connectivity
|
||||
|
||||
**Issue**: Redis connection fails
|
||||
**Solution**: Check Redis service status, verify Redis URL, ensure network connectivity
|
||||
|
||||
#### Nginx Issues
|
||||
|
||||
**Issue**: 502 Bad Gateway error
|
||||
**Solution**: Check backend service status, verify proxy configuration, ensure backend is running
|
||||
|
||||
**Issue**: 404 Not Found error
|
||||
**Solution**: Check Nginx root directory, verify file permissions, ensure files exist
|
||||
|
||||
**Issue**: SSL certificate errors
|
||||
**Solution**: Check SSL configuration, verify certificate validity, ensure proper certificate chain
|
||||
|
||||
### 2. Performance Issues
|
||||
|
||||
**Issue**: High CPU usage
|
||||
**Solution**: Optimize application code, increase server resources, implement caching
|
||||
|
||||
**Issue**: Slow database queries
|
||||
**Solution**: Optimize SQL queries, add indexes, consider database sharding
|
||||
|
||||
**Issue**: Memory leaks
|
||||
**Solution**: Profile application, fix memory leaks, increase memory limit
|
||||
|
||||
**Issue**: Network latency
|
||||
**Solution**: Use CDN for static files, optimize API responses, consider edge caching
|
||||
|
||||
### 3. Security Issues
|
||||
|
||||
**Issue**: Unauthorized access
|
||||
**Solution**: Implement proper authentication, use HTTPS, configure firewalls
|
||||
|
||||
**Issue**: SQL injection
|
||||
**Solution**: Use parameterized queries, validate input, use ORM
|
||||
|
||||
**Issue**: Cross-site scripting (XSS)
|
||||
**Solution**: Sanitize user input, use Content Security Policy, escape output
|
||||
|
||||
**Issue**: Cross-site request forgery (CSRF)
|
||||
**Solution**: Implement CSRF tokens, validate Origin header, use SameSite cookies
|
||||
|
||||
### 4. Scaling Issues
|
||||
|
||||
**Issue**: Application not scaling properly
|
||||
**Solution**: Check auto-scaling configuration, ensure load balancer is working, optimize application for scaling
|
||||
|
||||
**Issue**: Database bottleneck
|
||||
**Solution**: Implement database replication, use read replicas, consider sharding
|
||||
|
||||
**Issue**: Cache inconsistency
|
||||
**Solution**: Implement proper cache invalidation, use distributed cache, consider cache warming
|
||||
|
||||
**Issue**: Session management
|
||||
**Solution**: Use Redis for session storage, implement stateless sessions, consider JWT
|
||||
|
||||
## 📚Best Practices
|
||||
|
||||
### 1. Deployment Best Practices
|
||||
|
||||
- **Infrastructure as Code**: Use Terraform or CloudFormation for infrastructure
|
||||
- **CI/CD Pipeline**: Implement continuous integration and deployment
|
||||
- **Environment Consistency**: Use Docker for consistent environments
|
||||
- **Rolling Deployments**: Use rolling deployments to minimize downtime
|
||||
- **Blue-Green Deployment**: Use blue-green deployment for zero downtime
|
||||
- **Canary Releases**: Test new versions with a subset of users
|
||||
|
||||
### 2. Monitoring Best Practices
|
||||
|
||||
- **Comprehensive Monitoring**: Monitor all components of the system
|
||||
- **Proactive Alerting**: Set up alerts for potential issues
|
||||
- **Anomaly Detection**: Use machine learning for anomaly detection
|
||||
- **Log Aggregation**: Centralize logs for easier analysis
|
||||
- **Performance Baselines**: Establish performance baselines for comparison
|
||||
- **Dashboards**: Create comprehensive monitoring dashboards
|
||||
|
||||
### 3. Security Best Practices
|
||||
|
||||
- **Defense in Depth**: Implement multiple layers of security
|
||||
- **Principle of Least Privilege**: Grant minimum required permissions
|
||||
- **Regular Audits**: Conduct regular security audits
|
||||
- **Security Training**: Train developers on security best practices
|
||||
- **Incident Response Plan**: Have a plan for security incidents
|
||||
- **Compliance**: Ensure compliance with relevant regulations
|
||||
|
||||
### 4. Maintenance Best Practices
|
||||
|
||||
- **Regular Backups**: Schedule regular backups
|
||||
- **Backup Testing**: Test backup restoration regularly
|
||||
- **Documentation**: Keep comprehensive documentation
|
||||
- **Change Management**: Implement change management process
|
||||
- **Disaster Recovery Plan**: Have a disaster recovery plan
|
||||
- **Knowledge Transfer**: Ensure knowledge is shared among team members
|
||||
|
||||
## 🎉Conclusion
|
||||
|
||||
FastapiAdmin provides flexible deployment options to meet different production environment needs. Whether you choose Docker Compose for ease of deployment, manual deployment for full control, or cloud services for managed infrastructure, FastapiAdmin can be deployed reliably and securely.
|
||||
|
||||
By following the best practices outlined in this guide, you can ensure that your FastapiAdmin deployment is scalable, secure, and maintainable. Regular monitoring, backups, and security maintenance are essential for keeping your application running smoothly and securely.
|
||||
|
||||
For more detailed information about specific deployment methods or cloud providers, please refer to their official documentation.
|
||||
@@ -0,0 +1 @@
|
||||
# Examples
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,450 @@
|
||||
---
|
||||
outline: "deep"
|
||||
title: Development Guidelines
|
||||
---
|
||||
# Development Guidelines
|
||||
|
||||
## 📚 Guidelines Overview
|
||||
|
||||
To ensure project code consistency, readability, and maintainability, the FastapiAdmin project has established the following development guidelines. All developers participating in the project should follow these guidelines.
|
||||
|
||||
## 🎨 Frontend Development Guidelines
|
||||
|
||||
### 1. Code Style
|
||||
|
||||
#### 1.1 TypeScript Guidelines
|
||||
|
||||
- Use TypeScript strict mode (`"strict": true`)
|
||||
- Add type annotations for all variables, functions, and interfaces
|
||||
- Avoid using `any` type unless the type is truly indeterminable
|
||||
- Use interfaces to define object types, not type aliases
|
||||
- Use enums to define constant sets
|
||||
- Use `type` to define union types and intersection types
|
||||
- Use `as const` assertions to ensure type safety
|
||||
- Use `readonly` modifiers to protect immutable data
|
||||
- Use `unknown` type to handle data of uncertain types
|
||||
|
||||
#### 1.2 Vue Guidelines
|
||||
|
||||
- Use Composition API
|
||||
- Use `<script setup lang="ts">` syntax
|
||||
- Use PascalCase for component naming
|
||||
- Use camelCase for variable and function naming
|
||||
- Use UPPER_SNAKE_CASE for constant naming
|
||||
- Use `ref()` to define reactive variables
|
||||
- Use `computed()` to define computed properties
|
||||
- Use `watch()` or `watchEffect()` to monitor changes
|
||||
- Use `onMounted()`, `onUnmounted()` and other lifecycle hooks
|
||||
- Use `defineProps()` to define component props with types
|
||||
- Use `defineEmits()` to define component events with types
|
||||
- Use `defineExpose()` to define exposed component properties and methods
|
||||
|
||||
#### 1.3 CSS Guidelines
|
||||
|
||||
- Use UnoCSS atomic CSS
|
||||
- Avoid using inline styles
|
||||
- Use BEM naming convention (if not using UnoCSS)
|
||||
- Use kebab-case for class names
|
||||
- Avoid using ID selectors
|
||||
- Use CSS variables for theme management
|
||||
- Avoid using `!important` modifier
|
||||
- Use flexbox layout to ensure cross-platform consistency
|
||||
- Use CSS Grid layout appropriately
|
||||
- Optimize CSS selector priority
|
||||
|
||||
### 2. Component Development Best Practices
|
||||
|
||||
- **Single Responsibility Principle**: Each component should be responsible for only one function
|
||||
- **Props Design**:
|
||||
- Use `required` and `default` to clearly specify props requirements
|
||||
- Add validation for complex props
|
||||
- Use `withDefaults()` to set default values for props
|
||||
- **Events Design**:
|
||||
- Use kebab-case for event naming
|
||||
- Event parameter types should be clear
|
||||
- Avoid passing too many parameters in events
|
||||
- **Slots Design**:
|
||||
- Use named slots to improve readability
|
||||
- Add default content for slots
|
||||
- Use scoped slots to pass data
|
||||
- **Styles Design**:
|
||||
- Use `scoped` styles to avoid conflicts
|
||||
- Use `:deep()` selectors appropriately
|
||||
- Avoid using global styles in components
|
||||
|
||||
### 3. State Management Best Practices
|
||||
|
||||
- **Modular Design**: Split stores by functional modules
|
||||
- **State Definition**:
|
||||
- Use `interface` to define state types
|
||||
- Initialize all states
|
||||
- Avoid using overly nested state structures
|
||||
- **Actions Design**:
|
||||
- Handle asynchronous operations
|
||||
- Use try/catch to catch errors
|
||||
- Use transactions when committing multiple mutations
|
||||
- **Getters Design**:
|
||||
- Cache calculation results
|
||||
- Avoid modifying state in getters
|
||||
- Use parameterized getters appropriately
|
||||
|
||||
### 4. API Call Best Practices
|
||||
|
||||
- **Modular Management**: Organize API interfaces by functional modules
|
||||
- **Request Encapsulation**:
|
||||
- Unified handling of request headers
|
||||
- Unified error handling
|
||||
- Unified loading state handling
|
||||
- **Response Handling**:
|
||||
- Type definitions for response data structures
|
||||
- Unified handling of response status codes
|
||||
- Appropriate handling of empty data and edge cases
|
||||
- **Request Optimization**:
|
||||
- Use debounce and throttle
|
||||
- Cache results of frequent requests
|
||||
- Use concurrent requests appropriately
|
||||
|
||||
### 5. Performance Optimization Recommendations
|
||||
|
||||
- **Code Splitting**: Use route lazy loading and component lazy loading
|
||||
- **Resource Optimization**:
|
||||
- Compress images and static resources
|
||||
- Use WebP format images
|
||||
- Use CDN appropriately
|
||||
- **Rendering Optimization**:
|
||||
- Use `v-memo` to cache calculation results
|
||||
- Use `v-if` and `v-show` appropriately
|
||||
- Avoid using complex expressions in templates
|
||||
- **Network Optimization**:
|
||||
- Use HTTP/2 or HTTP/3
|
||||
- Enable Gzip or Brotli compression
|
||||
- Set caching strategies appropriately
|
||||
|
||||
### 6. Testing Best Practices
|
||||
|
||||
- **Test Layering**: Unit tests, integration tests, end-to-end tests
|
||||
- **Test Coverage**:
|
||||
- 100% coverage for core functionality
|
||||
- 80%+ coverage for complex logic
|
||||
- 50%+ coverage for simple functionality
|
||||
- **Testing Tools**:
|
||||
- Use Vitest for unit testing
|
||||
- Use Playwright for end-to-end testing
|
||||
- Use Vue Test Utils for component testing
|
||||
|
||||
### 7. Code Review Points
|
||||
|
||||
- **Type Safety**: Check if TypeScript type definitions are correct
|
||||
- **Code Quality**: Check if code is concise and clear
|
||||
- **Performance Issues**: Check for performance bottlenecks
|
||||
- **Security Issues**: Check for security vulnerabilities
|
||||
- **Guideline Compliance**: Check if project development guidelines are followed
|
||||
|
||||
## 🐍 Backend Development Guidelines
|
||||
|
||||
### 1. Code Style
|
||||
|
||||
#### 1.1 Python Guidelines
|
||||
|
||||
- Follow PEP 8 code style
|
||||
- Use 4 spaces for indentation
|
||||
- Line length should not exceed 100 characters
|
||||
- Leave two blank lines between functions and classes
|
||||
- Leave one blank line between methods
|
||||
- Group import statements by standard library, third-party library, and local library
|
||||
|
||||
#### 1.2 FastAPI Guidelines
|
||||
|
||||
- Use FastAPI decorators to define routes
|
||||
- Use Pydantic models to define request and response data
|
||||
- Use dependency injection for authentication and authorization
|
||||
- Use path parameters and query parameters
|
||||
- Use HTTPException for error handling
|
||||
- Use Depends to inject dependencies
|
||||
|
||||
### 2. Directory Structure
|
||||
|
||||
```
|
||||
backend/app/
|
||||
├── api/ # API interfaces
|
||||
├── common/ # Common code
|
||||
├── config/ # Configuration management
|
||||
├── core/ # Core functionality
|
||||
├── plugin/ # Plugin system
|
||||
├── scripts/ # Script tools
|
||||
└── utils/ # Utility functions
|
||||
```
|
||||
|
||||
### 3. Plugin Development Guidelines
|
||||
|
||||
- Plugin directories should start with `module_`
|
||||
- Plugins should include files such as `controller.py`, `model.py`, `schema.py`, `service.py`, `crud.py`
|
||||
- Controllers should use `APIRouter` to define routes
|
||||
- Route prefixes should correspond to module names (module_xxx -> /xxx)
|
||||
- Controllers should use `OperationLogRoute` to record operation logs
|
||||
- Interfaces should use `AuthPermission` for permission control
|
||||
|
||||
### 4. Database Guidelines
|
||||
|
||||
- Use SQLAlchemy 2.0 ORM
|
||||
- Use Alembic for database migrations
|
||||
- Model classes should inherit from `Base`
|
||||
- Model classes should define `__tablename__` attribute
|
||||
- Field naming should use snake_case
|
||||
- Table names should use snake_case plural form
|
||||
- Foreign keys should be defined using `ForeignKey`
|
||||
- Relationships should be defined using `relationship`
|
||||
|
||||
### 5. Authentication and Authorization Guidelines
|
||||
|
||||
- Use JWT for authentication
|
||||
- Use RBAC model for permission management
|
||||
- Interfaces should add permission control decorators
|
||||
- Permission string format: `module:controller:action`
|
||||
- Permissions should be configured in role management
|
||||
|
||||
### 6. Error Handling Guidelines
|
||||
|
||||
- Use `HTTPException` for HTTP errors
|
||||
- Use custom exception handling for global errors
|
||||
- Error responses should have a unified format
|
||||
- Errors should be logged
|
||||
|
||||
### 7. Logging Guidelines
|
||||
|
||||
- Use Python standard library `logging` module
|
||||
- Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL
|
||||
- Logs should include time, level, module, message, and other information
|
||||
- Key operations should be logged
|
||||
- Errors should be logged with detailed information
|
||||
|
||||
## 📦 FastApp Mobile Development Guidelines
|
||||
|
||||
### 1. Code Style
|
||||
|
||||
- Follow frontend development guidelines
|
||||
- Use TypeScript strict mode
|
||||
- Use Vue 3 Composition API
|
||||
- Use `<script setup lang="ts">` syntax
|
||||
- Use PascalCase for component naming
|
||||
- Use camelCase for variable and function naming
|
||||
|
||||
### 2. Directory Structure
|
||||
|
||||
```
|
||||
FastApp/src/
|
||||
├── api/ # API interfaces
|
||||
├── components/ # Components
|
||||
├── composables/ # Composable functions
|
||||
├── constants/ # Constant definitions
|
||||
├── enums/ # Enum definitions
|
||||
├── layouts/ # Layout components
|
||||
├── pages/ # Page files
|
||||
├── router/ # Router configuration
|
||||
├── static/ # Static resources
|
||||
├── store/ # State management
|
||||
├── styles/ # Style files
|
||||
├── types/ # TypeScript type definitions
|
||||
├── utils/ # Utility functions
|
||||
├── App.vue # Application root component
|
||||
└── main.ts # Application entry file
|
||||
```
|
||||
|
||||
### 3. Page Development Guidelines
|
||||
|
||||
- Page components should be placed in the `pages` directory
|
||||
- Page directories should use kebab-case
|
||||
- Page components should include `index.vue` file
|
||||
- Page components can include auxiliary files such as `data.ts`, `types.ts`
|
||||
- Page components should use lifecycle hooks such as `onLoad()`, `onShow()`
|
||||
- Page navigation should use APIs such as `uni.navigateTo()`, `uni.switchTab()`
|
||||
|
||||
### 4. API Call Guidelines
|
||||
|
||||
- Follow frontend API call guidelines
|
||||
- Use the encapsulated `request.ts` utility
|
||||
- API interfaces should be classified by module
|
||||
- API calls should handle error situations
|
||||
- API calls should display loading state
|
||||
|
||||
### 5. Cross-Platform Adaptation Guidelines
|
||||
|
||||
- Use conditional compilation to handle platform differences
|
||||
- Use `#ifdef`, `#ifndef`, `#endif` directives
|
||||
- Platform-specific APIs should add conditional compilation
|
||||
- Styles should consider differences between platforms
|
||||
- Layouts should use flexbox to ensure cross-platform consistency
|
||||
|
||||
## 🎯 Git Commit Guidelines
|
||||
|
||||
### 1. Branch Management
|
||||
|
||||
- `master`: Main branch, used for releasing production versions
|
||||
- `dev`: Development branch, used for integration development
|
||||
- `feature/xxx`: Feature branch, used for developing new features
|
||||
- `bugfix/xxx`: Fix branch, used for fixing bugs
|
||||
- `hotfix/xxx`: Hotfix branch, used for emergency fixes in production environment
|
||||
|
||||
### 2. Commit Message Guidelines
|
||||
|
||||
Commit messages should follow the following format:
|
||||
|
||||
```
|
||||
<type>(<scope>): <subject>
|
||||
|
||||
<body>
|
||||
|
||||
<footer>
|
||||
```
|
||||
|
||||
#### 2.1 Type
|
||||
|
||||
- `feat`: New feature
|
||||
- `fix`: Bug fix
|
||||
- `docs`: Documentation changes
|
||||
- `style`: Code style changes
|
||||
- `refactor`: Code refactoring
|
||||
- `test`: Test code changes
|
||||
- `chore`: Build tool or dependency changes
|
||||
- `revert`: Revert commit
|
||||
|
||||
#### 2.2 Scope
|
||||
|
||||
- Optional, used to specify the scope of changes
|
||||
- For example: `api`, `component`, `page`, `store`, etc.
|
||||
|
||||
#### 2.3 Subject
|
||||
|
||||
- Brief commit message, not exceeding 50 characters
|
||||
- Use imperative mood, starting with a verb
|
||||
- First letter lowercase
|
||||
- No period at the end
|
||||
|
||||
#### 2.4 Body
|
||||
|
||||
- Optional, detailed commit message
|
||||
- Each line not exceeding 72 characters
|
||||
- Explain why, not how
|
||||
|
||||
#### 2.5 Footer
|
||||
|
||||
- Optional, used to reference issues or bugs
|
||||
- For example: `Closes #123`, `Fixes #456`
|
||||
|
||||
### 3. Commit Examples
|
||||
|
||||
```
|
||||
feat(api): Add user login endpoint
|
||||
|
||||
- Implement user login functionality
|
||||
- Add JWT authentication
|
||||
- Handle login error cases
|
||||
|
||||
Closes #123
|
||||
```
|
||||
|
||||
```
|
||||
fix(frontend): Fix homepage carousel display issue
|
||||
|
||||
- Fix carousel height calculation error
|
||||
- Optimize carousel transition animation
|
||||
|
||||
Fixes #456
|
||||
```
|
||||
|
||||
```
|
||||
docs: Update development documentation
|
||||
|
||||
- Add API documentation
|
||||
- Improve deployment guide
|
||||
```
|
||||
|
||||
### 4. Pull Request Guidelines
|
||||
|
||||
- Pull Requests should merge from feature branches to dev branch
|
||||
- Pull Request titles should be clear and semantic
|
||||
- Pull Request descriptions should detail the changes
|
||||
- Pull Requests should include related issue links
|
||||
- Pull Requests should pass all tests
|
||||
- Pull Requests should be reviewed by at least one reviewer
|
||||
|
||||
## 🔧 Toolchain Guidelines
|
||||
|
||||
### 1. Frontend Toolchain
|
||||
|
||||
- Use Vite as build tool
|
||||
- Use ESLint for code linting
|
||||
- Use Prettier for code formatting
|
||||
- Use Stylelint for style linting
|
||||
- Use Husky for Git hook management
|
||||
- Use Commitlint for commit message checking
|
||||
|
||||
### 2. Backend Toolchain
|
||||
|
||||
- Use Poetry or pip for dependency management
|
||||
- Use Pylint or Flake8 for code linting
|
||||
- Use Black for code formatting
|
||||
- Use MyPy for type checking
|
||||
- Use pytest for testing
|
||||
|
||||
## 💡 Development Process Guidelines
|
||||
|
||||
### 1. Requirements Analysis
|
||||
|
||||
- Clarify functional requirements
|
||||
- Analyze business logic
|
||||
- Determine technical solutions
|
||||
|
||||
### 2. Design Phase
|
||||
|
||||
- Design database table structure
|
||||
- Design API interfaces
|
||||
- Design frontend pages
|
||||
- Design component structure
|
||||
|
||||
### 3. Development Phase
|
||||
|
||||
- Create branches
|
||||
- Implement features
|
||||
- Write tests
|
||||
- Run tests
|
||||
|
||||
### 4. Testing Phase
|
||||
|
||||
- Unit tests
|
||||
- Integration tests
|
||||
- End-to-end tests
|
||||
- Performance tests
|
||||
|
||||
### 5. Deployment Phase
|
||||
|
||||
- Build production version
|
||||
- Deploy to test environment
|
||||
- Perform regression testing
|
||||
- Deploy to production environment
|
||||
|
||||
### 6. Maintenance Phase
|
||||
|
||||
- Monitor system running status
|
||||
- Handle bugs and issues
|
||||
- Perform performance optimization
|
||||
- Perform feature iterations
|
||||
|
||||
## 📚 Reference Materials
|
||||
|
||||
- [TypeScript Official Documentation](https://www.typescriptlang.org/docs/)
|
||||
- [Vue Official Documentation](https://vuejs.org/docs/)
|
||||
- [FastAPI Official Documentation](https://fastapi.tiangolo.com/)
|
||||
- [SQLAlchemy Official Documentation](https://docs.sqlalchemy.org/)
|
||||
- [PEP 8 Style Guide](https://peps.python.org/pep-0008/)
|
||||
- [Conventional Commits](https://www.conventionalcommits.org/)
|
||||
- [ESLint Official Documentation](https://eslint.org/docs/)
|
||||
- [Prettier Official Documentation](https://prettier.io/docs/en/)
|
||||
|
||||
## 🤝 Contribution Guidelines
|
||||
|
||||
If you have any suggestions or improvements for the development guidelines, please submit an Issue or Pull Request. We will carefully consider every suggestion and continuously improve the development guidelines.
|
||||
|
||||
## 📄 License Agreement
|
||||
|
||||
This development guidelines document adopts the MIT License, consistent with the FastapiAdmin project.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,278 @@
|
||||
---
|
||||
outline: "deep"
|
||||
title: Project Overview
|
||||
---
|
||||
# Project Overview
|
||||
|
||||
## 📋FastApiAdmin Introduction
|
||||
|
||||
**FastApiAdmin** is a **completely open-source, highly modular, and technologically advanced modern rapid development platform** designed to help developers efficiently build high-quality enterprise-level backend systems. The project adopts a **frontend-backend separation architecture**, integrating the Python backend framework `FastAPI` and the mainstream frontend framework `Vue3` to achieve multi-end unified development, providing a one-stop out-of-the-box development experience.
|
||||
|
||||
### Core Values
|
||||
|
||||
- **Reduce Development Costs**: Out-of-the-box functional modules reduce repetitive development work
|
||||
- **Improve Development Efficiency**: Unified technology stack and development specifications accelerate project delivery
|
||||
- **Ensure System Quality**: Strict code quality control and testing processes
|
||||
- **Flexible Scalability**: Modular design supports business customization and function extension
|
||||
|
||||
### Technical Advantages
|
||||
|
||||
- **Backend**: Based on FastAPI asynchronous framework, excellent performance, automatically generates API documentation
|
||||
- **Frontend**: Based on Vue3 + TypeScript + ElementPlus, type-safe, good development experience
|
||||
- **Mobile**: Based on Uni App, supports multi-platform deployment
|
||||
- **Database**: Supports MySQL and MongoDB to meet different business scenario needs
|
||||
- **Cache**: Integrated Redis to improve system response speed
|
||||
- **Deployment**: Supports Docker containerized deployment, simplifying operation and maintenance work
|
||||
|
||||
## 🎯Application Scenarios
|
||||
|
||||
- **Enterprise Internal Management Systems**: Human resources, finance, OA and other systems
|
||||
- **Business Operation Platforms**: E-commerce, content management, customer management and other systems
|
||||
- **Data Analysis Platforms**: Data visualization, report statistics and other systems
|
||||
- **API Management Platforms**: Interface management, documentation management and other systems
|
||||
- **Multi-platform Applications**: Application scenarios that require both Web and mobile terminals
|
||||
|
||||
## 📦Project Structure Overview
|
||||
|
||||
The project has been split into three independent repositories for separate development and maintenance:
|
||||
|
||||
### 1. FastapiAdmin Main Project
|
||||
|
||||
```sh
|
||||
FastapiAdmin/
|
||||
├─ backend/ # Backend project
|
||||
│ ├─ app/ # Core application code
|
||||
│ │ ├─ api/ # API interfaces
|
||||
│ │ │ └─ v1/ # API version
|
||||
│ │ │ ├─ module_common/ # Common module
|
||||
│ │ │ ├─ module_monitor/ # Monitoring module
|
||||
│ │ │ └─ module_system/ # System module
|
||||
│ │ ├─ common/ # Common code
|
||||
│ │ ├─ config/ # Configuration management
|
||||
│ │ ├─ core/ # Core functionality
|
||||
│ │ ├─ plugin/ # Plugin system
|
||||
│ │ │ ├─ module_application/ # Application module
|
||||
│ │ │ ├─ module_example/ # Example module
|
||||
│ │ │ └─ module_generator/ # Code generation module
|
||||
│ │ ├─ scripts/ # Script tools
|
||||
│ │ └─ utils/ # Utility functions
|
||||
│ ├─ alembic/ # Database migration
|
||||
│ ├─ env/ # Environment configuration
|
||||
│ ├─ static/ # Static resources
|
||||
│ ├─ tests/ # Test code
|
||||
│ ├─ README.md # Backend documentation
|
||||
│ ├─ main.py # Backend entry
|
||||
│ └─ requirements.txt # Python dependencies
|
||||
├─ frontend/ # Frontend project
|
||||
│ ├─ src/ # Source code
|
||||
│ │ ├─ api/ # API interfaces
|
||||
│ │ ├─ assets/ # Resource files
|
||||
│ │ ├─ components/ # Components
|
||||
│ │ ├─ composables/ # Composables
|
||||
│ │ ├─ constants/ # Constants
|
||||
│ │ ├─ directives/ # Directives
|
||||
│ │ ├─ enums/ # Enums
|
||||
│ │ ├─ lang/ # Internationalization
|
||||
│ │ ├─ layouts/ # Layouts
|
||||
│ │ ├─ plugins/ # Plugins
|
||||
│ │ ├─ router/ # Router
|
||||
│ │ ├─ store/ # State management
|
||||
│ │ ├─ styles/ # Styles
|
||||
│ │ ├─ types/ # Type definitions
|
||||
│ │ ├─ utils/ # Utility functions
|
||||
│ │ └─ views/ # Pages
|
||||
│ ├─ public/ # Static resources
|
||||
│ ├─ package.json # Frontend dependencies
|
||||
│ └─ README.md # Frontend documentation
|
||||
├─ devops/ # DevOps project
|
||||
│ ├─ backend/ # Backend deployment configuration
|
||||
│ ├─ nginx/ # Nginx configuration
|
||||
│ └─ redis/ # Redis configuration
|
||||
├─ docker-compose.yaml # Deployment file
|
||||
├─ deploy.sh # Deployment script
|
||||
├─ LICENSE # License
|
||||
└─ README.md # Project documentation
|
||||
```
|
||||
|
||||
### 2. FastApp Mobile Application
|
||||
|
||||
```sh
|
||||
FastApp/
|
||||
├─ src/ # Source code directory
|
||||
│ ├─ api/ # API interfaces
|
||||
│ │ ├─ auth.ts # Authentication interfaces
|
||||
│ │ ├─ file.ts # File interfaces
|
||||
│ │ └─ user.ts # User interfaces
|
||||
│ ├─ components/ # Components
|
||||
│ │ ├─ cu-date-query/ # Date query component
|
||||
│ │ ├─ cu-picker/ # Picker component
|
||||
│ │ ├─ qiun-error/ # Error component
|
||||
│ │ └─ qiun-loading/ # Loading component
|
||||
│ ├─ composables/ # Composables
|
||||
│ │ ├─ useNavigationBar.ts # Navigation bar management
|
||||
│ │ ├─ useStomp.ts # WebSocket management
|
||||
│ │ └─ useTabbar.ts # Tabbar management
|
||||
│ ├─ constants/ # Constants
|
||||
│ │ ├─ index.ts # Constants definition
|
||||
│ │ └─ storage.constant.ts # Storage keys
|
||||
│ ├─ enums/ # Enums
|
||||
│ │ ├─ api-code.enum.ts # API error codes
|
||||
│ │ └─ api-header.enum.ts # API headers
|
||||
│ ├─ layouts/ # Layout components
|
||||
│ │ ├─ default.vue # Default layout
|
||||
│ │ └─ tabbar.vue # Tabbar layout
|
||||
│ ├─ pages/ # Page files
|
||||
│ │ ├─ index/ # Home page
|
||||
│ │ │ ├─ data.ts # Data definition
|
||||
│ │ │ ├─ index.vue # Home page component
|
||||
│ │ │ └─ types.ts # Type definitions
|
||||
│ │ ├─ login/ # Login page
|
||||
│ │ │ └─ index.vue # Login component
|
||||
│ │ ├─ mine/ # Personal center
|
||||
│ │ │ ├─ about/ # About page
|
||||
│ │ │ ├─ faq/ # FAQ page
|
||||
│ │ │ ├─ feedback/ # Feedback page
|
||||
│ │ │ ├─ profile/ # Profile page
|
||||
│ │ │ ├─ settings/ # Settings page
|
||||
│ │ │ └─ index.vue # Personal center component
|
||||
│ │ └─ work/ # Workbench
|
||||
│ │ ├─ data.ts # Data definition
|
||||
│ │ ├─ index.vue # Workbench component
|
||||
│ │ └─ types.ts # Type definitions
|
||||
│ ├─ router/ # Router configuration
|
||||
│ │ └─ index.ts # Router configuration file
|
||||
│ ├─ static/ # Static resources
|
||||
│ │ ├─ icons/ # Icons
|
||||
│ │ ├─ images/ # Images
|
||||
│ │ └─ logo.png # Logo
|
||||
│ ├─ store/ # State management
|
||||
│ │ ├─ modules/ # Modules
|
||||
│ │ │ ├─ theme.store.ts # Theme management
|
||||
│ │ │ └─ user.store.ts # User management
|
||||
│ │ └─ index.ts # State management configuration
|
||||
│ ├─ styles/ # Style files
|
||||
│ │ └─ index.scss # Global styles
|
||||
│ ├─ types/ # TypeScript definitions
|
||||
│ ├─ utils/ # Utility functions
|
||||
│ │ ├─ auth.ts # Authentication utility
|
||||
│ │ ├─ color.ts # Color utility
|
||||
│ │ ├─ index.ts # Utility functions
|
||||
│ │ ├─ request.ts # Request utility
|
||||
│ │ └─ storage.ts # Storage utility
|
||||
│ ├─ App.vue # Application root component
|
||||
│ ├─ main.ts # Application entry file
|
||||
│ ├─ manifest.json # Application configuration file
|
||||
│ ├─ pages.json # Page router configuration
|
||||
│ └─ theme.json # Theme configuration
|
||||
├─ public/ # Static resources
|
||||
├─ .env.development # Development environment configuration
|
||||
├─ .env.production # Production environment configuration
|
||||
├─ package.json # Project dependencies
|
||||
├─ pages.config.ts # Page configuration
|
||||
├─ tsconfig.json # TypeScript configuration
|
||||
├─ unocss.config.ts # UnoCSS configuration
|
||||
└─ vite.config.ts # Vite configuration
|
||||
```
|
||||
|
||||
### 3. FastDocs Official Documentation
|
||||
|
||||
```sh
|
||||
FastDocs/
|
||||
├─ docs/ # Documentation source
|
||||
│ ├─ development/ # Development documentation
|
||||
│ ├─ en/ # English documentation
|
||||
│ ├─ overview/ # Overview documentation
|
||||
│ ├─ quickstart/ # Quick start
|
||||
│ ├─ public/ # Static resources
|
||||
│ └─ index.md # Home page
|
||||
├─ .vitepress/ # VitePress configuration
|
||||
│ ├─ theme/ # Theme configuration
|
||||
│ └─ config.ts # Site configuration
|
||||
├─ package.json # Project dependencies
|
||||
└─ README.md # Project documentation
|
||||
```
|
||||
|
||||
## ✨Core Highlights
|
||||
|
||||
| Feature | Description |
|
||||
| ---- | ---- |
|
||||
| 🔭 Rapid Development | A completely open-source modern rapid development platform designed to help developers efficiently build high-quality enterprise-level backend systems. |
|
||||
| 🌐 Full-Stack Integration | Frontend-backend separation, integrating Python (FastAPI) + Vue3 multi-end development, supporting Web and mobile terminals. |
|
||||
| 🧱 Modular Design | System functions are highly decoupled, plugin-based architecture, supporting automatic route discovery and registration, easy to extend and maintain. |
|
||||
| ⚡️ High Performance | Using FastAPI asynchronous framework + Redis cache to optimize interface response speed. |
|
||||
| 🔒 Secure Authentication | Support for JWT OAuth2 authentication mechanism to ensure system security. |
|
||||
| 📊 Permission Management | RBAC model implements fine-grained permission control at the menu, button, and data levels. |
|
||||
| 🚀 Quick Deployment | Support for Docker/Docker Compose/Nginx one-click deployment. |
|
||||
| 📄 Developer-Friendly | Provide comprehensive Chinese documentation + Chinese interface + visual toolchain, reducing learning costs. |
|
||||
| 🧩 Quick Integration | Based on Vue3, Vite5, Pinia, ElementPlus and other mainstream frontend technology stacks, out-of-the-box. |
|
||||
| 📱 Mobile Support | FastApp mobile application developed based on UniApp, supporting multi-end operation (H5, WeChat Mini Program, Alipay Mini Program, App, etc.). |
|
||||
| 🤖 Agent Framework | Integrated agent framework, providing AI capabilities. |
|
||||
| 🎨 Theme Customization | Support for dark/light theme switching, providing personalized interface experience. |
|
||||
| 🌍 Internationalization Support | Built-in internationalization framework, supporting multi-language switching. |
|
||||
| 📈 Data Visualization | Integrated chart library, providing rich data visualization capabilities. |
|
||||
| 🛠️ Code Generation | Built-in code generation tool, improving development efficiency. |
|
||||
|
||||
## 🔧Technology Stack
|
||||
|
||||
| Category | Technology | Description |
|
||||
|---------|------------|-------------|
|
||||
| **Backend Framework** | FastAPI / Uvicorn / Pydantic 2.0 / Alembic | Modern, high-performance asynchronous framework with enforced type constraints and data migration |
|
||||
| **ORM** | SQLAlchemy 2.0 | Powerful ORM library |
|
||||
| **Scheduled Tasks** | APScheduler | Easily implement scheduled tasks |
|
||||
| **Authentication** | PyJWT | Implement JWT authentication |
|
||||
| **Frontend Framework** | Vue3 / Vite5 / Pinia / TypeScript | Rapidly develop Vue3 applications |
|
||||
| **Frontend Tools** | ESLint / Prettier / Stylelint | Code quality and style tools |
|
||||
| **Mobile Framework** | UniApp / Vue3 / TypeScript | Cross-platform mobile application development |
|
||||
| **UI Library** | ElementPlus (Web) / Wot Design Uni (Mobile) | Enterprise-level UI component library |
|
||||
| **CSS Framework** | UnoCSS / SCSS | Atomic CSS and preprocessor |
|
||||
| **Database** | MySQL / PostgreSQL / SQLite | Relational database support |
|
||||
| **Cache** | Redis | Powerful cache database |
|
||||
| **API Documentation** | Swagger / Redoc | Automatically generate API documentation |
|
||||
| **Deployment** | Docker / Nginx / Docker Compose | Rapid project deployment |
|
||||
| **Monitoring** | Built-in Server Monitoring / Cache Monitoring | System operation status monitoring |
|
||||
| **Internationalization** | i18n | Multi-language support |
|
||||
| **Data Visualization** | ECharts | Rich data visualization capabilities |
|
||||
|
||||
## ✨Built-in Modules
|
||||
|
||||
### FastapiAdmin Main Project Modules
|
||||
|
||||
| Module Name | Submodules | Description |
|
||||
|---------|------------|-------------|
|
||||
| **Dashboard** | Workbench, Analysis Page | System overview and data analysis |
|
||||
| **System Management** | User, Role, Menu, Department, Position, Dictionary, Configuration, Announcement | Core system management functions |
|
||||
| **Monitoring Management** | Online Users, Server Monitoring, Cache Monitoring | System operation status monitoring |
|
||||
| **Task Management** | Scheduled Tasks | Asynchronous task scheduling management |
|
||||
| **Log Management** | Operation Logs | User behavior auditing |
|
||||
| **Development Tools** | Code Generation, Form Builder, API Documentation | Tools to improve development efficiency |
|
||||
|
||||
### FastApp Mobile Application Modules
|
||||
|
||||
| Module Name | Submodules | Description |
|
||||
|---------|------------|-------------|
|
||||
| **Home** | Carousel, Quick Navigation, Announcements, Data Statistics | Mobile home page display |
|
||||
| **Workbench** | Business function entry, supports permission control | Mobile core function area |
|
||||
| **Personal Center** | Personal Information, Settings, FAQ, Feedback | User personal related functions |
|
||||
| **User Authentication** | Login, Registration, Password Reset | User identity verification |
|
||||
| **Data Statistics** | Real-time visitor count, page views and other data display | Business data visualization |
|
||||
|
||||
## 📞Contact Information
|
||||
|
||||
If you have any questions or suggestions about the project, please contact us through the following ways:
|
||||
|
||||
- **GitHub**: [fastapiadmin/FastapiAdmin](https://github.com/fastapiadmin/FastapiAdmin)
|
||||
- **Gitee**: [fastapiadmin/FastapiAdmin](https://gitee.com/fastapiadmin/FastapiAdmin)
|
||||
- **Email**: 948080782@qq.com
|
||||
|
||||
## 🤝Contribution Guide
|
||||
|
||||
We welcome community contributions, including but not limited to:
|
||||
|
||||
- Submit bug reports and feature suggestions
|
||||
- Improve code quality and performance
|
||||
- Perfect documentation and examples
|
||||
- Develop new functional modules
|
||||
|
||||
## 📄License
|
||||
|
||||
This project adopts the MIT license. For details, see the [LICENSE](https://github.com/fastapiadmin/FastapiAdmin/blob/master/LICENSE) file.
|
||||
@@ -0,0 +1,400 @@
|
||||
---
|
||||
outline: "deep"
|
||||
title: Quick Start
|
||||
---
|
||||
# Quick Start
|
||||
|
||||
## 🍪Demo Environment
|
||||
|
||||
- Official Website: <https://service.fastapiadmin.com>
|
||||
- Demo Address: <https://service.fastapiadmin.com/web>
|
||||
- Mini Program Address: <https://service.fastapiadmin.com/app>
|
||||
- Admin Account: `admin` Password: `123456`
|
||||
- Demo Account: `demo` Password: `123456`
|
||||
|
||||
## 👷Installation and Usage
|
||||
|
||||
### Version Description
|
||||
|
||||
| Type | Technology Stack | Version |
|
||||
|------|-----------------|---------|
|
||||
| Backend | Python | >=3.10 |
|
||||
| Backend | FastAPI | 0.109 |
|
||||
| Frontend | Node.js | >= 20.0 (recommended to use the latest version) |
|
||||
| Frontend | npm | 16.14 |
|
||||
| Frontend | Vue3 | 3.3 |
|
||||
| Web UI | ElementPlus | 2.10.4 |
|
||||
| Mobile | Uni App | 3.0.0 |
|
||||
| App UI | Wot Design Uni | 1.9.1 |
|
||||
| Database | MySQL | 8.0 (recommended to use the latest version) |
|
||||
| Middleware | Redis | 7.0 (recommended to use the latest version) |
|
||||
|
||||
### Environment Preparation
|
||||
|
||||
#### 1. Install Python
|
||||
|
||||
```sh
|
||||
# macOS
|
||||
brew install python@3.10
|
||||
|
||||
# Ubuntu/Debian
|
||||
sudo apt update
|
||||
sudo apt install python3.10 python3.10-venv python3.10-dev
|
||||
|
||||
# CentOS/RHEL
|
||||
sudo dnf install python3.10 python3.10-venv python3.10-devel
|
||||
```
|
||||
|
||||
#### 2. Install Node.js
|
||||
|
||||
```sh
|
||||
# Using nvm installation (recommended)
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
|
||||
nvm install 20
|
||||
nvm use 20
|
||||
|
||||
# Or using package manager
|
||||
# macOS
|
||||
brew install node@20
|
||||
|
||||
# Ubuntu/Debian
|
||||
sudo apt update
|
||||
sudo apt install nodejs npm
|
||||
|
||||
# CentOS/RHEL
|
||||
sudo dnf install nodejs npm
|
||||
```
|
||||
|
||||
#### 3. Install Database and Cache
|
||||
|
||||
```sh
|
||||
# Install MySQL
|
||||
# macOS
|
||||
brew install mysql
|
||||
brew services start mysql
|
||||
|
||||
# Ubuntu/Debian
|
||||
sudo apt update
|
||||
sudo apt install mysql-server
|
||||
sudo systemctl start mysql
|
||||
|
||||
# Install Redis
|
||||
# macOS
|
||||
brew install redis
|
||||
brew services start redis
|
||||
|
||||
# Ubuntu/Debian
|
||||
sudo apt install redis-server
|
||||
sudo systemctl start redis
|
||||
```
|
||||
|
||||
### Get Code
|
||||
|
||||
```sh
|
||||
# Clone code to local
|
||||
# FastapiAdmin main project
|
||||
git clone https://github.com/fastapiadmin/FastapiAdmin.git
|
||||
# FastApp mobile
|
||||
git clone https://github.com/fastapiadmin/FastApp.git
|
||||
# FastDocs official documentation
|
||||
git clone https://github.com/fastapiadmin/FastDocs.git
|
||||
```
|
||||
|
||||
### Local Backend Startup (FastapiAdmin Main Project)
|
||||
|
||||
#### 1. Configure Environment Variables
|
||||
|
||||
```sh
|
||||
# Enter backend project directory
|
||||
cd FastapiAdmin/backend
|
||||
|
||||
# Copy environment configuration file
|
||||
cp env/.env.dev.example env/.env.dev
|
||||
|
||||
# Edit environment configuration file (modify according to actual situation)
|
||||
# Main configuration items: database connection, Redis connection, JWT secret key, etc.
|
||||
```
|
||||
|
||||
#### 2. Install Dependencies
|
||||
|
||||
```sh
|
||||
# Create virtual environment (optional but recommended)
|
||||
python3 -m venv .venv
|
||||
|
||||
# Activate virtual environment
|
||||
# macOS/Linux
|
||||
source .venv/bin/activate
|
||||
# Windows
|
||||
.venv\Scripts\activate
|
||||
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
#### 3. Database Initialization
|
||||
|
||||
```sh
|
||||
# Generate migration files
|
||||
python main.py revision "Initial migration" --env=dev
|
||||
|
||||
# Apply migration
|
||||
python main.py upgrade --env=dev
|
||||
|
||||
# Initialize system data
|
||||
python main.py init
|
||||
```
|
||||
|
||||
#### 4. Start Backend Service
|
||||
|
||||
```sh
|
||||
# Development environment startup
|
||||
python main.py run --env=dev
|
||||
|
||||
# Or use default environment (dev)
|
||||
python main.py run
|
||||
|
||||
# Production environment startup
|
||||
python main.py run --env=prod
|
||||
```
|
||||
|
||||
### Local Frontend Startup (FastapiAdmin Main Project)
|
||||
|
||||
#### 1. Configure Environment Variables
|
||||
|
||||
```sh
|
||||
# Enter frontend project directory
|
||||
cd FastapiAdmin/frontend
|
||||
|
||||
# Copy environment configuration file
|
||||
cp .env.development.example .env.development
|
||||
|
||||
# Edit environment configuration file (modify according to actual situation)
|
||||
# Main configuration items: API base URL, etc.
|
||||
```
|
||||
|
||||
#### 2. Install Dependencies
|
||||
|
||||
```sh
|
||||
# Install pnpm (if not installed)
|
||||
npm install -g pnpm
|
||||
|
||||
# Install frontend dependencies
|
||||
pnpm install
|
||||
```
|
||||
|
||||
#### 3. Start Frontend Service
|
||||
|
||||
```sh
|
||||
# Development environment startup
|
||||
pnpm run dev
|
||||
|
||||
# Build frontend, generate `dist` directory
|
||||
pnpm run build
|
||||
```
|
||||
|
||||
### Local Mini Program H5 Startup (FastApp Mobile)
|
||||
|
||||
#### 1. Configure Environment Variables
|
||||
|
||||
```sh
|
||||
# Enter mobile project directory
|
||||
cd FastApp
|
||||
|
||||
# Copy environment configuration file
|
||||
cp .env.development .env.development
|
||||
|
||||
# Edit environment configuration file (modify according to actual situation)
|
||||
# Main configuration items: API base URL, etc.
|
||||
```
|
||||
|
||||
#### 2. Install Dependencies
|
||||
|
||||
```sh
|
||||
# Install frontend dependencies
|
||||
pnpm install
|
||||
```
|
||||
|
||||
#### 3. Start H5 Service
|
||||
|
||||
```sh
|
||||
# Start H5 development service
|
||||
pnpm run dev:h5
|
||||
|
||||
# Build H5 version, generate `dist/build/h5` directory
|
||||
pnpm run build:h5
|
||||
|
||||
# Start other platforms (such as WeChat Mini Program)
|
||||
pnpm run dev:mp-weixin
|
||||
```
|
||||
|
||||
### Local Project Official Website Startup (FastDocs Official Documentation)
|
||||
|
||||
```sh
|
||||
# Enter FastDocs official documentation directory
|
||||
cd FastDocs
|
||||
|
||||
# Install dependencies
|
||||
pnpm install
|
||||
|
||||
# Run documentation project
|
||||
pnpm run docs:dev
|
||||
|
||||
# Build documentation project, generate `dist` directory
|
||||
pnpm run docs:build
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Local Access Addresses
|
||||
|
||||
- FastDocs Documentation Address: <http://127.0.0.1:5180>
|
||||
- FastapiAdmin Frontend Address: <http://127.0.0.1:5173>
|
||||
- FastAPI Interface Documentation: <http://127.0.0.1:8001/api/v1/docs>
|
||||
- FastApp H5 Address: <http://127.0.0.1:5174>
|
||||
|
||||
### Default Account Password
|
||||
|
||||
- Admin Account: `admin` Password: `123456`
|
||||
- Demo Account: `demo` Password: `123456`
|
||||
|
||||
## 🐳 Docker Deployment
|
||||
|
||||
### 1. Preparation
|
||||
|
||||
- Server needs to install Docker and Docker Compose
|
||||
- Ensure server ports 80 (Nginx) and 8001 (backend) are available
|
||||
|
||||
### 2. Deployment Steps
|
||||
|
||||
```sh
|
||||
# Enter FastapiAdmin main project directory
|
||||
cd FastapiAdmin
|
||||
|
||||
# Copy environment configuration files
|
||||
cp backend/env/.env.prod.example backend/env/.env.prod
|
||||
cp frontend/.env.production.example frontend/.env.production
|
||||
|
||||
# Edit environment configuration files (modify according to actual server situation)
|
||||
# Main configuration items: database connection, Redis connection, JWT secret key, API base URL, etc.
|
||||
|
||||
# Give script execution permission
|
||||
chmod +x start.sh
|
||||
|
||||
# Execute deployment script
|
||||
./start.sh
|
||||
|
||||
# Check deployment status
|
||||
docker compose ps
|
||||
|
||||
# View logs
|
||||
docker logs -f fastapiadmin-backend
|
||||
```
|
||||
|
||||
### 3. Deployment File Description
|
||||
|
||||
| Configuration File | Description | Path |
|
||||
|-------------------|-------------|------|
|
||||
| Backend environment configuration | Production environment database, Redis and other configurations | `FastapiAdmin/backend/env/.env.prod` |
|
||||
| Frontend environment configuration | Production environment API address and other configurations | `FastapiAdmin/frontend/.env.production` |
|
||||
| Docker configuration | Container orchestration configuration | `FastapiAdmin/docker-compose.yaml` |
|
||||
| Nginx configuration | Reverse proxy configuration | `FastapiAdmin/devops/nginx/nginx.conf` |
|
||||
|
||||
### 4. Common Docker Commands
|
||||
|
||||
```sh
|
||||
# View images
|
||||
docker images
|
||||
|
||||
# View containers
|
||||
docker compose ps
|
||||
|
||||
# Stop service
|
||||
docker compose down
|
||||
|
||||
# Restart service
|
||||
docker compose up -d
|
||||
|
||||
# View container logs
|
||||
docker logs -f <container name>
|
||||
|
||||
# Enter container
|
||||
docker exec -it <container name> bash
|
||||
```
|
||||
|
||||
## 🔧Module Display
|
||||
|
||||
### Web End
|
||||
|
||||
| Module Name <div style="width:60px"/> | Screenshot |
|
||||
|-------------|------------|
|
||||
| Dashboard |  |
|
||||
| Code Generation |  |
|
||||
| Intelligent Assistant |  |
|
||||
|
||||
### Mobile End
|
||||
|
||||
| Login <div style="width:60px"/> | Home <div style="width:60px"/> | Profile <div style="width:60px"/> |
|
||||
|----------|----------|----------|
|
||||
|  |  |  |
|
||||
|
||||
## 🚀Secondary Development Tutorial
|
||||
|
||||
### Backend Part (FastapiAdmin Main Project)
|
||||
|
||||
1. **Write entity class layer**: Create example ORM model in `FastapiAdmin/backend/app/api/v1/models/demo/example_model.py` (corresponding to entity class layer in Spring Boot)
|
||||
2. **Write data model layer**: Create example data model in `FastapiAdmin/backend/app/api/v1/schemas/demo/example_schema.py` (corresponding to DTO layer in Spring Boot)
|
||||
3. **Write query parameter model layer**: Create example query parameter model in `FastapiAdmin/backend/app/api/v1/params/demo/example_param.py` (corresponding to DTO layer in Spring Boot)
|
||||
4. **Write persistence layer**: Create example data layer in `FastapiAdmin/backend/app/api/v1/cruds/demo/example_crud.py` (corresponding to Mapper or DAO layer in Spring Boot)
|
||||
5. **Write business layer**: Create example data layer in `FastapiAdmin/backend/app/api/v1/services/demo/example_service.py` (corresponding to Service layer in Spring Boot)
|
||||
6. **Write interface layer**: Create example data layer in `FastapiAdmin/backend/app/api/v1/controllers/demo/example_controller.py` (corresponding to Controller layer in Spring Boot)
|
||||
7. **Register backend route**: Register example route in `FastapiAdmin/backend/app/api/v1/urls/demo/example_url.py`
|
||||
8. **Register route to FastAPI service**: Register route in `FastapiAdmin/backend/plugin/init_app.py`
|
||||
9. **Add demo module to system initialization script**: Add in `FastapiAdmin/backend/app/scripts/initialize.py` (if needed, you can configure demo's menu permissions in `FastapiAdmin/backend/app/scripts/data/system_menu.json` and `FastapiAdmin/backend/app/scripts/data/system_role_menus.json` or add from frontend page menu)
|
||||
10. **Add demo module to database migration script**: Add in `FastapiAdmin/backend/app/alembic/env.py`
|
||||
|
||||
### Frontend Part (FastapiAdmin Main Project)
|
||||
|
||||
1. **Frontend access backend interface address**: Configure in `FastapiAdmin/frontend/src/api/demo/example.ts`
|
||||
2. **Write frontend page**: Write in `FastapiAdmin/frontend/src/views/demo/example/index.vue`
|
||||
|
||||
### Mobile Part (FastApp Mobile)
|
||||
|
||||
1. **Mobile access backend interface address**: Write in `FastApp/src/api`
|
||||
2. **Write mobile page**: Write in `FastApp/src/pages`
|
||||
|
||||
## 💡Common Problems and Solutions
|
||||
|
||||
### 1. Backend Startup Failure
|
||||
|
||||
**Problem**: Database connection failure
|
||||
**Solution**: Check if the database connection information in the environment configuration file is correct, ensure the database service is running, and the username and password are correct.
|
||||
|
||||
**Problem**: Redis connection failure
|
||||
**Solution**: Check if the Redis connection information in the environment configuration file is correct, ensure the Redis service is running.
|
||||
|
||||
**Problem**: Dependency installation failure
|
||||
**Solution**: Ensure the Python version is correct (>=3.10), you can try to reinstall dependencies using a virtual environment.
|
||||
|
||||
### 2. Frontend Startup Failure
|
||||
|
||||
**Problem**: Dependency installation failure
|
||||
**Solution**: Ensure the Node.js version is correct (>=20.0), you can try to clear the cache and reinstall: `pnpm cache clean && pnpm install`.
|
||||
|
||||
**Problem**: API request failure
|
||||
**Solution**: Check if the API base URL in the frontend environment configuration file is correct, ensure the backend service is running.
|
||||
|
||||
### 3. Deployment Problems
|
||||
|
||||
**Problem**: Docker deployment failure
|
||||
**Solution**: Ensure the server has installed Docker and Docker Compose, check if ports are occupied, view container logs to understand specific error information.
|
||||
|
||||
**Problem**: Nginx configuration error
|
||||
**Solution**: Check if the reverse proxy settings in the Nginx configuration file are correct, ensure the backend service address is configured correctly.
|
||||
|
||||
### 4. Other Problems
|
||||
|
||||
**Problem**: System initialization failure
|
||||
**Solution**: Ensure the database has been correctly initialized, and migrations have been applied, you can try to re-execute the initialization command: `python main.py init`.
|
||||
|
||||
**Problem**: Insufficient permissions
|
||||
**Solution**: Check user role permission settings, ensure the current user has sufficient permissions to access the required functions.
|
||||
@@ -0,0 +1,201 @@
|
||||
---
|
||||
outline: "deep"
|
||||
title: Why Choose FastapiAdmin?
|
||||
---
|
||||
# Why Choose FastapiAdmin?
|
||||
|
||||
## 🎯Core Advantages
|
||||
|
||||
### 1. Advanced Technology Stack
|
||||
|
||||
- **Backend**: Based on FastAPI asynchronous framework, performance is significantly better than traditional synchronous frameworks
|
||||
- **Frontend**: Based on Vue3 + TypeScript + ElementPlus, providing a type-safe and efficient development experience
|
||||
- **Mobile**: Based on Uni App, achieving "write once, run everywhere" cross-platform development
|
||||
- **Database**: Supports MySQL and MongoDB, meeting different business scenario needs
|
||||
- **Cache**: Integrated Redis, improving system response speed and reducing database pressure
|
||||
|
||||
### 2. Complete Functional Modules
|
||||
|
||||
- **System Management**: User, role, menu, department, position management
|
||||
- **Monitoring Management**: Server monitoring, cache monitoring, online users, log management
|
||||
- **Public Management**: Configuration management, dictionary management, task management, file management
|
||||
- **Development Tools**: Code generation, form building, interface management, workflow management
|
||||
- **Mobile Application**: Unified login, personal center, workbench, message push
|
||||
|
||||
### 3. Highly Modular Design
|
||||
|
||||
- **Decoupled Architecture**: Frontend and backend separation, clear layer division
|
||||
- **Plug-in Support**: Modular design, easy to extend and customize
|
||||
- **Standardized Development**: Unified coding standards and development specifications
|
||||
- **Easy Maintenance**: Clear code structure, comprehensive documentation
|
||||
|
||||
### 4. Excellent Performance
|
||||
|
||||
- **Asynchronous Processing**: FastAPI asynchronous framework handles concurrent requests efficiently
|
||||
- **Cache Optimization**: Multi-level cache strategy reduces database access
|
||||
- **Database Optimization**: Reasonable index design and query optimization
|
||||
- **Load Balancing**: Support for horizontal scaling to handle high concurrency
|
||||
|
||||
### 5. Security and Reliability
|
||||
|
||||
- **Authentication**: JWT OAuth2 authentication mechanism, secure and reliable
|
||||
- **Permission Control**: RBAC model implements fine-grained permission management
|
||||
- **Data Encryption**: Sensitive data encryption storage
|
||||
- **Audit Logs**: Complete operation logs for traceability
|
||||
- **Error Handling**: Comprehensive exception handling and error reporting mechanism
|
||||
|
||||
### 6. Easy Deployment and Maintenance
|
||||
|
||||
- **Docker Support**: One-click deployment with Docker Compose
|
||||
- **Nginx Integration**: Built-in reverse proxy configuration
|
||||
- **Multi-environment Support**: Development, testing, production environment isolation
|
||||
- **Monitoring Alert**: Server and application monitoring, timely alerting
|
||||
- **Automated Operation and Maintenance**: Support for CI/CD pipeline integration
|
||||
|
||||
### 7. Rich Development Tools
|
||||
|
||||
- **Code Generator**: Automatically generates CRUD code, improving development efficiency
|
||||
- **Form Builder**: Visual form design, no need for manual coding
|
||||
- **API Documentation**: Automatically generated by FastAPI, real-time update
|
||||
- **Workflow Designer**: Visual workflow design and execution
|
||||
- **Intelligent Assistant**: AI-assisted development and system operation
|
||||
|
||||
### 8. Multi-platform Support
|
||||
|
||||
- **Web End**: Responsive design, supports PC and tablet devices
|
||||
- **Mobile End**: Based on Uni App, supports WeChat Mini Program, H5, iOS, Android
|
||||
- **Unified Experience**: Consistent user experience across different platforms
|
||||
- **Data Synchronization**: Real-time data synchronization between Web and mobile ends
|
||||
|
||||
## 📊Comparison with Other Frameworks
|
||||
|
||||
### FastapiAdmin vs Traditional Backend Frameworks
|
||||
|
||||
| Feature | FastapiAdmin | Django Admin | Flask Admin | Spring Boot Admin |
|
||||
|---------|--------------|-------------|-------------|-------------------|
|
||||
| **Technology Stack** | FastAPI + Vue3 + TypeScript | Django + Template | Flask + Template | Spring Boot + Thymeleaf |
|
||||
| **Performance** | High (asynchronous) | Medium (synchronous) | Medium (synchronous) | Medium (synchronous) |
|
||||
| **Frontend Experience** | Modern, interactive | Simple, static | Simple, static | Traditional, heavy |
|
||||
| **Mobile Support** | Built-in FastApp | None | None | None |
|
||||
| **Modularity** | High | Medium | Low | Medium |
|
||||
| **Customization** | High | Medium | High | Medium |
|
||||
| **Learning Curve** | Medium | Low | Medium | High |
|
||||
| **Community Support** | Growing | Large | Medium | Large |
|
||||
| **Deployment** | Docker-friendly | Traditional | Traditional | Complex |
|
||||
|
||||
### FastapiAdmin vs Other Rapid Development Platforms
|
||||
|
||||
| Feature | FastapiAdmin | Ant Design Pro | Ruoyi Fast | Jeecg Boot |
|
||||
|---------|--------------|----------------|------------|------------|
|
||||
| **Backend Language** | Python | JavaScript (Node.js) | Java | Java |
|
||||
| **Frontend Framework** | Vue3 + TypeScript | React + TypeScript | Vue3 | Vue3 |
|
||||
| **Mobile Support** | Built-in FastApp | None | None | None |
|
||||
| **Database Support** | MySQL, MongoDB | MySQL | MySQL | MySQL |
|
||||
| **Asynchronous Support** | Yes | Yes | No | No |
|
||||
| **Code Quality** | High | High | Medium | Medium |
|
||||
| **Documentation** | Comprehensive | Comprehensive | Medium | Medium |
|
||||
| **Ecosystem** | Growing | Mature | Small | Medium |
|
||||
| **License** | MIT | MIT | Apache 2.0 | Apache 2.0 |
|
||||
|
||||
## 🎯Suitable Scenarios
|
||||
|
||||
### 1. Enterprise Internal Management Systems
|
||||
|
||||
- **Human Resource Management**: Employee information, attendance, performance management
|
||||
- **Financial Management**: Budget, expense, invoice management
|
||||
- **OA System**: Approval workflow, document management, meeting management
|
||||
- **Asset Management**: Fixed assets, inventory management
|
||||
|
||||
### 2. Business Operation Platforms
|
||||
|
||||
- **E-commerce Backend**: Order management, product management, customer management
|
||||
- **Content Management System**: Article publishing, media management, column management
|
||||
- **Customer Relationship Management**: Customer information, sales pipeline, service records
|
||||
- **Marketing Management**: Activity management, coupon management, data analysis
|
||||
|
||||
### 3. Data Analysis Platforms
|
||||
|
||||
- **Business Intelligence**: Data dashboard, report generation, trend analysis
|
||||
- **Operation Analysis**: User behavior analysis, traffic analysis, conversion rate analysis
|
||||
- **Financial Analysis**: Revenue analysis, cost analysis, profit analysis
|
||||
- **Performance Analysis**: Department performance, employee performance, project performance
|
||||
|
||||
### 4. API Management Platforms
|
||||
|
||||
- **Interface Management**: API documentation, testing, monitoring
|
||||
- **Developer Platform**: Third-party integration, SDK management, access control
|
||||
- **Service Governance**: Service registration, discovery, load balancing
|
||||
- **API Gateway**: Request routing, authentication, rate limiting
|
||||
|
||||
### 5. Multi-platform Applications
|
||||
|
||||
- **Enterprise Applications**: Need both Web and mobile access
|
||||
- **Field Services**: On-site staff use mobile terminals, backend management through Web
|
||||
- **Customer Services**: Customers use mobile terminals, staff manage through Web
|
||||
- **Internal Tools**: Employees use both PC and mobile terminals
|
||||
|
||||
## 🔧Technical Advantages in Detail
|
||||
|
||||
### 1. Backend Advantages
|
||||
|
||||
- **FastAPI Framework**: Asynchronous processing, automatic API documentation generation, type hints
|
||||
- **SQLAlchemy 2.0**: Modern ORM, support for asynchronous operations
|
||||
- **Redis Cache**: High performance, support for various data structures
|
||||
- **MySQL 8.0**: Stable, reliable, support for complex queries
|
||||
- **JWT Authentication**: Stateless, secure, easy to scale
|
||||
|
||||
### 2. Frontend Advantages
|
||||
|
||||
- **Vue3 Composition API**: Better code organization, easier reuse
|
||||
- **TypeScript**: Type safety, better development experience
|
||||
- **ElementPlus**: Rich components, beautiful interface
|
||||
- **Pinia**: Lightweight state management, better TypeScript support
|
||||
- **Axios**: Powerful HTTP client, support for interceptors
|
||||
|
||||
### 3. Mobile Advantages
|
||||
|
||||
- **Uni App**: Cross-platform development, support for multiple terminals
|
||||
- **Wot Design Uni**: Mobile-optimized UI components
|
||||
- **Vue3 Syntax**: Consistent with Web frontend, reduced learning cost
|
||||
- **Native Performance**: Near-native performance through rendering optimization
|
||||
- **Easy Packaging**: One-click packaging for multiple platforms
|
||||
|
||||
### 4. DevOps Advantages
|
||||
|
||||
- **Docker Containerization**: Consistent environment, easy deployment
|
||||
- **Docker Compose**: Multi-container orchestration, simplified management
|
||||
- **Nginx Reverse Proxy**: High performance, support for HTTPS
|
||||
- **CI/CD Integration**: Automated testing and deployment
|
||||
- **Monitoring System**: Real-time monitoring, timely alerting
|
||||
|
||||
## 📚Complete Documentation
|
||||
|
||||
- **Getting Started Guide**: Detailed installation and configuration steps
|
||||
- **Development Documentation**: Backend, frontend, mobile development guides
|
||||
- **Deployment Documentation**: Docker deployment, manual deployment, cloud deployment
|
||||
- **API Documentation**: Automatically generated by FastAPI, interactive testing
|
||||
- **Best Practices**: Development specifications, performance optimization, security guidelines
|
||||
|
||||
## 🤝Active Community
|
||||
|
||||
- **Open Source**: Completely open source, MIT license
|
||||
- **Community Support**: GitHub, Gitee, QQ group, WeChat group
|
||||
- **Continuous Updates**: Regular version updates and bug fixes
|
||||
- **Feedback Channels**: Multiple channels for suggestions and issues
|
||||
- **Contribution Guide**: Clear contribution process and guidelines
|
||||
|
||||
## 🚀Future Plans
|
||||
|
||||
- **AI Integration**: Deep integration of AI capabilities into the development process
|
||||
- **Microservices Support**: Evolution towards microservices architecture
|
||||
- **Low-code Platform**: Further simplification of development process
|
||||
- **More Templates**: Rich industry-specific templates
|
||||
- **Internationalization**: Better support for multi-language and multi-region
|
||||
|
||||
## 🎉Conclusion
|
||||
|
||||
**FastapiAdmin** is a **modern, efficient, and comprehensive rapid development platform** that combines the advantages of FastAPI, Vue3, and Uni App. It provides a complete solution for enterprise-level application development, from backend API to frontend interface, and from Web end to mobile end.
|
||||
|
||||
Whether you are building a small internal tool or a large enterprise system, FastapiAdmin can help you **reduce development costs, improve development efficiency, and ensure system quality**.
|
||||
|
||||
Choose FastapiAdmin, choose a better development experience!
|
||||
Reference in New Issue
Block a user