언어/Python
[FastAPI]client-server 데이터 주고받기 && 422 에러
개발자국S2
2022. 12. 28. 15:41
이 둘은 한 프로젝트 안에 있다
RestClient
import requests
import json
class RestClient:
def restapi_post(self, url, body):
try:
headers = {'Content-Type': 'application/json', 'charset': 'UTF-8', 'Accept': '*/*'}
response = requests.post(url, headers=headers, data=json.dumps(body, ensure_ascii=False, indent="\t", default=str))
return response
except Exception as err:
raise
def restapi_get(self, url):
try:
headers = {'Content-Type': 'application/json', 'charset': 'UTF-8', 'Accept': '*/*'}
response = requests.get(url, headers=headers, allow_redirects=True)
return response
except Exception as err:
raise
requests를 사용해서 서버로 데이터를 보내준다.
두개의 메소드를 만들어놨지만, post로 보낼것.
data는 json.dumps형식을 통해 json으로 넘어간다.
Client
from common.RestClient import RestClient
if __name__ == '__main__':
hello = {"param": "hello","param2":"goodbye"}
rc = RestClient()
rc.restapi_post('http://127.0.0.1:8000/test', hello)
보내줄 데이터 : hello
필요한 파라미터 : url주소, 보내줄 데이터
아예 다른 프로젝트에서 API 구성
Server
from fastapi import FastAPI, requests
from pydantic import BaseModel
from fastapi.encoders import jsonable_encoder
app = FastAPI()
class MonitorRequest(BaseModel):
param:str
param2:str
@app.post("/monitor_info")
def post_monitor_info(mr: MonitorRequest):
result = jsonable_encoder(mr)
print(result)
return result
이게 매우 민감하다.
422에러를 잡으려고 하루종일 시간을 썼는데, 결국에는 오타때문이었다.
넘겨줄 class에 선언한 변수명, type, 순서를 반드시 잘 확인해야한다.
422에러는 보통 데이터의 형태가 맞지 않는 경우에 나는 에러인데,
json이 문제인가싶어 jsonable_encoder()를 사용했었다.
*저거 빼도 오타를 고치니 잘 돌아간다.
print(type(data['monitor_id']), type(data['hostname']), type(data['interface_id']), type(data['process_cnt']),
type(data['process_starttime']), type(data['process_endtime']), type(data['process_elapsed_time']))
타입하나하나 확인하니 함수하나를 변경하면서 none으로 리턴되는 값이 있었다.
서버에서는 str이 올것을 기대했는데, Nonetype이 가면서 오류가 나는것이었음.
임시적으로 str(해당값)으로 변경하니 200이 떴다.
반응형