Languages/python

[PYTHON] Flask(02) DB에서 데이터 받아와 html에 출력하기

뱅타 2021. 3. 23. 19:36

mysql(heidiDB)에서 받은 값들을 html에 출력하기

총 4개의 파일로 기획

.py 파일들

myheidi01.py

# 불러오기
import pymysql
import pandas as pd
import numpy as np

def getList(s_name):    
        
    gil_db = pymysql.connect(
        user='root', 
        passwd='python', 
        host='127.0.0.1', 
        db='python', 
        charset='utf8'
    )
    cursor = gil_db.cursor()
    
    #* 쓰는걸 지양하자. 파이썬 ;이 있거나 없거나 상관이 없다.
    sql = f"""
            SELECT s_code, s_name, s_price, in_date 
            FROM stock
            WHERE s_name = '{s_name}'
            """
    cursor.execute(sql)
    rows = cursor.fetchall()
    print(rows[2][2])
    
    # price = []
    list = []
    for row in rows:
        # price.append(row[2])
        list.append(row)
    
    gil_db.close()
    return list

if __name__ == '__main__':
    arr = getList("LG")
    arr = np.array(arr)
    print(arr)

myflask05stock.py

from flask import Flask, request
from flask import render_template
from day11.myheidi01 import getList

app = Flask(__name__)

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

@app.route('/list', methods =['get','post'])
def mylist():
    s_name = request.form["s_name"]
    list = getList(s_name)
    return render_template('stock.html', list = list, s_name = s_name)

if __name__ == '__main__':
    app.run(host="127.0.0.1", port='80')

HTML

index.html - 첫 화면

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="http://localhost/list" method = "post">
		<input name = 's_name' value = ""/><br/>
		<input type = "submit">
	</form>
</body>
</html>

stock.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
	.table{
		border-collapse : "collapse"
	}
	th {
		background-color : "lightgray"
	}
</style>
</head>
<body>
	<p>{{s_name}}의 주가변동</p>
	<table border = '' class = "table">
		<tr>
			<th>code</th>
			<th>name</th>
			<th>price</th>
			<th>date</th>
		<tr/>
			{% for item in list %}
		<tr>
				{% for i in item %}
			<td>
				<option>{{i}}</option>
			</td>
				{% endfor %}
		</tr>
			{% endfor %}
	</table>
</body>
</html>

출력 결과물

  1. 값 입력하기

2_1. 삼성전자 입력 시 결과 받기

2_2. LG 로 입력 시 결과

flask 이용 시 불편한 점

  • 서버를 껐다가 켜야지 수정한 것들이 반영된다.
  • 그래서 매번 수정 후 브라우저를 새로고침 하는것이 아니라 서버를 껐다가 켜주어야 한다.
728x90
반응형