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

update role

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