Spaces:
Sleeping
Sleeping
from fastapi import FastAPI, HTTPException, Request, Depends | |
from fastapi.middleware.cors import CORSMiddleware | |
from pydantic import BaseModel | |
import pymongo | |
from bson.objectid import ObjectId | |
# Khởi tạo FastAPI app và cho phép CORS | |
app = FastAPI() | |
origins = [ | |
"*" # Cho phép tất cả origin, bạn nên thay đổi trong môi trường production | |
] | |
app.add_middleware( | |
CORSMiddleware, | |
allow_origins=origins, | |
allow_credentials=True, | |
allow_methods=["*"], | |
allow_headers=["*"], | |
) | |
# MongoDB connection | |
mongo_url = "mongodb+srv://ip6ofme:[email protected]/" | |
client = pymongo.MongoClient(mongo_url) | |
db = client["test"] | |
pdf_collection = db["PdfDetails"] | |
voter_collection = db["Voters"] | |
# Pydantic models để validate dữ liệu | |
class PDF(BaseModel): | |
title: str | |
group: str | |
url: str | |
class Vote(BaseModel): | |
id: str | |
class Voter(BaseModel): | |
name: str | |
group: str | |
class VoteByVoter(BaseModel): | |
voter_id: str | |
file_id: str | |
# API để upload file và lưu thông tin vào MongoDB | |
async def upload_file(pdf: PDF): | |
new_pdf = { | |
"title": pdf.title, | |
"group": pdf.group, | |
"url": pdf.url, | |
"votes": 0 | |
} | |
result = pdf_collection.insert_one(new_pdf) | |
return {"status": "ok", "id": str(result.inserted_id)} | |
# API để tăng số lượng vote của file dựa trên ID | |
async def vote(vote: Vote): | |
try: | |
file = pdf_collection.find_one({"_id": ObjectId(vote.id)}) | |
if not file: | |
raise HTTPException(status_code=404, detail="File not found") | |
pdf_collection.update_one({"_id": ObjectId(vote.id)}, {"$inc": {"votes": 1}}) | |
return {"status": "ok"} | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=str(e)) | |
# API để lấy số lượng votes của file theo ID | |
async def get_votes(id: str): | |
try: | |
file = pdf_collection.find_one({"_id": ObjectId(id)}) | |
if not file: | |
raise HTTPException(status_code=404, detail="File not found") | |
return {"status": "ok", "votes": file.get("votes", 0)} | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=str(e)) | |
# API để lấy danh sách tất cả các file | |
async def get_files(): | |
try: | |
files = pdf_collection.find({}) | |
file_list = [] | |
for file in files: | |
file_list.append({ | |
"id": str(file["_id"]), | |
"title": file["title"], | |
"group": file["group"], | |
"url": file["url"], | |
"votes": file.get("votes", 0) | |
}) | |
return {"status": "ok", "data": file_list} | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=str(e)) | |
# API mới để đăng ký người bình chọn | |
async def register_voter(voter: Voter): | |
new_voter = { | |
"name": voter.name, | |
"group": voter.group, | |
"number_of_votes": 0 | |
} | |
result = voter_collection.insert_one(new_voter) | |
return {"status": "ok", "id": str(result.inserted_id)} | |
# API mới để bình chọn | |
async def vote_by_voter(vote: VoteByVoter): | |
voter = voter_collection.find_one({"_id": ObjectId(vote.voter_id)}) | |
if not voter: | |
raise HTTPException(status_code=404, detail="Voter not found") | |
if voter["number_of_votes"] >= 5: | |
raise HTTPException(status_code=400, detail="Maximum votes reached") | |
# Tăng số lượt bình chọn của người dùng | |
voter_collection.update_one({"_id": ObjectId(vote.voter_id)}, {"$inc": {"number_of_votes": 1}}) | |
# Tăng số lượt bình chọn cho file | |
pdf_collection.update_one({"_id": ObjectId(vote.file_id)}, {"$inc": {"votes": 1}}) | |
return {"status": "ok", "message": "Vote recorded successfully"} | |
# API để lấy thông tin người bình chọn | |
async def get_voter(id: str): | |
voter = voter_collection.find_one({"_id": ObjectId(id)}) | |
if not voter: | |
raise HTTPException(status_code=404, detail="Voter not found") | |
return { | |
"status": "ok", | |
"name": voter["name"], | |
"group": voter["group"], | |
"number_of_votes": voter["number_of_votes"] | |
} | |
# Khởi chạy server | |
if __name__ == "__main__": | |
import uvicorn | |
uvicorn.run(app, host="0.0.0.0", port=7860) |