zbparse/flask_app/ConnectionLimiter.py

22 lines
534 B
Python
Raw Normal View History

2024-11-25 10:13:39 +08:00
# flask_app/ConnectionLimiter.py
import threading
2024-11-25 09:15:56 +08:00
from functools import wraps
class ConnectionLimiter:
2024-11-25 10:27:46 +08:00
def __init__(self, max_connections=1):
2024-11-25 10:13:39 +08:00
self.semaphore = threading.Semaphore(max_connections)
2024-11-25 09:15:56 +08:00
def limit_connections(self, f):
2024-11-25 10:13:39 +08:00
"""装饰器:限制并发连接数"""
2024-11-25 09:15:56 +08:00
@wraps(f)
2024-11-25 10:13:39 +08:00
def wrapped(*args, **kwargs):
self.semaphore.acquire()
2024-11-25 09:15:56 +08:00
try:
return f(*args, **kwargs)
finally:
self.semaphore.release()
2024-11-25 10:13:39 +08:00
return wrapped