-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfastapi_mongodb.py
More file actions
1238 lines (1135 loc) · 40.2 KB
/
Copy pathfastapi_mongodb.py
File metadata and controls
1238 lines (1135 loc) · 40.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fastapi import FastAPI, HTTPException, Depends, Query, Path, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field, model_serializer
from typing import Dict, List, Any, Optional
from mongodb_api import MongoDBQueryAPI
from redis_cache import redis_cache
import uvicorn
from contextlib import asynccontextmanager
from datetime import datetime
from swagger_config import get_swagger_config
import time
import json
from fastapi.responses import Response
# 获取Swagger配置
swagger_config = get_swagger_config()
# 全局MongoDB API实例
mongodb_api = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理"""
global mongodb_api
mongodb_api = MongoDBQueryAPI()
yield
if mongodb_api:
mongodb_api.close_connection()
# 创建FastAPI应用,使用优化的Swagger配置
app = FastAPI(
title="MongoDB查询API",
description="""
## MongoDB查询接口
这是一个完整的MongoDB查询接口,支持各种查询操作。
### 主要功能
- 🔌 **连接管理** - 灵活的MongoDB连接配置
- 🔍 **文档查询** - 支持简单和复杂条件查询
- 📊 **聚合查询** - 强大的数据聚合功能
- 📈 **统计信息** - 获取集合详细统计
- 🛡️ **错误处理** - 完善的异常处理机制
### 使用流程
1. 使用 `/query` 接口,传入连接信息和查询条件
2. 使用 `/aggregate` 接口进行聚合查询
3. 可选调用 `/stats` 获取统计信息
### 环境要求
- Python 3.7+
- MongoDB 4.0+
- pymongo 4.0+
### 示例连接字符串
- 本地连接: `mongodb://localhost:27017/`
- 带认证: `mongodb://username:password@localhost:27017/`
- 集群连接: `mongodb://host1:port1,host2:port2/`
### 快速开始
1. 启动服务后访问 `/docs` 查看Swagger文档
2. 使用"Try it out"功能直接测试API
3. 查看示例代码了解使用方法
""",
version="1.0.0",
contact={
"name": "MongoDB API Support",
"email": "support@example.com",
"url": "https://github.com/your-repo/mongodb-api"
},
license_info={
"name": "MIT License",
"url": "https://opensource.org/licenses/MIT",
},
lifespan=lifespan,
# 使用优化的Swagger UI配置
swagger_ui_parameters=swagger_config["swagger_ui_parameters"],
# 添加服务器配置
servers=swagger_config["servers"],
# 添加标签配置
openapi_tags=swagger_config["tags"]
)
# ⚡️就在这里添加!
from fastapi.middleware.gzip import GZipMiddleware
app.add_middleware(GZipMiddleware, minimum_size=1000)
# 添加CORS中间件
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 允许所有来源
allow_credentials=True,
allow_methods=["*"], # 允许所有方法
allow_headers=["*"], # 允许所有头
)
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
"""
添加性能统计中间件
- 计算请求处理时间
- 计算响应数据长度
- 添加到响应头和日志
"""
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
# 将处理时间添加到响应头
response.headers["X-Process-Time-Ms"] = str(round(process_time * 1000, 2))
# 获取响应体并计算长度
response_body = b""
async for chunk in response.body_iterator:
response_body += chunk
response_length = len(response_body)
response.headers["X-Response-Length"] = str(response_length)
# 打印日志
print(f"INFO: Request: {request.method} {request.url.path} - "
f"Process Time: {response.headers['X-Process-Time-Ms']}ms - "
f"Response Length: {response_length} bytes")
# 从原始响应重新创建新的响应,因为body_iterator已被消耗
return Response(
content=response_body,
status_code=response.status_code,
headers=dict(response.headers),
media_type=response.media_type
)
# 数据模型
class ConnectionRequest(BaseModel):
connection_string: str = Field(
...,
description="MongoDB连接字符串",
example="mongodb://localhost:27017/",
min_length=1
)
database_name: str = Field(
...,
description="数据库名称",
example="test_db",
min_length=1
)
collection_name: str = Field(
...,
description="集合名称",
example="users",
min_length=1
)
class Config:
json_schema_extra = {
"example": {
"connection_string": "mongodb://localhost:27017/",
"database_name": "test_db",
"collection_name": "users"
}
}
class QueryRequest(BaseModel):
# 数据库连接信息
connection_string: str = Field(
...,
description="MongoDB连接字符串",
example="mongodb://localhost:27017/",
min_length=1
)
database_name: str = Field(
...,
description="数据库名称",
example="test_db",
min_length=1
)
collection_name: str = Field(
...,
description="集合名称",
example="users",
min_length=1
)
# 查询参数
query_filter: Optional[Dict[str, Any]] = Field(
default=None,
description="查询条件,支持MongoDB查询语法",
example={"age": {"$gte": 25}, "status": "active"}
)
projection: Optional[Dict[str, Any]] = Field(
default=None,
description="投影字段,1表示包含,0表示排除",
example={"name": 1, "age": 1, "email": 1, "_id": 0}
)
sort: Optional[List[List[Any]]] = Field(
default=None,
description="排序条件,格式:[['字段名', 1或-1]],1为升序,-1为降序",
example=[["age", -1], ["name", 1]]
)
limit: Optional[int] = Field(
default=None,
description="限制返回文档数量",
example=10,
ge=1,
le=1000
)
skip: Optional[int] = Field(
default=None,
description="跳过文档数量",
example=0,
ge=0,
le=10000
)
cache_ttl: Optional[int] = Field(
default=300,
description="缓存时间(秒)。传0则不使用缓存,传None则使用默认缓存时间。"
)
force_refresh: bool = Field(
default=False,
description="是否强制从数据库重新获取数据,忽略缓存。如果为true,将直接查询数据库并更新缓存。"
)
class Config:
json_schema_extra = {
"example": {
"connection_string": "mongodb://localhost:27017/",
"database_name": "test_db",
"collection_name": "users",
"query_filter": {
"age": {"$gte": 25},
"department": {"$in": ["技术部", "销售部"]},
"status": "active"
},
"projection": {
"name": 1,
"age": 1,
"email": 1,
"department": 1,
"_id": 0
},
"sort": [["age", -1], ["name", 1]],
"limit": 10,
"skip": 0
}
}
class QueryOneRequest(BaseModel):
# 数据库连接信息
connection_string: str = Field(
...,
description="MongoDB连接字符串",
example="mongodb://localhost:27017/",
min_length=1
)
database_name: str = Field(
...,
description="数据库名称",
example="test_db",
min_length=1
)
collection_name: str = Field(
...,
description="集合名称",
example="users",
min_length=1
)
# 查询参数
query_filter: Optional[Dict[str, Any]] = Field(
default=None,
description="查询条件,支持MongoDB查询语法",
example={"age": {"$gte": 25}, "status": "active"}
)
projection: Optional[Dict[str, Any]] = Field(
default=None,
description="投影字段,1表示包含,0表示排除",
example={"name": 1, "age": 1, "email": 1, "_id": 0}
)
sort: Optional[List[List[Any]]] = Field(
default=None,
description="排序条件,格式:[['字段名', 1或-1]],1为升序,-1为降序",
example=[["age", -1], ["name", 1]]
)
cache_ttl: Optional[int] = Field(
default=300,
description="缓存时间(秒)。传0则不使用缓存,传None则使用默认缓存时间。"
)
force_refresh: bool = Field(
default=False,
description="是否强制从数据库重新获取数据,忽略缓存。如果为true,将直接查询数据库并更新缓存。"
)
class Config:
json_schema_extra = {
"example": {
"connection_string": "mongodb://localhost:27017/",
"database_name": "test_db",
"collection_name": "users",
"query_filter": {
"age": {"$gte": 25},
"department": {"$in": ["技术部", "销售部"]},
"status": "active"
},
"projection": {
"name": 1,
"age": 1,
"email": 1,
"department": 1,
"_id": 0
},
"sort": [["age", -1], ["name", 1]]
}
}
class AggregateRequest(BaseModel):
# 数据库连接信息
connection_string: str = Field(
...,
description="MongoDB连接字符串",
example="mongodb://localhost:27017/",
min_length=1
)
database_name: str = Field(
...,
description="数据库名称",
example="test_db",
min_length=1
)
collection_name: str = Field(
...,
description="集合名称",
example="users",
min_length=1
)
# 聚合参数
pipeline: List[Dict[str, Any]] = Field(
...,
description="聚合管道,支持MongoDB聚合操作符",
min_items=1
)
cache_ttl: Optional[int] = Field(
default=300,
description="缓存时间(秒)。传0则不使用缓存,传None则使用默认缓存时间。"
)
force_refresh: bool = Field(
default=False,
description="是否强制从数据库重新获取数据,忽略缓存。如果为true,将直接查询数据库并更新缓存。"
)
class Config:
json_schema_extra = {
"example": {
"connection_string": "mongodb://localhost:27017/",
"database_name": "test_db",
"collection_name": "users",
"pipeline": [
{"$match": {"age": {"$gte": 25}}},
{"$group": {"_id": "$department", "count": {"$sum": 1}, "avg_age": {"$avg": "$age"}}},
{"$sort": {"count": -1}}
]
}
}
class DistinctRequest(BaseModel):
# 数据库连接信息
connection_string: str = Field(
...,
description="MongoDB连接字符串",
example="mongodb://localhost:27017/",
min_length=1
)
database_name: str = Field(
...,
description="数据库名称",
example="test_db",
min_length=1
)
collection_name: str = Field(
...,
description="集合名称",
example="users",
min_length=1
)
# distinct参数
field: str = Field(
...,
description="要查询唯一值的字段名",
example="department",
min_length=1
)
query_filter: Optional[Dict[str, Any]] = Field(
default=None,
description="可选的查询条件,用于过滤文档",
example={"age": {"$gte": 25}, "status": "active"}
)
cache_ttl: Optional[int] = Field(
default=300,
description="缓存时间(秒)。传0则不使用缓存,传None则使用默认缓存时间。"
)
force_refresh: bool = Field(
default=False,
description="是否强制从数据库重新获取数据,忽略缓存。如果为true,将直接查询数据库并更新缓存。"
)
class Config:
json_schema_extra = {
"example": {
"connection_string": "mongodb://localhost:27017/",
"database_name": "test_db",
"collection_name": "users",
"field": "department",
"query_filter": {"age": {"$gte": 25}},
"cache_ttl": 300
}
}
class ApiResponse(BaseModel):
status: str = Field(..., description="响应状态:success/error/info")
message: str = Field(..., description="响应消息")
data: Optional[Any] = Field(default=None, description="响应数据")
count: Optional[int] = Field(default=None, description="数据条数")
cache_ttl: Optional[int] = Field(default=None, description="缓存时间(秒)")
timestamp: str = Field(..., description="响应时间戳")
@model_serializer
def ser_model(self) -> Dict[str, Any]:
"""自定义模型序列化,仅在count不为None时返回该字段"""
response = {
"status": self.status,
"message": self.message,
"data": self.data,
"timestamp": self.timestamp,
}
if self.count is not None:
response['count'] = self.count
if self.cache_ttl is not None:
response['cache_ttl'] = self.cache_ttl
return response
class Config:
json_schema_extra = {
"example": {
"status": "success",
"message": "查询成功,返回 5 个文档",
"data": [
{"name": "张三", "age": 28, "email": "zhangsan@example.com"},
{"name": "李四", "age": 32, "email": "lisi@example.com"}
],
"count": 5,
"timestamp": "2024-01-01T12:00:00"
}
}
# 依赖函数
def get_mongodb_api():
"""获取MongoDB API实例"""
if mongodb_api is None:
raise HTTPException(status_code=500, detail="MongoDB API未初始化")
return mongodb_api
# API路由
@app.post(
"/connect",
response_model=ApiResponse,
summary="连接MongoDB数据库",
description="""
连接到指定的MongoDB数据库和集合。
**参数说明:**
- `connection_string`: MongoDB连接字符串
- `database_name`: 要连接的数据库名称
- `collection_name`: 要操作的集合名称
**返回结果:**
- 成功:返回连接成功信息
- 失败:返回错误详情
**使用示例:**
```json
{
"connection_string": "mongodb://localhost:27017/",
"database_name": "test_db",
"collection_name": "users"
}
```
""",
tags=["连接管理"],
responses={
200: {
"description": "连接成功",
"content": {
"application/json": {
"example": {
"status": "success",
"message": "连接成功",
"data": {
"database": "test_db",
"collection": "users"
},
"timestamp": "2024-01-01T12:00:00"
}
}
}
},
400: {
"description": "连接失败",
"content": {
"application/json": {
"example": {
"status": "error",
"message": "连接失败: 无法连接到MongoDB服务器",
"timestamp": "2024-01-01T12:00:00"
}
}
}
}
}
)
async def connect_to_mongodb(
request: ConnectionRequest,
api: MongoDBQueryAPI = Depends(get_mongodb_api)
):
result = api.connect_to_mongodb(
request.connection_string,
request.database_name,
request.collection_name
)
if result["status"] == "error":
raise HTTPException(status_code=400, detail=result["message"])
return ApiResponse(**result)
@app.post(
"/query",
response_model=ApiResponse,
summary="查询MongoDB文档(自动连接和断开)",
description="""
根据指定条件查询MongoDB文档,自动处理连接和断开。
**功能特点:**
- 自动连接指定的MongoDB数据库
- 执行查询操作
- 自动断开连接,释放资源
- 支持所有MongoDB查询功能
**查询条件示例:**
- 简单条件:`{"age": 25}`
- 范围查询:`{"age": {"$gte": 20, "$lte": 30}}`
- 数组查询:`{"department": {"$in": ["技术部", "销售部"]}}`
- 复杂条件:`{"$and": [{"age": {"$gte": 25}}, {"status": "active"}]}`
**投影字段说明:**
- `{"field": 1}` - 包含该字段
- `{"field": 0}` - 排除该字段
- `{"_id": 0}` - 排除_id字段
**排序说明:**
- `[["field", 1]]` - 按字段升序
- `[["field", -1]]` - 按字段降序
- `[["field1", 1], ["field2", -1]]` - 多字段排序
""",
tags=["数据查询"],
responses={
200: {
"description": "查询成功",
"content": {
"application/json": {
"example": {
"status": "success",
"message": "查询成功,返回 3 个文档",
"data": [
{"name": "张三", "age": 28, "email": "zhangsan@example.com"},
{"name": "李四", "age": 32, "email": "lisi@example.com"},
{"name": "王五", "age": 25, "email": "wangwu@example.com"}
],
"count": 3,
"timestamp": "2024-01-01T12:00:00"
}
}
}
},
400: {
"description": "查询失败",
"content": {
"application/json": {
"example": {
"status": "error",
"message": "查询失败: 无法连接到MongoDB服务器",
"timestamp": "2024-01-01T12:00:00"
}
}
}
}
}
)
async def query_documents(
request: QueryRequest
):
"""
查询MongoDB文档,自动处理连接和断开
"""
cache_key = None
use_cache = request.cache_ttl != 0
# 1. 检查缓存 (如果不强制刷新)
if use_cache and not request.force_refresh:
# 使用请求的所有参数来生成缓存键,确保唯一性
cache_key = redis_cache.generate_cache_key("query", request.dict())
cached_result = redis_cache.get(cache_key)
if cached_result:
# 如果命中缓存,直接返回结果,不创建MongoDB连接
cached_result["message"] = f"查询成功 (来自缓存),返回 {cached_result.get('count', 0)} 个文档"
# 添加缓存时间信息
cached_result["cache_ttl"] = request.cache_ttl
return ApiResponse(**cached_result)
# 2. 只有缓存未命中时才创建MongoDB连接和查询
api = MongoDBQueryAPI()
try:
# 连接数据库
connection_result = api.connect_to_mongodb(
request.connection_string,
request.database_name,
request.collection_name
)
if connection_result["status"] == "error":
return ApiResponse(
status="error",
message=f"连接失败: {connection_result['message']}",
timestamp=datetime.now().isoformat()
)
# 转换排序格式
sort_list = None
if request.sort:
sort_list = [(item[0], item[1]) for item in request.sort]
# 执行查询
result = api.query_documents(
query_filter=request.query_filter,
projection=request.projection,
sort=sort_list,
limit=request.limit,
skip=request.skip
)
# 3. 设置缓存 (如果查询成功且启用了缓存)
if use_cache and result["status"] == "success":
if cache_key is None: # 如果是强制刷新,之前没生成key
cache_key = redis_cache.generate_cache_key("query", request.dict())
redis_cache.set(cache_key, result, ttl=request.cache_ttl)
# 添加缓存时间信息到响应
result["cache_ttl"] = request.cache_ttl
return ApiResponse(**result)
except Exception as e:
return ApiResponse(
status="error",
message=f"查询过程中发生错误: {str(e)}",
timestamp=datetime.now().isoformat()
)
finally:
# 确保连接被关闭
api.close_connection()
@app.post(
"/query_one",
response_model=ApiResponse,
summary="查询MongoDB单个文档(自动连接和断开)",
description="""
根据指定条件查询MongoDB单个文档,自动处理连接和断开。
**功能特点:**
- 自动连接指定的MongoDB数据库
- 执行查询操作,只返回第一个匹配的文档
- 自动断开连接,释放资源
- 支持所有MongoDB查询功能
**使用场景:**
- 根据唯一ID查询单个文档
- 获取满足条件的第一个文档
- 检查文档是否存在
- 获取最新或最旧的文档
**查询条件示例:**
- 简单条件:`{"age": 25}`
- 范围查询:`{"age": {"$gte": 20, "$lte": 30}}`
- 数组查询:`{"department": {"$in": ["技术部", "销售部"]}}`
- 复杂条件:`{"$and": [{"age": {"$gte": 25}}, {"status": "active"}]}`
**投影字段说明:**
- `{"field": 1}` - 包含该字段
- `{"field": 0}` - 排除该字段
- `{"_id": 0}` - 排除_id字段
**排序说明:**
- `[["field", 1]]` - 按字段升序
- `[["field", -1]]` - 按字段降序
- `[["field1", 1], ["field2", -1]]` - 多字段排序
""",
tags=["数据查询"],
responses={
200: {
"description": "查询成功",
"content": {
"application/json": {
"example": {
"status": "success",
"message": "查询单个文档成功",
"data": {
"name": "张三",
"age": 28,
"email": "zhangsan@example.com",
"department": "技术部"
},
"timestamp": "2024-01-01T12:00:00"
}
}
}
},
200: {
"description": "没有找到匹配的文档",
"content": {
"application/json": {
"example": {
"status": "info",
"message": "没有找到匹配的文档",
"data": None,
"timestamp": "2024-01-01T12:00:00"
}
}
}
},
400: {
"description": "查询失败",
"content": {
"application/json": {
"example": {
"status": "error",
"message": "查询失败: 无法连接到MongoDB服务器",
"timestamp": "2024-01-01T12:00:00"
}
}
}
}
}
)
async def query_one_document(
request: QueryOneRequest
):
"""
执行单个文档查询,自动处理连接和断开
"""
cache_key = None
use_cache = request.cache_ttl != 0
# 1. 检查缓存 (如果不强制刷新)
if use_cache and not request.force_refresh:
cache_key = redis_cache.generate_cache_key("query_one", request.dict())
cached_result = redis_cache.get(cache_key)
if cached_result:
# 如果命中缓存,直接返回结果,不创建MongoDB连接
cached_result["message"] = f"查询单个文档成功 (来自缓存)"
# 添加缓存时间信息
cached_result["cache_ttl"] = request.cache_ttl
return ApiResponse(**cached_result)
# 2. 只有缓存未命中时才创建MongoDB连接和查询
api = MongoDBQueryAPI()
try:
# 连接数据库
connection_result = api.connect_to_mongodb(
request.connection_string,
request.database_name,
request.collection_name
)
if connection_result["status"] == "error":
return ApiResponse(
status="error",
message=f"连接失败: {connection_result['message']}",
timestamp=datetime.now().isoformat()
)
# 转换排序格式
sort_list = None
if request.sort:
sort_list = [(item[0], item[1]) for item in request.sort]
# 执行查询
result = api.query_one_document(
query_filter=request.query_filter,
projection=request.projection,
sort=sort_list
)
# 3. 设置缓存 (如果查询成功且启用了缓存)
if use_cache and result["status"] == "success":
if cache_key is None: # 如果是强制刷新,之前没生成key
cache_key = redis_cache.generate_cache_key("query_one", request.dict())
redis_cache.set(cache_key, result, ttl=request.cache_ttl)
# 添加缓存时间信息到响应
result["cache_ttl"] = request.cache_ttl
return ApiResponse(**result)
except Exception as e:
return ApiResponse(
status="error",
message=f"查询过程中发生错误: {str(e)}",
timestamp=datetime.now().isoformat()
)
finally:
# 确保连接被关闭
api.close_connection()
@app.post(
"/aggregate",
response_model=ApiResponse,
summary="执行聚合管道查询(自动连接和断开)",
description="""
执行MongoDB聚合管道查询,自动处理连接和断开。
**功能特点:**
- 自动连接指定的MongoDB数据库
- 执行聚合查询操作
- 自动断开连接,释放资源
- 支持所有MongoDB聚合功能
**常用聚合操作:**
- `$match`: 过滤文档
- `$group`: 分组统计
- `$sort`: 排序
- `$limit`: 限制数量
- `$skip`: 跳过数量
- `$project`: 字段投影
- `$lookup`: 关联查询
**聚合函数:**
- `$sum`: 求和
- `$avg`: 平均值
- `$max`: 最大值
- `$min`: 最小值
- `$count`: 计数
""",
tags=["聚合查询"],
responses={
200: {
"description": "聚合查询成功",
"content": {
"application/json": {
"example": {
"status": "success",
"message": "聚合查询成功,返回 2 个文档",
"data": [
{"_id": "技术部", "count": 5, "avg_age": 30.2, "avg_salary": 18000},
{"_id": "销售部", "count": 3, "avg_age": 28.5, "avg_salary": 15000}
],
"count": 2,
"timestamp": "2024-01-01T12:00:00"
}
}
}
}
}
)
async def aggregate_documents(
request: AggregateRequest
):
"""
执行聚合查询,自动处理连接和断开
"""
cache_key = None
use_cache = request.cache_ttl != 0
# 1. 检查缓存 (如果不强制刷新)
if use_cache and not request.force_refresh:
cache_key = redis_cache.generate_cache_key("aggregate", request.dict())
cached_result = redis_cache.get(cache_key)
if cached_result:
# 如果命中缓存,直接返回结果,不创建MongoDB连接
cached_result["message"] = f"聚合查询成功 (来自缓存),返回 {cached_result.get('count', 0)} 个文档"
# 添加缓存时间信息
cached_result["cache_ttl"] = request.cache_ttl
return ApiResponse(**cached_result)
# 2. 只有缓存未命中时才创建MongoDB连接和查询
api = MongoDBQueryAPI()
try:
# 连接数据库
connection_result = api.connect_to_mongodb(
request.connection_string,
request.database_name,
request.collection_name
)
if connection_result["status"] == "error":
return ApiResponse(
status="error",
message=f"连接失败: {connection_result['message']}",
timestamp=datetime.now().isoformat()
)
# 执行聚合查询
result = api.aggregate_pipeline(request.pipeline)
# 3. 设置缓存 (如果查询成功且启用了缓存)
if use_cache and result["status"] == "success":
if cache_key is None: # 如果是强制刷新,之前没生成key
cache_key = redis_cache.generate_cache_key("aggregate", request.dict())
redis_cache.set(cache_key, result, ttl=request.cache_ttl)
# 添加缓存时间信息到响应
result["cache_ttl"] = request.cache_ttl
return ApiResponse(**result)
except Exception as e:
return ApiResponse(
status="error",
message=f"聚合查询过程中发生错误: {str(e)}",
timestamp=datetime.now().isoformat()
)
finally:
# 确保连接被关闭
api.close_connection()
@app.post(
"/distinct",
response_model=ApiResponse,
summary="查询字段唯一值(自动连接和断开)",
description="""
查询指定字段的唯一值,自动处理连接和断开。
**功能特点:**
- 自动连接指定的MongoDB数据库
- 执行distinct查询操作
- 自动断开连接,释放资源
- 支持可选的查询条件过滤
**使用场景:**
- 获取所有部门列表
- 获取所有城市列表
- 获取所有状态值
- 获取满足条件的唯一值
**查询条件示例:**
- 无过滤:查询所有文档的字段唯一值
- 条件过滤:`{"age": {"$gte": 25}}` - 只查询年龄大于25的文档的字段唯一值
- 状态过滤:`{"status": "active"}` - 只查询活跃状态的文档的字段唯一值
""",
tags=["数据查询"],
responses={
200: {
"description": "distinct查询成功",
"content": {
"application/json": {
"example": {
"status": "success",
"message": "distinct查询成功,字段 'department' 返回 3 个唯一值",
"data": {
"field": "department",
"values": ["技术部", "销售部", "人事部"],
"count": 3
},
"count": 3,
"timestamp": "2024-01-01T12:00:00"
}
}
}
},
400: {
"description": "distinct查询失败",
"content": {
"application/json": {
"example": {
"status": "error",
"message": "distinct查询失败: 无法连接到MongoDB服务器",
"timestamp": "2024-01-01T12:00:00"
}
}
}
}
}
)
async def distinct_documents(
request: DistinctRequest
):
"""
执行distinct查询,自动处理连接和断开
"""
cache_key = None
use_cache = request.cache_ttl != 0