Programmers/데브코스 인공지능

[프로그래머스 스쿨 AI] Weak 4 Flask

1. Flask

1. Flask

웹을 파이썬으로 구동해주는 서버역활을 해준다

사용법은 아래와 같다

하지만 동적이게 하려면 좀 여러가지 함수가 필요함으로 자바스크립트를 연동하였다

2. 삽질 영상

1. 일단 데이터를 보여주고 받을 웹을 만든다

 

2.flask와 데이터를 주고받을 수 있게편집한다

 

 

3. 데이터를 저장하기위해 DB를 이용한다

 

 

3. 코드

Folder─┬─ app.py
             ├─ templates ─── index.html
             └─ static ─┬─ css   ───   style.css
                               ├─ font   ───  DeathKnell.otf
                               ├─ script ─── flask.js
                               └─ index.html(블라켓용 실시간 웹디자인 보기)
                                 

1. app.py

from flask import Flask, render_template, Response, url_for, request, redirect
import mysql.connector

app = Flask(__name__)

''' DB 연동 '''

mydb = mysql.connector.connect(
    host = "localhost",
    user="root",
    passwd = "0000",
    database = "menu"
)
@app.route("/")
def home():

    return render_template("index.html")

@app.route("/menu")
def menu():
    my_cursor = mydb.cursor()
    my_cursor.execute("select * from menutbl;")
    data = my_cursor.fetchall()
    menus = []
    for i in data:
        menus.append({'id':i[0],'name':i[1],'price':i[2]})

    return render_template("index.html", menulist=menus)

@app.route("/menu",methods=['POST'])
def newmenu():
    my_cursor = mydb.cursor()
    sql = "insert into menutbl (dbname, dbprice) values (%s, %s);"
    my_cursor.execute(sql, (request.form['lname'],request.form['lprice']))
    mydb.commit()
    return redirect(url_for("menu"))

@app.route("/update",methods=['POST'])
def updatemenu():
    my_cursor = mydb.cursor()
    sql = "update menutbl set dbname = %s , dbprice = %s where id = %s ;"
    my_cursor.execute(sql,(request.form['lname'],request.form['lprice'],request.form['lid']))
    mydb.commit()
    return redirect(url_for("menu"))

@app.route("/delet",methods=['POST'])
def delmenu():
    my_cursor = mydb.cursor()
    sql = "DELETE FROM menutbl WHERE id = %s"
    adr = (request.form['lid'], )
    my_cursor.execute(sql,adr)
    mydb.commit()
    numset()
    return redirect(url_for("menu"))


def numset():
    my_cursor = mydb.cursor()
    sql = "ALTER TABLE menutbl AUTO_INCREMENT=1;"
    my_cursor.execute(sql)
    sql = "SET @count=0;"
    my_cursor.execute(sql)
    sql = "UPDATE menutbl SET id=@count:=@count+1;"
    my_cursor.execute(sql)
    mydb.commit()

if __name__ == "__main__":
    app.run()


'''  bd 없을때
menus = [{"id":1, "name":"caffee" ,"price":10000},
    {"id":2, "name":"latte" ,"price":12000},
    {"id":3, "name":"banana" ,"price":10000}
]


menus 
@app.route("/")
def home():
    return render_template("index.html")

@app.route("/menu")
def menu():

    return render_template("index.html", menulist=menus)

@app.route("/menu",methods=['POST'])
def newmenu():
    new = {
        "id":request.form['lid'],
        "name":request.form['lname'],
        "price" : request.form['lprice']
    }
    
    menus.append(new)
    return redirect(url_for("menu"))

@app.route("/update",methods=['POST'])
def updatemenu():
    new = {
        "id":request.form['lid'],
        "name":request.form['lname'],
        "price" : request.form['lprice']
    }
    menus[int(request.form['lid'])-1] = new

    return redirect(url_for("menu"))

@app.route("/delet",methods=['POST'])
def delmenu():
    del menus[int(request.form['lid'])-1]
    numset()
    return redirect(url_for("menu"))

def numset():
    for num, i in enumerate(menus):
        i['id'] = num+1
    

if __name__ == "__main__":
    app.run()
'''

2. templates/css/style.css

@charset "UTF-8";

/* font */

@font-face {
    font-family: knell;
    src: url('../font/DeathKnell.otf')
}


/* header */
body {background-color: black; color:white}

div.header {font-family:'knell';font-size: 40px; text-align: center; border-bottom: 3px solid white; border-radius: 10px}

