본문 바로가기

카테고리 없음

[머신러닝] Spring 과 연동하여 서비스 구현

 

 

 

 

 

Spring 과 연동하여 서비스 구현

 

 

Welcome to Python.org

The official home of the Python Programming Language

www.python.org

 

파이썬 설치

 

workspace 폴더 생성

 

 

vscode 로 workspace 접속

 

 

google 에 사이킷런 모델 저장 검색

▲ 모델을 생성한 뒤 서버를 종료시켰다 다시 실행시키면 모델을 다시 학습시켜야 하기 때문에 모델을 파일로 저장해둔 뒤 사용 ▲

 

 

vscode 에서 파이썬 extension 설치

 

vscode 에서 code runner extension 도 설치

 

 

cmd 로 workspace 경로로 이동하여 django 설치

▲ 위 설정은 local 환경에 설치 ▲

 

 


 

가상환경으로 설치하여 관리하는 방법

 

 

가상환경 폴더를 하나 생성해서 가상환경에서 관리할 수도 있다

 

가상환경을 활성화

 

 

가상환경 종료

 

 

가상환경 내에서 pip install 을 사용해 가상환경 별로 각각 다른 버전의 라이브러리를 설치하여 관리할 수 있다

 


 

 

test1 이름으로 django 프로젝트 하나 생성

 

생성 완료

 

 

프로젝트 파일안에 들어가서 migrate 를 진행한다 (필수)

 

 

django 서버 실행

 

 

서버 주소 확인

 

 

접속 확인

 

 

test 경로로 들어오면 views 라는 파일의 test 함수를 실행하겠다

 

 

views.py 파일 생성 및 test 함수 선언하여 콘솔에 출력

 

 

HttpResponse 사용하여 웹으로 출력 후 확인

 

 

서버 종료 후 djangorestframework 라이브러리 설치

 

 

다시 서버 구동

 

 

프로젝트 경로 내의 templates 라는 폴더에서 view 단을 관리할 것이다라고 선언

 

 

BASE_DIR 은 여기에 선언되어 있음 ( default 는 프로젝트 폴더 까지 경로 )

 

 

서버 폴더 바로 하위에 templates 폴더 생성 후 안에 ajax.html 생성

 

ajax 경로로 접속할 시 views.py 파일의 ajax 함수를 실행

 

 

ajax 함수를 선언.... render 를 import 하여 html 파일을 응답해준다

 

 

html 간단하게 작성 코드는 아래

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function get() {
  $.ajax({ url : "/result/", type : "GET",
    success : function(data) { $('#label').text(data.execute) } });
}
function post() {  $.ajax({ url : "/result/", type : "post",
    success : function(data) { $('#label').text(data.execute) } });
}
function put() {  $.ajax({ url : "/result/", type : "put",
    success : function(data) { $('#label').text(data.execute) } });
}
function del() {  $.ajax({ url : "/result/", type : "delete",
    success : function(data) { $('#label').text(data.execute) } });
}
</script>
<label id="label">button click</label><hr>
<button onclick="get()">GET</button> <button onclick="post()">POST</button>
<button onclick="put()">PUT</button> <button onclick="del()">DELETE</button>

 

 

result 경로로 접속 시 views.py 의 result 함수 실행

 

 

resframework 의 Response 와 api_view 를 import 하여 각각 get, post, put, delete 요청을 모두 result 함수로 처리하게 하고 요청 방식에 따라 로직을 구분하여 나눈다

 

 

코드 정삭적으로 실행되는 것 확인

 

 

경로 추가

 

 

test2 경로로 접속 시 실행될 함수 선언

 

 

spring 에서 jsp 파일에 코드를 작성

 

 

접속하면 에러가 뜨는데 이유는 서로 다른 서버에 데이터를 요청하게되면 에러가 발생함...!!!

 

이 에러를 해결해주기 위해선 라이브러리 설치가 필요하다

 

 

서로 다른 서버끼리 데이터 교환을 허용해주는 라이브러리인 django-cors-headers 설치

 

 

settings.py 에 접속하여 설치한 crosheaders 라이브러리를 설정해준다 >> 정상적으로 데이터가 전송된다

 

 

CORS(Cross-Origin Resource Sharing) : 서로 다른 서버들 끼리 데이터를 주고 받으려 할때 발생하는 오류

 

이제부터 데이터를 요청하고 응답하면 된다

 

대출이 가능한지 가능하지 않은지 확인하는 부분을 구현해볼 것임

 

pandas 설치

 

 

sklearn 설치 ( 사이킷런 )

 

bank 경로 추가

 

 

머신 코드 작성

 

 

test1 프로젝트 안에 있는 bank_analysis.py 파일을 import 하여 init() 으로 초기화하여 객체에 저장장

 

 

django 서버 재실행

 

 

이제 스프링 코드 작성

 

 

경로 작성

 

bank_form.jsp 작성 ( 코드 아래 참고 )

<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function test(){
    let form = {}
    //배열 형태로 만들어 준다[{name:day,value:값},{name:weather,value:값}...]
    let arr = $("#frm").serializeArray()
    for(i=0;i<arr.length;i++){
      form[arr[i].name]=arr[i].value
    }
    $.ajax({
      url : "http://localhost:8000/bank/", type:"GET",
      data: form , 
      contentType:"application/json;charset=utf-8",
      dataType:"json",
      success: function(data){
         console.log("전송 성공 : ", data);
         if( data.key == 0 )
            msg ="가입 가능성 있음"
         else
            msg ="가입 안합니다!!!!!"
         $("#result").html( msg )
      },error:function(){ 
         alert("문제 발생") 
      }
    })
}
</script>

</head>
<body>
   <h1>정기예금 가입 여부</h1>
   <b id="result">결과를 보여줍니다</b>
   <hr>
   <form id="frm">
      <input type="text" name="age" placeholder="사용자 나이 입력"><br>
      <input type="text" name="duration" placeholder="마지막 접촉 지속 시간(초)"><br>
      <input type="text" name="campaign"
         placeholder="마케팅 전화를 받은 수(몇번 통화 됐는지)"><br>
      <!-- 10일전 마지막 통화인지 20일전 마지막 통화인지를 수로 입력 -->
      <input type="text" name="pdays" placeholder="마지막으로 통화한 일 수"><br>
      <input type="text" name="previous" placeholder="가입 제의를 한 횟수"><br>
      <input type="button" onclick="test()" value="click">
   </form>
</body>
</html>

 

 

spring 서버 실행 후 경로 접속

 

 

접속 성공

 

 

spring 서버에서 데이터를 django 서버로 전송하여 데이터 처리 후 다시 spring 서버로 받아서 메세지 처리....

 

 

▼ 세부 코드 ▼

ml_test.zip
0.02MB
test_1.zip
0.02MB

 

ml_test : spring 파일

test_1 : vscode 파일 ( python )

728x90