Merge pull request 'feature/tags-collection' (#36) from feature/tags-collection into master

Reviewed-on: #36
This commit is contained in:
v4l3n71n 2024-12-21 23:06:40 +01:00
commit ed1334f00a
4 changed files with 158 additions and 3 deletions

View File

@ -1,7 +1,7 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from .routers import users, token, mail, events
from .routers import users, token, mail, events, tags
from .dependencies import user_add
import os
@ -29,6 +29,7 @@ app.include_router(users.router)
app.include_router(token.router)
app.include_router(mail.router)
app.include_router(events.router)
app.include_router(tags.router)
@app.on_event("startup")

24
app/models/tags.py Normal file
View File

@ -0,0 +1,24 @@
from pydantic import BaseModel, EmailStr
from pydantic_mongo import AbstractRepository, ObjectIdField
from datetime import datetime, date
class Tags(BaseModel):
id: ObjectIdField = None
name: str
created_at: datetime = datetime.today()
class TagsOut(BaseModel):
id: ObjectIdField = None
name: str
class TagsIn(BaseModel):
name: str
class TagsIDS(BaseModel):
ids: list[str]
class TagsRepository(AbstractRepository[Tags]):
class Meta:
collection_name = "tags"

View File

@ -2,7 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException, status, Response
from fastapi.responses import JSONResponse
from datetime import datetime
from ..dependencies import users_token, permissions_checker, database
from ..models import events, users
from ..models import events, users, tags
from pydantic import EmailStr
from typing import Annotated, Union
from bson import ObjectId
@ -330,6 +330,7 @@ async def update_events(authorize: Annotated[bool, Depends(permissions_checker.P
detail="Body request is empty"
)
event_repository = events.EventRepository(database=database.database)
tags_repository = tags.TagsRepository(database=database.database)
event = event_repository.find_one_by({"name": {'$eq': eventSingle.name}})
if event is not None:
@ -347,6 +348,11 @@ async def update_events(authorize: Annotated[bool, Depends(permissions_checker.P
event.longitude = eventSingle.longitude
event.imgUrl = eventSingle.imgUrl
event.tags = eventSingle.tags
for tag_name in eventSingle:
tag = tags_repository.find_one_by({"name": {'$eq': tag_name}})
if tag is None:
tag = Tags(name=tag_name)
tags_repository.save(tag)
event.status = 1
event.created_at = datetime.today()
event_repository.save(event)
@ -363,7 +369,7 @@ async def update_events_id(item_id: str, authorize: Annotated[bool, Depends(perm
detail="Body request is empty"
)
event_repository = events.EventRepository(database=database.database)
tags_repository = tags.TagsRepository(database=database)
event = event_repository.find_one_by({"id": {'$eq': ObjectId(item_id)}})
if event is None:
raise HTTPException(
@ -378,6 +384,11 @@ async def update_events_id(item_id: str, authorize: Annotated[bool, Depends(perm
event.end_date = eventSingle.end_date
event.organizers = eventSingle.organizers
event.tags = eventSingle.tags
for tag_name in eventSingle:
tag = tags_repository.find_one_by({"name": {'$eq': tag_name}})
if tag is None:
tag = Tags(name=tag_name)
tags_repository.save(tag)
event.latitude = eventSingle.latitude
event.longitude = eventSingle.longitude
event.updated_at = datetime.today()

119
app/routers/tags.py Normal file
View File

@ -0,0 +1,119 @@
from fastapi import APIRouter, Depends, HTTPException, status, Response
from fastapi.responses import JSONResponse
from datetime import datetime
from ..dependencies import users_token, permissions_checker, database
from ..models import tags, users
from pydantic import EmailStr
from typing import Annotated, Union
from bson import ObjectId
from datetime import datetime
router = APIRouter()
@router.get("/tags", tags=["tags"], response_model=list[tags.TagsOut])
async def read_tags(
authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))],
skip: int = 0,
limit: int = 20,
id_tags: str | None = None,
name: str | None = None
):
# Validate `skip` and `limit`
if limit < 1 or skip < 0 or limit < skip:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="`skip` should be >= 0 and `limit` should be > 0 and greater than `skip`.",
)
limit = limit + skip
# Initialize filters
filters = []
if name:
filters.append({"name": {"$eq": name, "$options": "i"}})
# Add ID filter
if id_tags:
try:
tags_id = ObjectId(id_tags)
filters.append({"_id": {"$eq": event_id}})
except Exception:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid event ID format.")
# Combine all filters
object_search = {"$and": filters} if filters else {}
# Fetch and return results
tags_repository = tags.TagsRepository(database=database.database)
list_tags = []
for tag_index in tags_repository.find_by(object_search, limit=limit, skip=skip):
tag = tags.TagsOut(
id=tag_index.id,
name=tag_index.name
)
list_tags.append(event)
return list_tags
@router.get("/tags/count", tags=["tags"])
async def read_tags_count(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]):
count = database.database.get_collection("tags").estimated_document_count()
content = {"count":count}
response = JSONResponse(content=content)
return response
@router.get("/tags/{item_id}", tags=["tags"], response_model=tags.Tags)
async def read_tags_id(item_id : str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))]):
tags_repository = tags.TagsRepository(database=database.database)
tag = tags_repository.find_one_by_id(ObjectId(item_id))
return tag
@router.delete("/tags/groups",tags=["tags"])
async def delete_tags_groups(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], tagsids: tags.TagsIDS | None = None):
if len(tagsids.ids) == 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="eventids should be greater than 0"
)
tag_repository = tags.TagsRepository(database=database.database)
for i in tagsids.ids:
tag = tag_repository.find_one_by_id(ObjectId(i))
tag_repository.delete_one(tag)
content = {"message": "tags removed"}
response = JSONResponse(content=content)
return response
@router.delete("/tags/{item_id}", tags=["tags"])
async def delete_tags_id(item_id : str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))]):
tag_repository = tags.TagsRepository(database=database.database)
tag = tag_repository.find_one_by_id(ObjectId(item_id))
event_repository.delete_one(event)
content = {"message": "tags delete"}
response = JSONResponse(content=content)
return responsed
@router.put("/tags", tags=["tags"], status_code=status.HTTP_201_CREATED)
async def update_tags(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], tagSingle: tags.TagsIn | None = None):
if tagSingle is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Body request is empty"
)
tag_repository = tags.TagsRepository(database=database.database)
tag = tag_repository.find_one_by({"name": {'$eq': tagSingle.name}})
if tag is not None:
raise HTTPException(
status_code=status.HTTP_204_NO_CONTENT,
detail="name"
)
tag = tags.Tags(name=tagSingle.name)
tag.created_at = datetime.today()
tag_repository.save(event)
content = {"message": "tags created"}
response = JSONResponse(content=content, status_code=status.HTTP_201_CREATED)
return response