111 lines
5.1 KiB
Python
111 lines
5.1 KiB
Python
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.survey import manage_survey
|
|
|
|
KST = datetime.timezone(datetime.timedelta(hours=9))
|
|
|
|
router = APIRouter(
|
|
prefix="/survey",
|
|
tags=["survey"],
|
|
responses={404: {"description": "Not found"}},
|
|
)
|
|
|
|
# -----------------------------------------------------------------------------------------------
|
|
|
|
async def get_body(request: Request):
|
|
return await request.body()
|
|
|
|
#==================================================================================================
|
|
# 설문조사 데이터 수집
|
|
#==================================================================================================
|
|
@router.post("/collect")
|
|
async def collect_survey(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:
|
|
# 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={})
|
|
# body에서 ID 추출
|
|
try:
|
|
body = json.loads(body)
|
|
except json.JSONDecodeError as e:
|
|
# 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={})
|
|
|
|
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
|
|
# 데이터 검증
|
|
qna_list = body['QNA']
|
|
question_list = []
|
|
answer_list = []
|
|
for idx, qna in enumerate(qna_list):
|
|
if idx%2 == 0:
|
|
question_list.append(qna)
|
|
else:
|
|
answer_list.append(qna)
|
|
body['question_list'] = question_list
|
|
body['answer_list'] = answer_list
|
|
# DB 저장
|
|
insert_survey_update_survey_yn_result = await manage_survey.insert_survey_update_survey_yn(survey=body, db=db)
|
|
if insert_survey_update_survey_yn_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:
|
|
# 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={})
|
|
|
|
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}"
|
|
)
|
|
|
|
|
|
|