ManTea commited on
Commit
ecf06e7
·
1 Parent(s): f8a47c9

update role

Browse files
Files changed (1) hide show
  1. app.py +98 -104
app.py CHANGED
@@ -1,11 +1,20 @@
1
- from flask import Flask, request, jsonify
2
- from flask_cors import CORS
 
 
 
3
  import pymongo
4
- from bson.objectid import ObjectId
5
 
6
- # Khởi tạo Flask app cho phép CORS
7
- app = Flask(__name__)
8
- CORS(app)
 
 
 
 
 
 
 
9
 
10
  # MongoDB connection
11
  mongo_url = "mongodb+srv://ip6ofme:[email protected]/"
@@ -14,126 +23,111 @@ db = client["test"]
14
  pdf_collection = db["PdfDetails"]
15
  voter_collection = db["Voters"]
16
 
17
- # API để upload file và lưu thông tin vào MongoDB
18
- @app.route('/upload-files', methods=['POST'])
19
- def upload_file():
20
- # Chỉ lưu thông tin vào MongoDB
21
- title = request.form.get('title')
22
- group = request.form.get('group')
23
- firebase_url = request.form.get('url')
 
 
 
 
 
 
 
 
 
24
  new_pdf = {
25
- 'title': title,
26
- 'group': group,
27
- 'url': firebase_url,
28
- 'votes': 0
29
  }
30
  result = pdf_collection.insert_one(new_pdf)
31
- return jsonify({'status': 'ok', 'id': str(result.inserted_id)})
32
-
33
- # API để tăng số lượng vote của file dựa trên ID
34
- @app.route('/vote', methods=['POST'])
35
- def vote():
36
- data = request.json
37
- file_id = data.get('id')
38
 
 
 
 
 
39
  try:
40
- file = pdf_collection.find_one({'_id': ObjectId(file_id)})
41
  if not file:
42
- return jsonify({'status': 'error', 'message': 'File not found'}), 404
43
-
44
- pdf_collection.update_one({'_id': ObjectId(file_id)}, {'$inc': {'votes': 1}})
45
- return jsonify({'status': 'ok'})
46
  except Exception as e:
47
- return jsonify({'status': 'error', 'message': str(e)}), 500
48
-
49
- # API để lấy số lượng votes của file theo ID
50
- @app.route('/get-votes', methods=['GET'])
51
- def get_votes():
52
- file_id = request.args.get('id')
53
 
 
 
 
54
  try:
55
- file = pdf_collection.find_one({'_id': ObjectId(file_id)})
56
  if not file:
57
- return jsonify({'status': 'error', 'message': 'File not found'}), 404
58
-
59
- return jsonify({'status': 'ok', 'votes': file.get('votes', 0)})
60
  except Exception as e:
61
- return jsonify({'status': 'error', 'message': str(e)}), 500
62
 
63
- # API để lấy danh sách tất cả các file
64
- @app.route('/get-files', methods=['GET'])
65
- def get_files():
66
  try:
67
  files = pdf_collection.find({})
68
- file_list = []
69
- for file in files:
70
- file_list.append({
71
- 'id': str(file['_id']),
72
- 'title': file['title'],
73
- 'group': file['group'],
74
- 'url': file['url'],
75
- 'votes': file.get('votes', 0)
76
- })
77
- return jsonify({'status': 'ok', 'data': file_list})
 
78
  except Exception as e:
79
- return jsonify({'status': 'error', 'message': str(e)}), 500
80
 
81
- # API mới để đăng ký người bình chọn
82
- @app.route('/register-voter', methods=['POST'])
83
- def register_voter():
84
- data = request.json
85
- name = data.get('name')
86
- group = data.get('group')
87
- role = data.get('role') # Thêm trường role
88
-
89
  new_voter = {
90
- 'name': name,
91
- 'group': group,
92
- 'role': role, # Lưu role vào MongoDB
93
- 'number_of_votes': 0
94
  }
95
  result = voter_collection.insert_one(new_voter)
96
- return jsonify({'status': 'ok', 'id': str(result.inserted_id)})
97
 
98
- # API mới để bình chọn
99
- @app.route('/vote-by-voter', methods=['POST'])
100
- def vote_by_voter():
101
- data = request.json
102
- voter_id = data.get('voter_id')
103
- file_id = data.get('file_id')
104
-
105
- voter = voter_collection.find_one({'_id': ObjectId(voter_id)})
106
  if not voter:
107
- return jsonify({'status': 'error', 'message': 'Voter not found'}), 404
108
-
109
- max_votes = 5 if voter['role'] == 'judge' else 2
110
-
111
- if voter['number_of_votes'] >= max_votes:
112
- return jsonify({'status': 'error', 'message': 'Maximum votes reached'}), 400
113
 
114
- # Tăng số lượt bình chọn của người dùng
115
- voter_collection.update_one({'_id': ObjectId(voter_id)}, {'$inc': {'number_of_votes': 1}})
 
116
 
117
- # Tăng số lượt bình chọn cho file
118
- pdf_collection.update_one({'_id': ObjectId(file_id)}, {'$inc': {'votes': 1}})
119
-
120
- return jsonify({'status': 'ok', 'message': 'Vote recorded successfully'})
121
 
122
- # API để lấy thông tin người bình chọn
123
- @app.route('/get-voter', methods=['GET'])
124
- def get_voter():
125
- voter_id = request.args.get('id')
126
- voter = voter_collection.find_one({'_id': ObjectId(voter_id)})
127
  if not voter:
