ManTea commited on
Commit
5c82ae4
·
1 Parent(s): 5ef0fc4

Redis + Websocket

Browse files
Files changed (1) hide show
  1. app.py +13 -12
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from fastapi import FastAPI, HTTPException, Form, Request
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import JSONResponse
@@ -106,11 +107,14 @@ async def get_files():
106
 
107
  @app.post("/register-voter")
108
  async def register_voter(voter: VoterRegistration):
 
 
 
109
  new_voter = {
110
  'name': voter.name,
111
  'group': voter.group,
112
  'role': voter.role,
113
- 'number_of_votes': 0
114
  }
115
  result = voter_collection.insert_one(new_voter)
116
  return {'status': 'ok', 'id': str(result.inserted_id)}
@@ -124,16 +128,16 @@ async def vote_by_voter(vote_request: VoteRequest):
124
  if not voter:
125
  raise HTTPException(status_code=404, detail="Voter not found")
126
 
127
- max_votes = 10 if voter['role'] == 'judge' else 2
128
-
129
- if voter['number_of_votes'] + vote_request.vote_count > max_votes:
130
- raise HTTPException(status_code=400, detail="Maximum votes exceeded")
131
 
132
  try:
133
- # Update MongoDB
134
  voter_collection.update_one(
135
  {'_id': ObjectId(vote_request.voter_id)},
136
- {'$inc': {'number_of_votes': vote_request.vote_count}}
137
  )
138
  pdf_collection.update_one(
139
  {'_id': ObjectId(vote_request.file_id)},
@@ -165,7 +169,6 @@ async def get_voter(id: str):
165
  return json.loads(cached_voter)
166
  except RedisError as redis_err:
167
  print(f"Redis error: {redis_err}")
168
- # Continue without cache if Redis fails
169
  pass
170
 
171
  voter = voter_collection.find_one({'_id': ObjectId(id)})
@@ -177,15 +180,13 @@ async def get_voter(id: str):
177
  'name': voter['name'],
178
  'group': voter['group'],
179
  'role': voter['role'],
180
- 'number_of_votes': voter['number_of_votes']
181
  }
182
 
183
- # Try to save to cache
184
  try:
185
  redis_client.setex(f'voter:{id}', CACHE_EXPIRE_TIME, json.dumps(voter_data))
186
  except RedisError as redis_err:
187
  print(f"Redis caching error: {redis_err}")
188
- # Continue even if caching fails
189
  pass
190
 
191
  return voter_data
@@ -212,6 +213,6 @@ async def shutdown_event():
212
  # Close Redis connection
213
  redis_client.close()
214
 
215
- if __name__ == "__main__":
216
  import uvicorn
217
  uvicorn.run(app, host="0.0.0.0", port=5000)
 
1
+ Nguyễn Xuân Cường
2
  from fastapi import FastAPI, HTTPException, Form, Request
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from fastapi.responses import JSONResponse
 
107
 
108
  @app.post("/register-voter")
109
  async def register_voter(voter: VoterRegistration):
110
+ # Xác định số lượng vote tối đa dựa vào role
111
+ max_votes = 10 if voter.role == 'judge' else 2
112
+
113
  new_voter = {
114
  'name': voter.name,
115
  'group': voter.group,
116
  'role': voter.role,
117
+ 'number_of_votes': max_votes # Khởi tạo với số vote tối đa
118
  }
119
  result = voter_collection.insert_one(new_voter)
120
  return {'status': 'ok', 'id': str(result.inserted_id)}
 
128
  if not voter:
129
  raise HTTPException(status_code=404, detail="Voter not found")
130
 
131
+ # Kiểm tra số vote còn lại
132
+ remaining_votes = voter['number_of_votes'] # Số vote còn lại
133
+ if vote_request.vote_count > remaining_votes:
134
+ raise HTTPException(status_code=400, detail=f"Not enough votes remaining. You have {remaining_votes} votes left")
135
 
136
  try:
137
+ # Cập nhật MongoDB - giảm số vote còn lại
138
  voter_collection.update_one(
139
  {'_id': ObjectId(vote_request.voter_id)},
140
+ {'$inc': {'number_of_votes': -vote_request.vote_count}} # Giảm số vote còn lại
141
  )
142
  pdf_collection.update_one(
143
  {'_id': ObjectId(vote_request.file_id)},
 
169
  return json.loads(cached_voter)
170
  except RedisError as redis_err:
171
  print(f"Redis error: {redis_err}")
 
172
  pass
173
 
174
  voter = voter_collection.find_one({'_id': ObjectId(id)})
 
180
  'name': voter['name'],
181
  'group': voter['group'],
182
  'role': voter['role'],
183
+ 'number_of_votes': voter['number_of_votes'] # Số này giờ là số vote còn lại
184
  }
185
 
 
186
  try:
187
  redis_client.setex(f'voter:{id}', CACHE_EXPIRE_TIME, json.dumps(voter_data))
188
  except RedisError as redis_err:
189
  print(f"Redis caching error: {redis_err}")
 
190
  pass
191
 
192
  return voter_data
 
213
  # Close Redis connection
214
  redis_client.close()
215
 
216
+ if _name_ == "_main_":
217
  import uvicorn
218
  uvicorn.run(app, host="0.0.0.0", port=5000)