Spaces:
Runtime error
Runtime error
Download api/endpoints/tasks.py from Quratulain1/Deploy-Backend: direct link, hf CLI and curl.
- Browser
- Download file 5.48 kB
-
https://huggingface.co/spaces/Quratulain1/Deploy-Backend/resolve/main/api/endpoints/tasks.py
- Command line
-
hf download hf://spaces/Quratulain1/Deploy-Backend/api/endpoints/tasks.py
-
curl -L -o tasks.py https://huggingface.co/spaces/Quratulain1/Deploy-Backend/resolve/main/api/endpoints/tasks.py
5.48 kB
| from typing import Any, List, Optional | |
| from fastapi import APIRouter, Depends, HTTPException, status, Query | |
| from sqlmodel import select, or_ | |
| from sqlmodel.ext.asyncio.session import AsyncSession | |
| from datetime import datetime, timezone | |
| from core.db import get_session | |
| from models.task import Task, TaskCreate, TaskRead, TaskUpdate | |
| from core.auth import get_current_user | |
| router = APIRouter() | |
| async def read_tasks( | |
| session: AsyncSession = Depends(get_session), | |
| current_user: str = Depends(get_current_user), | |
| offset: int = 0, | |
| limit: int = 100, | |
| search: Optional[str] = None, | |
| is_completed: Optional[bool] = None, | |
| ) -> Any: | |
| """ | |
| Retrieve tasks with optional search and status filter. | |
| Results are sorted by updated_at descending (most recent first). | |
| """ | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| logger.info(f"[GET /tasks] User ID: {current_user}, Search: {search}, Completed: {is_completed}") | |
| query = select(Task).where(Task.user_id == current_user) | |
| # Apply search filter (title or description) | |
| if search: | |
| search_term = f"%{search}%" | |
| query = query.where( | |
| or_( | |
| Task.title.ilike(search_term), | |
| Task.description.ilike(search_term) | |
| ) | |
| ) | |
| # Apply status filter | |
| if is_completed is not None: | |
| query = query.where(Task.is_completed == is_completed) | |
| # Sort by updated_at descending (most recent first) | |
| query = query.order_by(Task.updated_at.desc()) | |
| query = query.offset(offset).limit(limit) | |
| result = await session.execute(query) | |
| tasks = result.scalars().all() | |
| return tasks | |
| async def create_task( | |
| *, | |
| session: AsyncSession = Depends(get_session), | |
| task_in: TaskCreate, | |
| current_user: str = Depends(get_current_user), | |
| ) -> Any: | |
| """ | |
| Create new task. | |
| """ | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| logger.info(f"[POST /tasks] User ID: {current_user}, Task: {task_in.title}, Priority: {task_in.priority}, Due: {task_in.due_date}") | |
| # Convert timezone-aware datetime to timezone-naive for PostgreSQL | |
| task_data = task_in.model_dump() | |
| if task_data.get('due_date') and task_data['due_date'].tzinfo is not None: | |
| task_data['due_date'] = task_data['due_date'].replace(tzinfo=None) | |
| db_obj = Task.model_validate(task_data, update={"user_id": current_user}) | |
| session.add(db_obj) | |
| await session.commit() | |
| await session.refresh(db_obj) | |
| logger.info(f"[POST /tasks] Created task ID: {db_obj.id}") | |
| return db_obj | |
| from services.recurrence import calculate_next_due_date | |
| async def patch_task( | |
| *, | |
| session: AsyncSession = Depends(get_session), | |
| id: int, | |
| task_in: TaskUpdate, | |
| current_user: str = Depends(get_current_user), | |
| ) -> Any: | |
| """ | |
| Patch a task. Triggers recurrence if status changes to COMPLETED. | |
| """ | |
| query = select(Task).where(Task.id == id, Task.user_id == current_user) | |
| result = await session.execute(query) | |
| db_obj = result.scalar_one_or_none() | |
| if not db_obj: | |
| raise HTTPException(status_code=404, detail="Task not found") | |
| old_status = db_obj.is_completed | |
| update_data = task_in.model_dump(exclude_unset=True) | |
| # Convert timezone-aware datetime to timezone-naive for PostgreSQL | |
| if update_data.get('due_date') and update_data['due_date'].tzinfo is not None: | |
| update_data['due_date'] = update_data['due_date'].replace(tzinfo=None) | |
| db_obj.sqlmodel_update(update_data) | |
| # Trigger logic: Mark COMPLETED and has recurrence | |
| if not old_status and db_obj.is_completed and db_obj.recurrence_rule: | |
| next_date = calculate_next_due_date( | |
| db_obj.due_date or datetime.now(timezone.utc), | |
| db_obj.recurrence_rule | |
| ) | |
| if next_date: | |
| new_task = Task( | |
| title=db_obj.title, | |
| description=db_obj.description, | |
| user_id=db_obj.user_id, | |
| priority=db_obj.priority, | |
| recurrence_rule=db_obj.recurrence_rule, | |
| due_date=next_date, | |
| is_completed=False | |
| ) | |
| session.add(new_task) | |
| session.add(db_obj) | |
| await session.commit() | |
| await session.refresh(db_obj) | |
| return db_obj | |
| async def read_task( | |
| *, | |
| session: AsyncSession = Depends(get_session), | |
| id: int, | |
| current_user: str = Depends(get_current_user), | |
| ) -> Any: | |
| """ | |
| Get task by ID. | |
| """ | |
| query = select(Task).where(Task.id == id, Task.user_id == current_user) | |
| result = await session.execute(query) | |
| db_obj = result.scalar_one_or_none() | |
| if not db_obj: | |
| raise HTTPException(status_code=404, detail="Task not found") | |
| return db_obj | |
| async def delete_task( | |
| *, | |
| session: AsyncSession = Depends(get_session), | |
| id: int, | |
| current_user: str = Depends(get_current_user), | |
| ) -> Any: | |
| """ | |
| Delete a task. | |
| """ | |
| query = select(Task).where(Task.id == id, Task.user_id == current_user) | |
| result = await session.execute(query) | |
| db_obj = result.scalar_one_or_none() | |
| if not db_obj: | |
| raise HTTPException(status_code=404, detail="Task not found") | |
| await session.delete(db_obj) | |
| await session.commit() | |
| return db_obj | |