본문 바로가기

HealRo Project

flask Rest API GET 매개변수

반응형

Spring Html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>나는</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>

<div class ="container">
	<div class ="row mt-4">
		<div class ="col-8">
			<label for ="text-input">자전거 이용률 예측 </label>
			<input class ="form-control" type ="text" id ="text-input">
		</div>
		<div class ="col-4">
			<button class ="btn btn-success btn-bg" id="btn"  >machine learning</button>
		</div>
	</div> 
</div>



</body>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="js/socket.js"></script>
</html>

 

 

Spring Sender

$(function(){ 
	$("#btn").click(function(){ 
		
		var data = {
				data : $('#text-input').val()
		}
		
		
		JSON.stringify(data);
		console.log(data);
		$.ajax({
	        type: "GET",
	        dataType: "jsonp",
	        data : data,
	        url: "http://localhost:5000/info",
	        success: function (data) {
	            console.log('data는'+data);
	        }
	    });
		}); 
	});
		

 

Python

 

pip install flask-restful 다운

from flask_restful import Resource, Api
from flask_restful import reqparse 

추가

parser 만들고, sender에서 보낸 json에서의 key이름으로 argument를 parsing 해서 parser에 add함.

parse에 저장되 있는 arg들로 부터 인자 값을 얻어옴.

 

인자로 받는 이름은 data object안에 있는 칼럼 이름이다.

var data = {
year : year,
hour : hour,
windspeed : windspeed,
humidity : humidity,
atemp : atemp,
temp : temp,
weather : weather,
workingday : workingday,
holiday : holiday,
season : season
}

같은 경우 year,hour,windspeed ,,,, 가 args안에 들어감

from functools import wraps
import json

from flask import Flask
from flask import redirect, request, current_app
from flask_jsonpify import jsonpify
from sklearn.ensemble import RandomForestRegressor

import pandas as pd
from flask_restful import Resource, Api
from flask_restful import reqparse



app = Flask(__name__)


@app.route('/', methods=['GET'])
def test():
    train = pd.read_csv("./train.csv")
    train["datetime"] = train["datetime"].astype("datetime64")
    print(train.dtypes)
    train["hour"] = train["datetime"].dt.hour
    train["year"] = train["datetime"].dt.year
    
    y = train["count"] 
    train = train.drop(["casual","registered","count","datetime"], 1)
    test = pd.read_csv("./test.csv")
    test["datetime"] = test["datetime"].astype("datetime64")
    test["hour"] = test["datetime"].dt.hour
    test["year"] = test["datetime"].dt.year
    test = test.drop("datetime",1)
    print(test)
    sub = pd.read_csv("./sampleSubmission.csv")
   
    
    rf = RandomForestRegressor()
    rf.fit(train,y)
    p = rf.predict(test)
    sub["count"] = p
     
    
    return jsonpify(test.head(1).to_json())
    
   

@app.route('/info',methods =['GET'])
def info():
    parser = reqparse.RequestParser()
    parser.add_argument('data', type=str)
    args = parser.parse_args()
     
    return jsonpify(args['data'])


if __name__ == '__main__': app.run()

반응형

'HealRo Project' 카테고리의 다른 글

자전거 이용률 예측 인공지능 개발  (0) 2020.01.24
RandomForest Regressor 성능 분석  (0) 2020.01.24
간단한 머신러닝 연동 테스트  (0) 2020.01.22
csv file eclipse 가져오기  (0) 2020.01.22
Cross Domain 해결  (0) 2020.01.21