Flask

[Flask] request, jinja2 template를 이용한 python Dictionary collection

땅콩새싹 2020. 9. 26. 15:48
반응형

request, jinja2 template를 이용한 python Dictionary collection

 


 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from flask import Flask, render_template, request
app = Flask(__name__)
 
@app.route('/')
def student():
   return render_template('student.html')
 
@app.route('/result',methods = ['POST''GET'])
def result():
   if request.method == 'POST':
      result = request.form
      return render_template("result.html",result = result)
 
if __name__ == '__main__':
   app.run(host = '0.0.0.0', port= 80, debug = True)

<app.py>

이번에는 student.html을 이용해 학생의 물리, 화학, 수학 점수를 입력받고

POST방식으로 전송한 후 result.html에서 jinja2 templates를 이용해 

python Dictionary(dict) collection을 통해 성적을 표로 출력해 보겠습니다.

 

위의 app.py에서 localhost로 접속을 하게 되면 student.html을 불러옵니다.

1
2
3
4
5
6
7
8
9
10
11
<html>
   <body>
      <form action = "http://localhost/result" method = "POST">
         <p>이름 <input type = "text" name = "name" /></p>
         <p>물리 <input type = "text" name = "Physics" /></p>
         <p>화학 <input type = "text" name = "chemistry" /></p>
         <p>수학 <input type ="text" name = "Mathematics" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
   </body>
</html>

<student.html>

<localhost(student.html)>

 

위에 정보를 입력하고 submit버튼을 누르면 POST형식으로 http://localhost/result로 넘어가게 됩니다.

이제 다시 app.py로 돌아가 result()함수 부분을 봅니다.

POST형식으로 result로 전송을 했기 때문에 request.form을 이용해 넘어온 정보를

result에 저장합니다. 그리고 render_templats를 이용해 result에 저장된 정보들을

result.html로 넘기게 됩니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
<!doctype html>
<html>
   <body>
      <table border = 1>
         {% for key, value in result.items() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html>

<result.html>

여기서 jinja2 templates이 사용되는데 jinja2에 대해 간단히 설명하면

웹 템플릿 엔진을 사용하게 되면 html코드 안에서 연산작업을 수행 할 수 있고

jinja2 템플릿 같은 경우에는 html코드 안에서 python 코드를 사용할 수 있도록

기능을 제공해 웹페이지를 더 풍성하게 만들 수 있게 도와주는 엔진입니다.

jinja의 기본적인 문법은 {{변수명}}, {%python 소스코드%}처럼 사용할 수 있습니다.

result.html에서 보면 jinja2를 이용해 python Dictionary를 통해

key값과 value값을 전달받고 table로 만들고 있습니다.

 

값 입력

 

결과 화면

 

반응형