HTTP์ ์์ฒญ๊ณผ ์๋ต์ ๊ฐ๋จํ ์์ ๋ก ํ์ด๋ณด์๋ค.
from flask import request
get_number = request.form.get('get_number')
* request
- HTTP์ Method (GET POST)๋ฅผ ํตํด ๋ค์ด์ค๋ ์์ฒญ์ request๋ผ๋ ์ ์ญ๋ณ์์ ์ ์ฅ๋๋ค.
- ์ด๋ request.form.get('html์ name์์ฑ') ์ ํตํด ๊ฐ์ ์ป์ ์ ์๋ค.
- request๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด import๊ฐ ํ์ํ๋ค.
ํ์ด์ฌ์์ ๊ฐ์ ์ฒ๋ฆฌํ๋ค, ๋ค์ templates์ผ๋ก ๋ณด๋ผ๋๋
return render_template('index.html'
, number1=number1)
์ด๋ฌํ ํ์์ผ๋ก ๋๊ฒจ์ฃผ๋ฉด ๋๋ค. ์๋ฅผ๋ค์ด number1์ด๋ผ๋ ๋ณ์๋ HTML์์ {{number1}} ๋ก ์ฌ์ฉํ๋ฉด ๋๋ค.
*app.py
from flask import Flask, render_template, request
from random import randint
app = Flask(__name__)
correct = []
i = 0
o_cnt, x_cnt = 0,0
@app.route('/', methods=["POST","GET"])
def postTest():
number1,number2 = randint(0,10),randint(0,100)
msg = "๋ฌธ์ ์์"
global correct , i , o_cnt , x_cnt
correct.append(number1+number2)
get_number = request.form.get('get_number')
if request.method == "POST":
if int(get_number) == correct[i]:
msg = "์ ๋ต์
๋๋ค."
o_cnt += 1
else :
x_cnt -= 1
msg = "๋ก ! ์ ๋ต์ %d์
๋๋ค."%correct[i]
i+=1
return render_template('index.html'
, number1=number1 ,number2=number2
,msg=msg
,o_cnt = o_cnt
,x_cnt = x_cnt)
if __name__ == "__main__" :
app.run(host = '127.0.0.1', port = 5000 , debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col">
<h1>Flask_simle example</h1><br><br><br>
</div></div></div>
<div class="container">
<div class="row">
<div class="col">
<form method="POST">
<h2>Q. {{number1}} + {{number2}} = ?</h2>
<input type="text" name="get_number">
<button type="submit" class="btn btn-primary">์ ์ถ</button>
<br><br><br>
{% if msg %}
<script> alert("{{msg}}")</script>
{% endif %}
<div class="alert alert-primary" role="alert">
๋ง์ ๋ฌธ์ : {{o_cnt}}
</div>
<div class="alert alert-danger" role="alert">
ํ๋ฆฐ ๋ฌธ์ : {{x_cnt}}
</div>
</form></div></div></div>
</body>
</html>