Flask서버 기초

BodeulMaNN·2023년 4월 5일
0

파이썬은 아무래도 사용하기 쉽게 만들어진 언어이기 때문에 서버활용하기는 어렵다.

보통 서버 연결 할때는 자바서버에 많이 연결된다.
DB는 보통 MySQL이나 OracleDB를 사용한다.

우리는 장고 or Flask 서버를 배운다.

공유기를 쓰지 않는 고정된 IP를 뽑아다가 꽂아주면 외부에서도 서버에 들어올 수 있다.

(보통 10만원정도 사용하면 고정된IP를 뽑을 수 있다.)

플라스크는 인터넷에 정보가 많이 있으니까 나중에 html태그코드를 쓸때 파일을 업로드 해서 불러오는법을

찾아보자.
(플라스크 html 찾아보면 바로 나옴)

#ip주소로 접속할 수 있는 url 주소를 dns로 바꾸어서 사람이 읽을 수 있는 도메인 이름으로 변환함.
DNS : Domain Name System

홈페이지 : 웹 사이트의 첫 화면
웹 사이트 : 그 회사의 사이트

박웅근 선생님 (리눅스 pipeline)

=============================== 플라스크 서버 오픈 ==================================
!pip install Flask
from flask import Flask

#자기 컴퓨터의 ip확인하기 : cmd:관리자권한 -> ipconfig / IPv4 주소 확인하기

app = Flask(name) (app이라는 객채를 먼저 생성 해주고.)
@app.route('/') (app객채에 대해 루트를 짜준다., '/' 뜻은 내 페이지의 시작점이다 라는걸 알려줌)

def hi(): (아무 함수나 출력 해주고)
return "hi, I'm Flask"
if name == 'main' : (러닝 해준다.)
app.run(host='127.0.0.1', port=5000) (127.0.0.1 은 그냥 내 컴터 아이피라는 뜻)

(ip주소의 3번째 자리가 다른사람과 똑같다면 다른 사람도 내 서버에 접속 할 수 있음.)
(같은 공유기의 와이파이를 쓰고 있다면 핸드폰에서도 내 서버주소를 치면 똑같이 서버에 접속할 수 있다.)

================================ 플라스크 디테일 리페어 =======================================
#get과 post의 차이는 url주소에 경로가 표시 되느냐 안되느냐의 차이이다.
(메이저 회사일 수록 get방식을 많이 사용한다. 집계에서 유리하다고 함.)
from flask import Flask
from flask import request (플라스크 서버안에서 get과 post를 가져오기 위한 임포트)

import sklearn (이건 전부 다 붓꽃 분류를 위한 ML 모듈 임포트)
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

app = Flask(name) (플라스크 서버를 구동할 수 있는 이름.)

def build_main_page(num): (서버 구동을 위한 main_page함수 세팅)
page = f'''

<html>
<head>

<title> 뭣이 중헌디?! </title>
</head>

<body>
<h1> iris 분류기 <h1>
<p>iris 분류 시스템 입니다.</p>
<a href = 'https://www.google.com'> 구글 ㄱㄱ </a><br>
<a href = 'http://127.0.0.1:5000/input'>		(서버 구동시 input 사이트로 이동할 수 있는 하이퍼링크)
새로 입고된 꽃의 치수를 입력하러 가요 </a>
</body>
</html>
'''
return page

def build_input_page(): (서버 구동을 위한 input_page함수 세팅)
page = '''

<html>
<head>
<style>		(꾸며주는 것 css)
body{background-color:#B2EBF4}
.input1{width:400px; height:47px; background-color:lightgreen; 	(input1 클래스를 꾸미겠다.)
border: 3px solid black; border-radius:5px;}
.input2{margin-left:130px; margin-top:20px; width:100px; height:40px; border-radius:5px;}
.form1{margin:40 0 0 40; font-style: oblique;}
</style>
</head>
<body>
ㅎㅇㅎㅇ<br>
지금 넣은 꽃 길이 cm단위로 잘 넣어봐바<br>
내 ml이 니꺼 품종 알려줄거임 ㅇㅇ<br>
끝나면 종류에 맞게 창고에 정리 해놔라<br>
<form action='http://127.0.0.1:5000/result' method='post' >
sepal_length(cm): <input type= 'text' name='sepal_length'></input><br>	(input은 웹사이트 내에서)
sepal_width(cm): <input type= 'text' name='sepal_width'></input><br>	(입력할 수 있는 공간생성)
petal_length(cm): <input type= 'text' name='petal_length'></input><br>
petal_width(cm) : <input type= 'text' name='petal_width'></input><br>
<input type= 'submit' value='ㄱㄱ'></input><br>		(submit은 제출버튼 / value는 제출버튼 이름)
</form>
</body>
</html>
'''

