backend/fastapi/app/router/inquiry_api.py

103 lines
4.8 KiB
Python
Raw Normal View History

2025-01-20 05:46:25 +00:00
from fastapi import APIRouter, Depends, HTTPException, Header, Body, status, Request
from sqlalchemy.orm import Session
from fastapi.security import APIKeyHeader
from typing import Union, Optional, List
from typing_extensions import Annotated
from db import models, schemas, crud
import json
import logging
import datetime
from kafka import KafkaProducer
from fastapi.responses import FileResponse, StreamingResponse
import io
import openpyxl
import time
from db.schemas import RawData, RtuGenerator
from db.base import get_db
from db.models import RawDatas, Raw_data_herit
import pandas as pd
from process.logger import logger
from process.certification import cert_process
from process.response import response
from process.inquiry import manage_inquiry
KST = datetime.timezone(datetime.timedelta(hours=9))
router = APIRouter(
prefix="/inquiry",
tags=["inquiry"],
responses={404: {"description": "Not found"}},
)
# -----------------------------------------------------------------------------------------------
async def get_body(request: Request):
return await request.body()
#==================================================================================================
# 문의 데이터 수집
#==================================================================================================
@router.post("/request")
async def request_inquiry(request: Request, body: bytes = Depends(get_body), db: Session = Depends(get_db)):
try:
# 인증서 갱신
auth_token = cert_process.renew_cert(request=request)
if auth_token['result'] == 'OK':
auth_token = auth_token['data']
elif auth_token['result'] == 'TOKEN_EXPIRED':
raise token_expired_return_process(auth_token['msg'])
else:
2025-01-27 14:39:33 +00:00
# return await response.error_res(auth_token=auth_token, auth_type='NOMAL', msg_title='사용자 인증 에러', msg_content='사용자 인증 정보가 정확하지 않습니다. 관리자에게 문의해주세요.', data={})
return await response.error_res(auth_token=auth_token, auth_type='NOMAL', msg_title='User Authentication Error', msg_content='User authentication information is incorrect. Please contact the administrator.', data={})
2025-01-20 05:46:25 +00:00
# body에서 ID 추출
try:
body = json.loads(body)
except json.JSONDecodeError as e:
2025-01-27 14:39:33 +00:00
# return await response.error_res(auth_token=auth_token, auth_type='NOMAL', msg_title='데이터 에러', msg_content='데이터 처리 장애가 발생했습니다. 요청정보를 정확히 입력했는지 확인해주세요.', data={})
return await response.error_res(auth_token=auth_token, auth_type='NOMAL', msg_title='Data Error', msg_content='Data processing error occurred. Please check if the requested information is entered correctly.', data={})
2025-01-20 05:46:25 +00:00
user_seq_result = cert_process.get_user_seq_by_token(token=auth_token['token'])
if user_seq_result["result"] == 'OK':
user_seq = user_seq_result['data']['user_seq']
body['user_seq'] = user_seq
# 데이터 검증
title = body['title']
contents = body['contents']
# DB 저장
insert_inquiry_result = await manage_inquiry.insert_inquiry(inquiry=body, db=db)
if insert_inquiry_result['result'] == 'OK':
return await response.ok_res(auth_token=auth_token, data={}, db=db)
else:
return await response.error_res(auth_token=auth_token, auth_type='NOMAL', msg_title='문의 저장 실패', msg_content='문의 저장 처리중 에러가 발생했습니다.', data={})
else:
2025-01-27 14:39:33 +00:00
# return await response.error_res(auth_token=auth_token, auth_type='NOMAL', msg_title='사용자 인증 에러', msg_content='사용자 인증 정보가 정확하지 않습니다. 관리자에게 문의해주세요.', data={})
return await response.error_res(auth_token=auth_token, auth_type='NOMAL', msg_title='User Authentication Error', msg_content='User authentication information is incorrect. Please contact the administrator.', data={})
2025-01-20 05:46:25 +00:00
except Exception as e:
logger.error(f"request error. URL: /room/score/create/room\nerror message: {e}")
return await response.error_res(auth_token=auth_token, auth_type='NOMAL', msg_title='방 생성 에러', msg_content='방 생성 처리중 에러가 발생했습니다.', data={})
#==================================================================================================
# 필요한 함수
#==================================================================================================
# 401 에러 발생
def token_expired_return_process(fail_msg):
logger.error(f"request fail: {fail_msg}")
return HTTPException(
status_code=401,
detail=f"{fail_msg}"
)