/* menulist */
.box {margin-top: 30px}
.box .listview {margin: 10px; border: 1px solid; padding: 10px ;float: left;width: 65%}
.box .listview table {text-align: right; line-height: 1.5;width: 100%}
.box .listview table tr {cursor: pointer;transition: 1.s ease-in-out;}
.box .listview table tr:hover {background-color: rgba(255,255,255,10%)}
.box .listview table thead td{padding: 10px; font-weight: bold; vertical-align: top; color: azure;  border-bottom: 3px solid;background-color: rgba(255,255,255,25%); border-top-left-radius: 20px;border-top-right-radius: 4px}
.box .listview table tbody td {padding: 10px;border-bottom: 1px solid;}
.box .listview table tbody #check {background-color: rgba(255,255,255,25%)}
/* control */
.box .control {margin: 10px;float:right; width: 20%; padding-right: 20px}
.box .control .btn input {display: block; border: 1px solid white; width: 130px;height: 45px;font-size: 25px;background: black;color: white;border-radius: 40px;margin: 20px; transition: 1.0s ease, box-shadow 3.3s ease}
.box .control .btn input:hover {background-color: white; color: black;}

.box .control .clickdata {border: 1px solid;padding: 10px;border-radius: 10px; display: none}
.box .control .clickdata input {text-align: center;margin-bottom: 10px; border-radius: 10px; width: 90%; color: #333333}
.box .control .clickdata input#maker {display: block;width: 40%; border: 1px solid white;background: black;color: white;transition: 1.0s ease, box-shadow 3.3s ease;}
.box .control .clickdata input#maker:hover {background-color: white; color: black;}

4. static/index.html

var table = document.getElementById('table'),rIndex;
for (var i = 0; i < table.rows.length; i++)
{
    table.rows[i].onclick = function()
    {
        rIndex = this.rowIndex;
        console.log(rIndex);
        document.getElementById('lid').value =  rIndex;
        document.getElementById('lname').value = this.cells[1].innerHTML;
        document.getElementById('lprice').value = this.cells[2].innerHTML;
        if (document.getElementById('check')){
            document.getElementById('check').id = "uncheck";
        }
        this.id ="check";
    }
}
var checked = true;
var clickdata = document.getElementById('clickdata');
function clickTrEvent(trObj) {
    if (trObj.id == "view"){
        clickdata.style.display = 'none';
        document.menus.submit();
    }
    if (trObj.id == "create"){
        checked = true;
        clickdata.style.display = 'block';
        document.getElementById('lid').value =  table.rows.length;
        document.getElementById('lname').value = "";
        document.getElementById('lprice').value = "";
    }
    if (trObj.id == "update"){
        checked = false;
        clickdata.style.display = 'block';
    }
    if (trObj.id == "delet"){
        clickdata.style.display = 'none';
        if (rIndex){
            document.sub1.action = "/delet";
            document.sub1.submit();
        }
    }
    if (trObj.id == "maker"){
        if (document.getElementById('lname').value == ""){
            alert('name을 입력해주세요');
        }
        else if (document.getElementById('lprice').value == ""){
            alert('price를 입력해주세요');
        }
        else{
            if (checked){
                document.sub1.action = "";
                document.sub1.submit();
            }else{
                document.sub1.action = "/update";
                document.sub1.submit();
            }
                
        }
    }
}

4. static/font/Deathknell

www.wfonts.com/font/death-knell

파일명 띠어쓰기 없에 주세여

 

Download Free Font Death Knell

Download free font Death Knell by Chequered Ink from category Brush

www.wfonts.com

 

 

5. templates/index.html

<!DOCTYPE html>
<meta charset="ko">
<html>

<head>
    <title>Flask</title>
    <link rel="stylesheet" href="./css/style.css">
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script defer type="text/javascript" src="script/flask.js"></script>
</head>

<body>
    <input type="button" id="hw" value="Hello world" />
    
    
    <div class="header">
        <p>Flask</p>
    </div>
    
    <div class="box">
        <div class="listview">
            <table id="table" >
                <thead>
                <tr id='cols'>
                    <td id='td1'>id</td>
                    <td id='td2'>name</td>
                    <td id='td3'>price</td>
                </tr>
                </thead>
                <tbody>
                {% for i in menulist %}
                <tr id="uncheck" onclick="javascript:clickTrEvent(this)">
                    <td >{{i['id']}}</td>
                    <td>{{i['name']}}</td>
                    <td id="price">{{i['price']}}</td>
                </tr>        
                {% endfor %}
                <tr id="check" onclick="javascript:clickTrEvent(this)">
                    <td>2</td>
                    <td>caffelatte</td>
                    <td id= "price">120000</td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="control">
            <div class="btn">
                <input type="button" id="view" value="보기" onclick="javascript:clickTrEvent(this)" >
                <input type="button" id="create" value="추가" onclick="javascript:clickTrEvent(this)">
                <input type="button" id="update" value="편집" onclick="javascript:clickTrEvent(this)">
                <input type="button" id="delet" value="삭제" onclick="javascript:clickTrEvent(this)">
            </div>
            <form name="sub1" method="post">
            <div class="clickdata" id="clickdata">
                name : <input type="text" name="lname" id='lname'><br>
                price : <input type="text" name="lprice" id='lprice'>
                <input type="button" id="maker" name="maker" value="확인" onclick="javascript:clickTrEvent(this)">
            </div>
            </form>
        </div>
    </div>
    
</body>
</html>