128
- return jsonify({'status': 'error', 'message': 'Voter not found'}), 404
129
- return jsonify({
130
- 'status': 'ok',
131
- 'name': voter['name'],
132
- 'group': voter['group'],
133
- 'role': voter['role'], # Thêm role vào phản hồi
134
- 'number_of_votes': voter['number_of_votes']
135
- })
136
-
137
- # Khởi chạy server
138
- if __name__ == "__main__":
139
- app.run(port=5000, debug=True)
 
1
+ from fastapi import FastAPI, HTTPException, Request, Form, Depends
2
+ from fastapi.responses import JSONResponse
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from pydantic import BaseModel
5
+ from bson import ObjectId
6
  import pymongo
 
7
 
8
+ app = FastAPI()
9
+
10
+ # Enable CORS
11
+ app.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=["*"],
14
+ allow_credentials=True,
15
+ allow_methods=["*"],
16
+ allow_headers=["*"],
17
+ )
18
 
19
  # MongoDB connection
20
  mongo_url = "mongodb+srv://ip6ofme:[email protected]/"
 
23
  pdf_collection = db["PdfDetails"]
24
  voter_collection = db["Voters"]
25
 
26
+ # Models
27
+ class VoteRequest(BaseModel):
28
+ id: str
29
+
30
+ class VoterVoteRequest(BaseModel):
31
+ voter_id: str
32
+ file_id: str
33
+
34
+ class RegisterVoterRequest(BaseModel):
35
+ name: str
36
+ group: str
37
+ role: str
38
+
39
+ # API to upload file information to MongoDB
40
+ @app.post("/upload-files")
41
+ async def upload_file(title: str = Form(...), group: str = Form(...), url: str = Form(...)):
42
  new_pdf = {
43
+ "title": title,
44
+ "group": group,
45
+ "url": url,
46
+ "votes": 0,
47
  }
48
  result = pdf_collection.insert_one(new_pdf)
49
+ return {"status": "ok", "id": str(result.inserted_id)}
 
 
 
 
 
 
50
 
51
+ # API to increment file vote count by ID
52
+ @app.post("/vote")
53
+ async def vote(request: VoteRequest):
54
+ file_id = request.id
55
  try:
56
+ file = pdf_collection.find_one({"_id": ObjectId(file_id)})
57
  if not file:
58
+ raise HTTPException(status_code=404, detail="File not found")
59
+ pdf_collection.update_one({"_id": ObjectId(file_id)}, {"$inc": {"votes": 1}})
60
+ return {"status": "ok"}
 
61
  except Exception as e:
62
+ raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
63
 
64
+ # API to get vote count by file ID
65
+ @app.get("/get-votes")
66
+ async def get_votes(id: str):
67
  try:
68
+ file = pdf_collection.find_one({"_id": ObjectId(id)})
69
  if not file:
70
+ raise HTTPException(status_code=404, detail="File not found")
71
+ return {"status": "ok", "votes": file.get("votes", 0)}
 
72
  except Exception as e:
73
+ raise HTTPException(status_code=500, detail=str(e))
74
 
75
+ # API to retrieve list of all files
76
+ @app.get("/get-files")
77
+ async def get_files():
78
  try:
79
  files = pdf_collection.find({})
80
+ file_list = [
81
+ {
82
+ "id": str(file["_id"]),
83
+ "title": file["title"],
84
+ "group": file["group"],
85
+ "url": file["url"],
86
+ "votes": file.get("votes", 0),
87
+ }
88
+ for file in files
89
+ ]
90
+ return {"status": "ok", "data": file_list}
91
  except Exception as e:
92
+ raise HTTPException(status_code=500, detail=str(e))
93
 
94
+ # API to register a voter
95
+ @app.post("/register-voter")
96
+ async def register_voter(request: RegisterVoterRequest):
 
 
 
 
 
97
  new_voter = {
98
+ "name": request.name,
99
+ "group": request.group,
100
+ "role": request.role,
101
+ "number_of_votes": 0,
102
  }
103
  result = voter_collection.insert_one(new_voter)
104
+ return {"status": "ok", "id": str(result.inserted_id)}
105
 
106
+ # API for voting by voter
107
+ @app.post("/vote-by-voter")
108
+ async def vote_by_voter(request: VoterVoteRequest):
109
+ voter = voter_collection.find_one({"_id": ObjectId(request.voter_id)})
 
 
 
 
110
  if not voter:
111
+ raise HTTPException(status_code=404, detail="Voter not found")
 
 
 
 
 
112
 
113
+ max_votes = 5 if voter["role"] == "judge" else 2
114
+ if voter["number_of_votes"] >= max_votes:
115
+ raise HTTPException(status_code=400, detail="Maximum votes reached")
116
 
117
+ voter_collection.update_one({"_id": ObjectId(request.voter_id)}, {"$inc": {"number_of_votes": 1}})
118
+ pdf_collection.update_one({"_id": ObjectId(request.file_id)}, {"$inc": {"votes": 1}})
119
+ return {"status": "ok", "message": "Vote recorded successfully"}
 
120
 
121
+ # API to get voter information
122
+ @app.get("/get-voter")
123
+ async def get_voter(id: str):
124
+ voter = voter_collection.find_one({"_id": ObjectId(id)})
 
125
  if not voter:
126
+ raise HTTPException(status_code=404, detail="Voter not found")
127
+ return {
128
+ "status": "ok",
129
+ "name": voter["name"],
130
+ "group": voter["group"],
131
+ "role": voter["role"],
132
+ "number_of_votes": voter["number_of_votes"],
133
+ }