return page

def ML_iris_train(): (붓꽃 데이터 훈련을 위한 함수세팅)
iris = load_iris()
X = iris.data
y = iris.target

dt_model = DecisionTreeClassifier(max_depth = 3)
dt_model.fit(X,y)

return dt_model

def ML_iris_predict(model, in1,in2, in3, in4): (붓꽃 데이터 예측을 위한 함수세팅)
result = model.predict([[in1, in2, in3, in4]])
return result

def build_result_page():
if request.method == 'POST':
input_method = 'POST'
sepal_length = request.form['sepal_length'] (post방식으로 가져오겠다.)
sepal_width = request.form['sepal_width']
petal_length = request.form['petal_length']
petal_width = request.form['petal_width']

elif request.method == 'GET':
    input_method = 'GET'
    sepal_length = request.args.get('sepal_length') 		(get방식으로 가져오겠다.)
    sepal_width = request.args.get('sepal_width')
    petal_length = request.args.get('petal_length')
    petal_width = request.args.get('petal_width')
    
sepal_length = float(sepal_length)	(붓꽃데이터 예측을 위한 각데이터마다 실수 변환)
sepal_width = float(sepal_width)	
petal_length = float(petal_length)
petal_width = float(petal_width)

result = ML_iris_predict(dt_model, sepal_length, sepal_width, petal_length, petal_width)
#붓꽃 예측모델을 result에 저장.    

if result == 0:
    result = 'setosa'
    img_file_name = 'C:/Users/aischool/Desktop/YHaischool/jupyter/iris_setosa.jpg'
elif result == 1:
    result = 'versicolor'
    img_file_name = 'C:/Users/aischool/Desktop/YHaischool/jupyter/iris_versicolor.jpg'
elif result == 2:
    result = 'versicolor'
    img_file_name = 'C:/Users/aischool/Desktop/YHaischool/jupyter/iris_virginica.jpg'
page = f'''			(포매팅)
<html>
<head></head>
<body>
    {input_method} 메세지가 들어왔어요.<br>
    첫 번째 입력은 {sepal_length} 이고,<br>
    두 번째 입력은 {sepal_width} 에요 <br>
    세 번째 입력은 {petal_length} 이고,<br>
    네 번째 입력은 {petal_width} 에요 <br>
    머신러닝 결과는 {result} 네요. {result}창고에 넣어두세요 <br>
</body>
</html>
'''
return page

dt_model = ML_iris_train() (붓꽃데이터로 훈련한 데이터를 dt_model에 저장.)

@app.route('/') (실질적으로 플라스크 서버를 돌아가게 해주는 데코레이터'@' ) /
def hi(): (변수 이름은 아무렇게나 생성, '/'는 홈페이지라는 뜻.)
#return "hi, I'm Flask"

page = build_main_page(100)		(위 함수 결과값 호출 후 page에 저장)
return page				(page 를 리턴)

@app.route('/input') (호스트 ip 서버에서 /input을 붙여주면 갈 수 있는 웹사이트)
def hi2():
page = build_input_page() (위 함수 결과값 호출 후 page에 저장)
return page (page 를 리턴)

@app.route('/result', methods=['POST', 'GET'])
def hi3():
#ML() 그동안 배운 ML결과를 보여줄 수 있게 마지막에 써줄 수 있음.
page = build_result_page() (위 함수 결과값 호출 후 page에 저장)
return page (page 를 리턴)

if name == 'main' : (플라스크 서버를 열어주는 host 서버 ip주소)
app.run(host='127.0.0.1', port=5000) (port는 5000이라는 값으로 열어주겠다는 의미)
ex. http://127.0.0.1:5000/ 을 하면 플라스크서버 홈페이지로 연결 됨.

=============================== 군집화 : 비지도 ===============================

profile
반갑습니다

0개의 댓글