Files
2026-08-05 23:59:15 +08:00

378 lines
8.6 KiB
Markdown

# API View Documentation
## 📋 **Table of Contents**
1. [GetIPDataView](#getipdataview)
2. [BaiduFanyiView](#baidufanyiview)
3. [User Views](#user-views)
---
## <a name="getipdataview"></a> 🌐 GetIPDataView
### **File Location**
`api/views/GetIPDataView.py`
### **Overview**
Retrieves client IP address information from various HTTP headers and server variables.
### **Class Details**
```python
@permission_classes([AllowAny])
class GetIPDataView(APIView):
def get(self, request):
# Implementation...
```
### **Method: GET**
#### **Parameters**
- No parameters required
#### **Response Format**
```json
{
"ip_info": {
"remote_addr": "string",
"http_x_forwarded_for": "string",
"http_x_real_ip": "string",
"http_client_ip": "string",
"http_x_forwarded": "string",
"http_x_cluster_client_ip": "string",
"http_forwarded_for": "string",
"http_forwarded": "string"
}
}
```
#### **HTTP Headers Checked**
The view extracts IP information from the following HTTP headers:
| Header | Description |
|--------|-------------|
| `REMOTE_ADDR` | Direct connection IP (most reliable) |
| `HTTP_X_FORWARDED_FOR` | Proxy/load balancer forwarded IP |
| `HTTP_X_REAL_IP` | Real client IP from proxy |
| `HTTP_CLIENT_IP` | Client IP header |
| `HTTP_X_FORWARDED` | Forwarded header |
| `HTTP_X_CLUSTER_CLIENT_IP` | Cluster client IP |
| `HTTP_FORWARDED_FOR` | Standard forwarded for header |
| `HTTP_FORWARDED` | Standard forwarded header |
### **Usage Example**
```bash
curl -X GET http://your-api.com/api/get-ip-data/
```
**Response:**
```json
{
"ip_info": {
"remote_addr": "192.168.1.100",
"http_x_forwarded_for": "203.0.113.50, 198.51.100.25",
"http_x_real_ip": "203.0.113.50",
"http_client_ip": "",
"http_x_forwarded": "",
"http_x_cluster_client_ip": "",
"http_forwarded_for": "",
"http_forwarded": ""
}
}
```
### **Error Handling**
- Returns HTTP 200 with empty strings for missing headers
- No authentication required (`@permission_classes([AllowAny])`)
---
## <a name="baidufanyiview"></a> 🌍 BaiduFanyiView
### **File Location**
`api/views/BaiduFanyiView.py`
### **Overview**
Provides translation and language recognition services using Baidu Translate API. All views are now fully asynchronous for better performance with Daphne ASGI server.
### **Class Details**
```python
# Async methods for all views
async def post(self, request): # For text and language recognition
async def post(self, request): # For picture translation
async def post(self, request): # For speech recognition
```
### **1. BaiduFanyiView (Text Translation)**
#### **Endpoint**: `POST /api/translate/`
##### **Parameters**
```json
{
"q": "text to translate", // Required: Text content (max 3000 chars)
"from_lang": "en", // Required: Source language code
"to_lang": "zh" // Required: Target language code
}
```
##### **Supported Languages**
Check `languages` and `auto_lang` from `info.baidu_lang_info`
##### **Response Example**
```json
{
"message": "Success",
"code": "10000",
"data": {
"trans_result": [
{
"src": "Hello world",
"dst": "你好世界"
}
],
"from": "en",
"to": "zh"
}
}
```
### **2. RecognizeLangTypeViews (Language Recognition)**
#### **Endpoint**: `POST /api/recognize-language/`
##### **Parameters**
```json
{
"q": "text to recognize" // Required: Text to identify language
}
```
##### **Response Example**
```json
{
"message": "Success",
"code": "10000",
"data": {
"lang": "en"
}
}
```
### **3. PictureRecognizeViews (Picture Translation)**
#### **Endpoint**: `POST /api/picture-translate/`
##### **Parameters**
- File upload via multipart/form-data
- Query parameters:
- `from_lang`: Source language
- `to_lang`: Target language
- `picture`: Image format type
##### **Request Format**
```bash
curl -X POST http://your-api.com/api/picture-translate/
-H "Content-Type: multipart/form-data"
-F "file=@image.jpg"
-G --data-urlencode "from_lang=en"
--data-urlencode "to_lang=zh"
--data-urlencode "picture=jpg"
```
### **4. SpeechRecognitionView (Speech Recognition)**
#### **Endpoint**: `POST /api/speech-recognition/`
##### **Parameters**
- Voice file upload via multipart/form-data
- Query parameters:
- `speech_type`: Audio format (e.g., "pcm")
- `from_lang`: Source language
- `to_lang`: Target language
##### **Error Codes**
| Code | Description |
|------|-------------|
| 10000 | Success |
| 20001 | Language not supported |
| 20002 | Invalid audio format |
| 20003 | Service temporarily unavailable |
### **Async Implementation Benefits**
- ✅ Non-blocking I/O operations
- ✅ Better concurrency handling
- ✅ Improved response times
- ✅ Full Daphne ASGI compatibility
---
## <a name="user-views"></a> 👤 User Views
### **File Location**
`user/views/user.py`
### **Overview**
Handles user authentication and email verification. Now fully converted to async operations with standardized response codes.
### **Class Details**
```python
@permission_classes([AllowAny])
class SendUserEmailAPIView(APIView):
async def post(self, request): # Email sending
@permission_classes([AllowAny])
class UserLoginOrRegisterAPIView(APIView):
async def post(self, request): # Login/Registration
```
### **1. SendUserEmailAPIView**
#### **Endpoint**: `POST /api/send-email/`
##### **Parameters**
```json
{
"to_email": "user@example.com" // Required: Recipient email address
}
```
##### **Response Examples**
**Registration Email:**
```json
{
"message": "账号未注册,已发送注册邮件",
"code": "10001",
"data": {
"email_sent": true,
"type": "register"
}
}
```
**Login Email:**
```json
{
"message": "邮件发送成功",
"code": "10002",
"data": {
"email_sent": true,
"type": "login"
}
}
```
### **2. UserLoginOrRegisterAPIView**
#### **Endpoint**: `POST /api/login-register/`
##### **Parameters**
```json
{
"email": "user@example.com", // Required: User email
"code": "12345678" // Required: Verification code
}
```
##### **Response Examples**
**Successful Registration:**
```json
{
"message": "注册成功",
"code": "10003",
"data": {
"user": { /* user data */ },
"refresh": "jwt_refresh_token",
"access": "jwt_access_token",
"token_type": "bearer",
"expires_in": 604800
}
}
```
**Successful Login:**
```json
{
"message": "登录成功",
"code": "10004",
"data": {
"user": { /* user data */ },
"refresh": "jwt_refresh_token",
"access": "jwt_access_token",
"token_type": "bearer",
"expires_in": 604800
}
}
```
##### **Error Responses**
```json
{
"message": "邮箱地址不能为空",
"code": "20002",
"data": {}
}
```
### **Standardized Response Format**
All responses follow the unified structure:
```json
{
"message": "Human readable message",
"code": "10000", // 5-digit zero-padded string
"data": { // Optional, null for errors
// Response payload
}
}
```
### **Async Implementation Features**
- ✅ Database operations wrapped with `sync_to_async`
- ✅ Email sending as async operation
- ✅ Full error handling with try-catch blocks
- ✅ Type-safe enum usage for codes/messages
---
## 📊 **Summary Statistics**
| View Class | Method | Async? | Error Codes | Status Codes |
|------------|--------|--------|-------------|--------------|
| GetIPDataView | GET | ❌ Sync | N/A | 200 |
| BaiduFanyiView | POST | ✅ Async | Multiple | 200, 400, 503 |
| RecognizeLangTypeViews | POST | ✅ Async | Multiple | 200, 400, 503 |
| PictureRecognizeViews | POST | ✅ Async | Multiple | 200, 400, 503 |
| SpeechRecognitionView | POST | ✅ Async | Multiple | 200, 503 |
| SendUserEmailAPIView | POST | ✅ Async | 3+ | 200, 201, 400, 500 |
| UserLoginOrRegisterAPIView | POST | ✅ Async | 6+ | 200, 400, 500 |
---
## 🚀 **Quick Start Guide**
### **Testing Endpoints:**
```bash
# Get IP Data
curl -X GET http://localhost:8000/api/get-ip-data/
# Send Email
curl -X POST http://localhost:8000/api/send-email/
-H "Content-Type: application/json"
-d '{"to_email":"test@example.com"}'
# Text Translation
curl -X POST http://localhost:8000/api/translate/
-H "Content-Type: application/json"
-d '{"q":"Hello","from_lang":"en","to_lang":"zh"}'
```
### **Running with Daphne:**
```bash
pip install aiohttp
daphne chunyu_project.asgi:application --port 8000
```