Spaces:
Sleeping
Sleeping
Redis + Websocket
Browse files
app.py
CHANGED
@@ -24,8 +24,16 @@ app.add_middleware(
|
|
24 |
allow_headers=["*"],
|
25 |
)
|
26 |
|
27 |
-
#
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
CACHE_EXPIRE_TIME = 300 # 5 minutes
|
30 |
|
31 |
# MongoDB connection
|
@@ -127,25 +135,28 @@ async def vote_by_voter(vote_request: VoteRequest):
|
|
127 |
if not voter:
|
128 |
raise HTTPException(status_code=404, detail="Voter not found")
|
129 |
|
130 |
-
|
131 |
-
remaining_votes = voter['number_of_votes'] # Số vote còn lại
|
132 |
if vote_request.vote_count > remaining_votes:
|
133 |
raise HTTPException(status_code=400, detail=f"Not enough votes remaining. You have {remaining_votes} votes left")
|
134 |
|
135 |
try:
|
136 |
-
# Cập nhật MongoDB
|
137 |
voter_collection.update_one(
|
138 |
{'_id': ObjectId(vote_request.voter_id)},
|
139 |
-
{'$inc': {'number_of_votes': -vote_request.vote_count}}
|
140 |
)
|
141 |
pdf_collection.update_one(
|
142 |
{'_id': ObjectId(vote_request.file_id)},
|
143 |
{'$inc': {'votes': vote_request.vote_count}}
|
144 |
)
|
145 |
|
146 |
-
#
|
147 |
-
|
148 |
-
|
|
|
|
|
|
|
|
|
149 |
|
150 |
# Emit socket event
|
151 |
updated_file = pdf_collection.find_one({'_id': ObjectId(vote_request.file_id)})
|
@@ -161,14 +172,14 @@ async def vote_by_voter(vote_request: VoteRequest):
|
|
161 |
@app.get("/get-voter")
|
162 |
async def get_voter(id: str):
|
163 |
try:
|
164 |
-
#
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
|
173 |
voter = voter_collection.find_one({'_id': ObjectId(id)})
|
174 |
if not voter:
|
@@ -179,14 +190,15 @@ async def get_voter(id: str):
|
|
179 |
'name': voter['name'],
|
180 |
'group': voter['group'],
|
181 |
'role': voter['role'],
|
182 |
-
'number_of_votes': voter['number_of_votes']
|
183 |
}
|
184 |
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
|
|
190 |
|
191 |
return voter_data
|
192 |
except Exception as e:
|
@@ -209,8 +221,9 @@ async def index():
|
|
209 |
async def shutdown_event():
|
210 |
# Close MongoDB connection
|
211 |
client.close()
|
212 |
-
# Close Redis connection
|
213 |
-
redis_client
|
|
|
214 |
|
215 |
if __name__ == "__main__":
|
216 |
import uvicorn
|
|
|
24 |
allow_headers=["*"],
|
25 |
)
|
26 |
|
27 |
+
# Sửa phần khởi tạo Redis client và thêm biến để kiểm tra Redis status
|
28 |
+
redis_available = False
|
29 |
+
try:
|
30 |
+
redis_client = redis.Redis(host='localhost', port=6379, db=0)
|
31 |
+
redis_client.ping() # Kiểm tra kết nối
|
32 |
+
redis_available = True
|
33 |
+
except redis.ConnectionError:
|
34 |
+
print("Redis không khả dụng - hệ thống sẽ chạy không có cache")
|
35 |
+
redis_client = None
|
36 |
+
|
37 |
CACHE_EXPIRE_TIME = 300 # 5 minutes
|
38 |
|
39 |
# MongoDB connection
|
|
|
135 |
if not voter:
|
136 |
raise HTTPException(status_code=404, detail="Voter not found")
|
137 |
|
138 |
+
remaining_votes = voter['number_of_votes']
|
|
|
139 |
if vote_request.vote_count > remaining_votes:
|
140 |
raise HTTPException(status_code=400, detail=f"Not enough votes remaining. You have {remaining_votes} votes left")
|
141 |
|
142 |
try:
|
143 |
+
# Cập nhật MongoDB
|
144 |
voter_collection.update_one(
|
145 |
{'_id': ObjectId(vote_request.voter_id)},
|
146 |
+
{'$inc': {'number_of_votes': -vote_request.vote_count}}
|
147 |
)
|
148 |
pdf_collection.update_one(
|
149 |
{'_id': ObjectId(vote_request.file_id)},
|
150 |
{'$inc': {'votes': vote_request.vote_count}}
|
151 |
)
|
152 |
|
153 |
+
# Chỉ xóa cache nếu Redis khả dụng
|
154 |
+
if redis_available:
|
155 |
+
try:
|
156 |
+
redis_client.delete('all_files')
|
157 |
+
redis_client.delete(f'voter:{vote_request.voter_id}')
|
158 |
+
except redis.RedisError:
|
159 |
+
print("Không thể xóa cache Redis")
|
160 |
|
161 |
# Emit socket event
|
162 |
updated_file = pdf_collection.find_one({'_id': ObjectId(vote_request.file_id)})
|
|
|
172 |
@app.get("/get-voter")
|
173 |
async def get_voter(id: str):
|
174 |
try:
|
175 |
+
# Chỉ check cache nếu Redis khả dụng
|
176 |
+
if redis_available:
|
177 |
+
try:
|
178 |
+
cached_voter = redis_client.get(f'voter:{id}')
|
179 |
+
if cached_voter:
|
180 |
+
return json.loads(cached_voter)
|
181 |
+
except redis.RedisError:
|
182 |
+
print("Không thể đọc cache Redis")
|
183 |
|
184 |
voter = voter_collection.find_one({'_id': ObjectId(id)})
|
185 |
if not voter:
|
|
|
190 |
'name': voter['name'],
|
191 |
'group': voter['group'],
|
192 |
'role': voter['role'],
|
193 |
+
'number_of_votes': voter['number_of_votes']
|
194 |
}
|
195 |
|
196 |
+
# Chỉ lưu cache nếu Redis khả dụng
|
197 |
+
if redis_available:
|
198 |
+
try:
|
199 |
+
redis_client.setex(f'voter:{id}', CACHE_EXPIRE_TIME, json.dumps(voter_data))
|
200 |
+
except redis.RedisError:
|
201 |
+
print("Không thể lưu cache Redis")
|
202 |
|
203 |
return voter_data
|
204 |
except Exception as e:
|
|
|
221 |
async def shutdown_event():
|
222 |
# Close MongoDB connection
|
223 |
client.close()
|
224 |
+
# Close Redis connection if available
|
225 |
+
if redis_available and redis_client:
|
226 |
+
redis_client.close()
|
227 |
|
228 |
if __name__ == "__main__":
|
229 |
import uvicorn
|