9장 웹 애플리케이션에 머신 러닝 모델 내장

sua·2022년 5월 7일
0

머신러닝 교과서

목록 보기
9/12
post-thumbnail

9.3 플라스크 웹 애플리케이션 개발

플라스크 : 핵심 모듈은 가볍고 단순하지만 다른 라이브러리들과 연결하여 쉽게 확장할 수 있어 마이크로프레임워크라고 함


☑️플라스크 설치하기☑️

conda install flask

9.3.1 첫 번째 플라스크 애플리케이션

첫 번째 애플리케이션 - 이름만 입력하는 폼 필드 하나만 가진 간단한 웹 페이지

☑️디렉터리 구조 만들기☑️

  • app.py : 플라스크 웹 애플리케이션을 구동하기 위해 파이썬 인터프리터로 실행할 핵심 코드를 담고 있음
  • templates 디렉터리 : 플라스크가 웹 브라우저에 표시할 정적인 HTML을 찾는 장소
1st_flask_app_1/
	app.py
    templates/
    	first_app.html

☑️app.py 파일 내용 살펴보기☑️

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('first_app.html')

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

☑️first_app.html 파일 내용 살펴보기☑️

<!doctype html>
<html>
  <head>
    <title>첫 번째 애플리케이션</title>
  </head>
  <body>

  <div>
	와우, 첫 번째 플라스크 웹 애플리케이션입니다!
  </div>

  </body>
</html>

☑️로컬에서 웹 애플리케이션 실행하기☑️

python app.py

Running on http://127.0.0.1:5000/


9.3.2 폼 검증과 화면 출력

WTForms 라이브러리를 사용하여 폼 요소 추가하기

☑️WTForms 라이브러리 설치하기☑️

conda install wtforms

☑️디렉터리 구조 셋팅하기☑️

1st_flask_app_2/
	app.py
    static/
    	style.css
    templates/
    	_formhelpers.html
        first_app.html
        hello.html

☑️수정된 app.py 파일 내용 살펴보기☑️

from flask import Flask, render_template, request
from wtforms import Form, TextAreaField, validators

app = Flask(__name__)

class HelloForm(Form):
    sayhello = TextAreaField('',[validators.DataRequired()])

@app.route('/')
def index():
    form = HelloForm(request.form)
    return render_template('first_app.html', form=form)

@app.route('/hello', methods=['POST'])
def hello():
    form = HelloForm(request.form)
    if request.method == 'POST' and form.validate():
        name = request.form['sayhello']
        return render_template('hello.html', name=name)
    return render_template('first_app.html', form=form)

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

☑️진자2 템플릿 엔진을 사용하여 매크로 구현하기☑️

{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
  </dt>
{% endmacro %}

☑️CSS로 스타일 추가☑️

body {
	font-size: 2em;
}

[first_app.html]

<!doctype html>
<html>
  <head>
    <title>첫 번째 애플리케이션</title>
	<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
  </head>
  <body>

{% from "_formhelpers.html" import render_field %}

<div>이름을 입력해 주세요.</div>
<form method=post action="/hello">

  <dl>
	  {{ render_field(form.sayhello) }}
  </dl>

  <input type=submit value='이름 입력' name='submit_btn'>

</form>

  </body>
</html>

☑️결과 페이지 만들기☑️

<!doctype html>
<html>
  <head>
    <title>첫 번째 애플리케이션</title>
	<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
  </head>
  <body>

<div>{{ name }} 님 안녕하세요!</div>


  </body>
</html>

☑️로컬 서버 실행☑️

python app.py


profile
가보자고

0개의 댓글

관련 채용 정보