티스토리 뷰
project/공공데이터 공통표준용어 검색
[Project] 공공데이터 공통표준용어 검색 만들기 - FastAPI ResponseBody Model 만들기
octo54 2024. 3. 26. 18:42반응형
FastAPI ResponseBody Model 만들기
https://fastapi.tiangolo.com/ko/tutorial/response-model/
응답 모델 - FastAPI
FastAPI framework, high performance, easy to learn, fast to code, ready for production
fastapi.tiangolo.com
1. ResponseModel
from typing import Optional, List
from pydantic import Field, BaseModel
class ResponseModel(BaseModel):
msg:str = Field("", description="응답메세지")
isOk:bool = Field(True, description="응답 성공 여부")
items:Optional[List[dict] | dict] = Field(None, description="응답 데이터")
2. ReponseModelPaging
class Paging(BaseModel):
totalSize: int = Field(0, description="전체 갯수")
totalPage: int = Field(0, description="전체 페이지 수")
page: int = Field(1, description="현재 페이지")
size: int = Field(10, description="출력 갯수")
class ResponseModelPaging(ResponseModel):
paging: Paging = Field(Paging(), description="페이지 정보")
3. Genric Type
from typing import TypeVar, Generic
T = TypeVar("T")
class ResponseModel(BaseModel,Generic[T]):
4. Main
"""
main.py
@제목: 메인 실행 파일
@설명: 메인 실행 파일
작성일자 작성자
-----------------------
2024.03.14 hiio420
"""
import math
import os.path
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.middleware.cors import CORSMiddleware
from libs import ExcelUtils
from models import ResponseModel, ResponseModelPaging, Paging
# 엑셀 파일 불러오기
CUR_DIR = os.path.abspath(os.path.dirname(__file__))
UPLOAD_DIR = os.path.join(CUR_DIR, 'upload')
file_path = os.path.join(UPLOAD_DIR, '(붙임)공공데이터 공통표준용어(2022.7월).xlsx')
excel_utils = ExcelUtils()
df_dict = excel_utils.read_excel(file_path)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class Item(BaseModel):
data_id: int = 0
page: int = 1
limit: int = 10
@app.get("/",response_model=ResponseModelPaging[dict])
def read_root(dataId: int = 0, page: int = 1, limit: int = 10, srchTxt: str = ""):
if page < 1:
page = 0
if limit < 10:
limit = 10
df = df_dict[dataId]
df = df[df.apply(lambda row: row.astype(str).str.contains(srchTxt, case=False).any(), axis=1)]
first_idx = (page - 1) * limit
last_idx = first_idx + limit - 1
total_size = df.shape[0]
last_page = math.ceil(total_size / limit)
df_sliced = df[first_idx:last_idx + 1].copy()
df_sliced["번호"] = [i for i in
range(total_size - (page - 1) * limit, total_size - (page - 1) * limit - df_sliced.shape[0], -1)]
data = []
if df_sliced.shape[0] != 0:
data = df_sliced.to_dict("records")
paging = Paging(page=page, size=limit, totalPage=last_page,totalSize=total_size)
resp = ResponseModelPaging(items=data,paging=paging)
print(resp)
return resp
'project > 공공데이터 공통표준용어 검색' 카테고리의 다른 글
[Project] 공공데이터 공통표준용어 검색 만들기 - Next.js 컴포넌트화 (0) | 2024.03.26 |
---|---|
[Project] 공공데이터 공통표준용어 검색 만들기 - 화면 만들어보기 #3 fetch 로 데이터 불러와서 뿌려주기 (0) | 2024.03.25 |
[Project] 공공데이터 공통표준용어 검색 만들기 - 화면 만들어보기 #2 기본 화면 그려보기 (0) | 2024.03.25 |
[Project] 공공데이터 공통표준용어 검색 만들기 - 화면 만들어보기 #1 WebStorm NextJs 설정 (0) | 2024.03.25 |
[Project] 공공데이터 공통표준용어 검색 만들기 - fastapi 엑셀 파일 불러와서 뿌려주기 #4 - 검색 (0) | 2024.03.19 |
※ 이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 관리자
- Webpack
- PostgreSQL
- Docker
- gatsbyjs
- nodejs
- 스마트 컨트랙트
- NestJS
- github
- Ktor
- AI 자동화
- Next.js
- seo 최적화 10개
- CI/CD
- fastapi
- kotlin
- REACT
- 백엔드개발
- SEO최적화
- App Router
- nextJS
- 개발블로그
- rag
- SEO 최적화
- 프론트엔드
- LangChain
- llm
- Prisma
- 웹개발
- AI챗봇
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함
반응형