prompts.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from fastapi import Depends, FastAPI, HTTPException, status
  2. from datetime import datetime, timedelta
  3. from typing import List, Union, Optional
  4. from fastapi import APIRouter
  5. from pydantic import BaseModel
  6. import json
  7. from apps.web.models.prompts import Prompts, PromptForm, PromptModel
  8. from utils.utils import get_current_user, get_admin_user
  9. from constants import ERROR_MESSAGES
  10. router = APIRouter()
  11. ############################
  12. # GetPrompts
  13. ############################
  14. @router.get("/", response_model=List[PromptModel])
  15. async def get_prompts(user=Depends(get_current_user)):
  16. return Prompts.get_prompts()
  17. ############################
  18. # CreateNewPrompt
  19. ############################
  20. @router.post("/create", response_model=Optional[PromptModel])
  21. async def create_new_prompt(form_data: PromptForm, user=Depends(get_admin_user)):
  22. prompt = Prompts.get_prompt_by_command(form_data.command)
  23. if prompt == None:
  24. prompt = Prompts.insert_new_prompt(user.id, form_data)
  25. if prompt:
  26. return prompt
  27. raise HTTPException(
  28. status_code=status.HTTP_400_BAD_REQUEST,
  29. detail=ERROR_MESSAGES.DEFAULT(),
  30. )
  31. raise HTTPException(
  32. status_code=status.HTTP_400_BAD_REQUEST,
  33. detail=ERROR_MESSAGES.COMMAND_TAKEN,
  34. )
  35. ############################
  36. # GetPromptByCommand
  37. ############################
  38. @router.get("/command/{command}", response_model=Optional[PromptModel])
  39. async def get_prompt_by_command(command: str, user=Depends(get_current_user)):
  40. prompt = Prompts.get_prompt_by_command(f"/{command}")
  41. if prompt:
  42. return prompt
  43. else:
  44. raise HTTPException(
  45. status_code=status.HTTP_401_UNAUTHORIZED,
  46. detail=ERROR_MESSAGES.NOT_FOUND,
  47. )
  48. ############################
  49. # UpdatePromptByCommand
  50. ############################
  51. @router.post("/command/{command}/update", response_model=Optional[PromptModel])
  52. async def update_prompt_by_command(
  53. command: str, form_data: PromptForm, user=Depends(get_admin_user)
  54. ):
  55. prompt = Prompts.update_prompt_by_command(f"/{command}", form_data)
  56. if prompt:
  57. return prompt
  58. else:
  59. raise HTTPException(
  60. status_code=status.HTTP_401_UNAUTHORIZED,
  61. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  62. )
  63. ############################
  64. # DeletePromptByCommand
  65. ############################
  66. @router.delete("/command/{command}/delete", response_model=bool)
  67. async def delete_prompt_by_command(command: str, user=Depends(get_admin_user)):
  68. result = Prompts.delete_prompt_by_command(f"/{command}")
  69. return result