Help us understand the problem. What is going on with this article?

Flaskとsqlite3で掲示板的なの

More than 1 year has passed since last update.

勉強のためにflaskとsqlite3を使って掲示板的なのを作ってみました。

以下の構文に変数を20個作って送信していますがlistをそのまま送ることができたらしいです

    text = ["hello","world"]
    #return name
    return render_template('index.html', title='flask test', text=text) #変更
<body>
  <h1>hello{{name[0]}}</h1>
</body>

使ったものは

・ Python(3.7.3)
・ Flask(1.1.1)
・ Sqlite3
・ html
・ css
・ Javascript
・ MacBook Catalina(10.15.1 Beta)

ファイル構成

Pythonserver/
 ├ mess2.db
 ├ app.py
 └ templates/
  └ index.html
  ├ 50moji.html
  ├ start.html
  ├ nokigou.html

データベースの中身

touch コマンドで普通にmess.dbを作れます

それから sqlite3 mess.db コマンドで開ます。
そしてデータベースを以下のコマンドで作ります。
CREATE TABLE usermess(id INTEGER PRIMARY KEY AUTOINCREMENT, name text, message text);
多分10個なかにデータを入れとかないと動かないと思います
以下のコマンドを十回繰り返してください
insert into usermess(name,message) values('hoge','huga');

使用方法

上のファイル構成にして
Python3 app.py
で実行すれば起動します。
起動したら
localhost:5000
にサイトでアクセスすればみれます。

start.html
<form action="/startbtn" method="POST">
    <input type="Submit" Value="始める">
</form>
app.py
from flask import Flask,render_template,request
from flask import *
import sqlite3

app = Flask(__name__)

@app.route('/startbtn', methods=['GET', 'POST'])
def createname():
    conn = sqlite3.connect('mess2.db')

    c = conn.cursor()

    c.execute("select name,message from usermess ORDER BY id DESC;")#select文

    messtuple = c.fetchall()#list型で挿入


    mess0 = str(messtuple[0][0])
    mess0_2 = str(messtuple[0][1])
    mess1 = str(messtuple[1][0])
    mess1_2 = str(messtuple[1][1])
    mess2 = str(messtuple[2][0])
    mess2_2 = str(messtuple[2][1])
    mess3 = str(messtuple[3][0])
    mess3_2 = str(messtuple[3][1])
    mess4 = str(messtuple[4][0])
    mess4_2 = str(messtuple[4][1])
    mess5 = str(messtuple[5][0])
    mess5_2 = str(messtuple[5][1])
    mess6 = str(messtuple[6][0])
    mess6_2 = str(messtuple[6][1])
    mess7 = str(messtuple[7][0])
    mess7_2 = str(messtuple[7][1])
    mess8 = str(messtuple[8][0])
    mess8_2 = str(messtuple[8][1])
    mess9 = str(messtuple[9][0])
    mess9_2 = str(messtuple[9][1])

    message = str(messtuple)#tupleをstrに変換

    # message = message.replace("0213124124382135794302857439025","'")
    # message = message.replace("0223124124382135794302857439025","(")

    conn.commit()

    conn.close()

    return render_template("index.html",messlist=message,mess0=mess0,mess0_2=mess0_2,mess1=mess1,mess1_2=mess1_2,mess2=mess2,mess2_2=mess2_2,mess3=mess3,mess3_2=mess3_2,mess4=mess4,mess4_2=mess4_2,mess5=mess5,mess5_2=mess5_2,mess6=mess6,mess6_2=mess6_2,mess7=mess7,mess7_2=mess7_2,mess8=mess8,mess8_2=mess8_2,mess9=mess9,mess9_2=mess9_2)


@app.route("/")
def main():
    return render_template("start.html")

@app.route('/btn', methods=['GET', 'POST'])
def test():
    if request.method == 'POST':

        conn = sqlite3.connect('mess2.db')

        c = conn.cursor()

        usertext = request.form["usertext"]
        username = request.form["username"]

        if "'" in usertext or "'" in username:
            return render_template("nokigou.html")



        usertextlen = len(usertext)
        usernamelen = len(username)

        if usertextlen > 50 or usernamelen > 50:
            return render_template("50moji.html")

        if usertextlen == 0 or usernamelen == 0:
            return render_template("50moji.html")

        # usertext = usertext.replace("'","0213124124382135794302857439025")#置換する
        # usertext = usertext.replace("(","0223124124382135794302857439025")

        # Insert a row of data
        c.execute("insert into usermess(name,message) values('%s','%s');"%(username,usertext))#insertする

        c.execute("select name,message from usermess ORDER BY id DESC;")#select文

        messtuple = c.fetchall()#list型で挿入

        mess0 = str(messtuple[0][0])
        mess0_2 = str(messtuple[0][1])
        mess1 = str(messtuple[1][0])
        mess1_2 = str(messtuple[1][1])
        mess2 = str(messtuple[2][0])
        mess2_2 = str(messtuple[2][1])
        mess3 = str(messtuple[3][0])
        mess3_2 = str(messtuple[3][1])
        mess4 = str(messtuple[4][0])
        mess4_2 = str(messtuple[4][1])
        mess5 = str(messtuple[5][0])
        mess5_2 = str(messtuple[5][1])
        mess6 = str(messtuple[6][0])
        mess6_2 = str(messtuple[6][1])
        mess7 = str(messtuple[7][0])
        mess7_2 = str(messtuple[7][1])
        mess8 = str(messtuple[8][0])
        mess8_2 = str(messtuple[8][1])
        mess9 = str(messtuple[9][0])
        mess9_2 = str(messtuple[9][1])


        message = str(messtuple)#listをstrに変換

        # message = message.replace("0213124124382135794302857439025","'")
        # message = message.replace("0223124124382135794302857439025","(")

        conn.commit()

        conn.close()

        return render_template("index.html",messlist=message,mess0=mess0,mess0_2=mess0_2,mess1=mess1,mess1_2=mess1_2,mess2=mess2,mess2_2=mess2_2,mess3=mess3,mess3_2=mess3_2,mess4=mess4,mess4_2=mess4_2,mess5=mess5,mess5_2=mess5_2,mess6=mess6,mess6_2=mess6_2,mess7=mess7,mess7_2=mess7_2,mess8=mess8,mess8_2=mess8_2,mess9=mess9,mess9_2=mess9_2)

@app.route('/reloadbtn', methods=['GET', 'POST'])
def reloadbtn():
    conn = sqlite3.connect('mess2.db')

    c = conn.cursor()

    c.execute("select name,message from usermess ORDER BY id DESC;")#select文

    messtuple = c.fetchall()#tuple型で挿入


    mess0 = str(messtuple[0][0])
    mess0_2 = str(messtuple[0][1])
    mess1 = str(messtuple[1][0])
    mess1_2 = str(messtuple[1][1])
    mess2 = str(messtuple[2][0])
    mess2_2 = str(messtuple[2][1])
    mess3 = str(messtuple[3][0])
    mess3_2 = str(messtuple[3][1])
    mess4 = str(messtuple[4][0])
    mess4_2 = str(messtuple[4][1])
    mess5 = str(messtuple[5][0])
    mess5_2 = str(messtuple[5][1])
    mess6 = str(messtuple[6][0])
    mess6_2 = str(messtuple[6][1])
    mess7 = str(messtuple[7][0])
    mess7_2 = str(messtuple[7][1])
    mess8 = str(messtuple[8][0])
    mess8_2 = str(messtuple[8][1])
    mess9 = str(messtuple[9][0])
    mess9_2 = str(messtuple[9][1])

    message = str(messtuple)#tupleをstrに変換

    # message = message.replace("0213124124382135794302857439025","'")
    # message = message.replace("0223124124382135794302857439025","(")

    #CREATE TABLE usermess(id INTEGER PRIMARY KEY AUTOINCREMENT, name text, message text);
    #insert into usermess(name,message) values('hoge','huga');

    conn.commit()

    conn.close()

    return render_template("index.html",messlist=message,mess0=mess0,mess0_2=mess0_2,mess1=mess1,mess1_2=mess1_2,mess2=mess2,mess2_2=mess2_2,mess3=mess3,mess3_2=mess3_2,mess4=mess4,mess4_2=mess4_2,mess5=mess5,mess5_2=mess5_2,mess6=mess6,mess6_2=mess6_2,mess7=mess7,mess7_2=mess7_2,mess8=mess8,mess8_2=mess8_2,mess9=mess9,mess9_2=mess9_2)

if __name__ == "__main__":
    app.run(debug=True,host='0.0.0.0', port=5000)#デフォルトだとlockalホスト意外でアクセスできないので

変数の移行が頭悪い

作り終わった後に知ったのですが変数20個も作らなくてもJSONで遅れるのでその方が楽です

index.html
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
            <form action="/btn" method="POST">
                <input id="input1" type="text" name="username" placeholder="名前" maxlength="100">
                <input id="input1" type="text" name="usertext" placeholder="メッセージを入力" maxlength="100">
                <input type="Submit" value="Submit">
            </form>
            <form action="/reloadbtn" method="POST">
                <input type="Submit" Value="更新">
            </form>
<div>
<div class="mess0">
    {{mess0}}<br>
    <p class="mess0_2">{{mess0_2}}</p>
</div>
<div class="mess1">
    {{mess1}}<br>
    <p class="mess_2">{{mess1_2}}</p>
</div>
<div class="mess2">
    {{mess2}}<br>
    <p class="mess_2">{{mess2_2}}</p>
</div>
<div class="mess3">
    {{mess3}}<br>
    <p class="mess_2">{{mess3_2}}</p>
</div>
<div class="mess4">
    {{mess4}}<br>
    <p class="mess_2">{{mess4_2}}</p>
</div>
<div class="mess5">
    {{mess5}}<br>
    <p class="mess_2">{{mess5_2}}</p>
</div>
<div class="mess6">
    {{mess6}}<br>
    <p class="mess_2">{{mess6_2}}</p>
</div>
<div class="mess7">
    {{mess7}}<br>
    <p class="mess_2">{{mess7_2}}</p>
    </div>
</div>
<div class="mess8">
    {{mess8}}<br>
    <p class="mess_2">{{mess8_2}}</p>
</div>
<div class="mess9">
    {{mess9}}<br>
    <p class="mess_2">{{mess9_2}}</p>
    </div>
</div>

<style>
    .mess0{
        margin : 30px ;
        padding : 20px ;
        border-bottom: solid 3px #87CEFA;
        background-color : rgb(233, 233, 233) ;       
    }
    .mess0_2{
        font-size: 20px;
    }
    .mess1{
        margin : 30px ;
        padding : 20px ;
        border-bottom: solid 3px #87CEFA;
        background-color : rgb(233, 233, 233) ;  
    }
    .mess1_2{
        font-size: 20px;
    }
    .mess2{
        margin : 30px ;
        padding : 20px ;
        border-bottom: solid 3px #87CEFA;
        background-color : rgb(233, 233, 233) ;        
    }
    .mess2_2{
        font-size: 20px;
    }
    .mess3{
        margin : 30px ;
        padding : 20px ;
        border-bottom: solid 3px #87CEFA;
        background-color : rgb(233, 233, 233) ;        
    }
    .mess3_2{
        font-size: 20px;
    }
    .mess4{
        margin : 30px ;
        padding : 20px ;
        border-bottom: solid 3px #87CEFA;
        background-color : rgb(233, 233, 233) ;    
    }.mess4_2{
        font-size: 20px;
    }
    .mess5{
        margin : 30px ;
        padding : 20px ;
        border-bottom: solid 3px #87CEFA;
        background-color : rgb(233, 233, 233) ;        
    }
    .mess5_2{
        font-size: 20px;
    }
    .mess6{
        margin : 30px ;
        padding : 20px ;
        border-bottom: solid 3px #87CEFA;
        background-color : rgb(233, 233, 233) ;        
    }
    .mess6_2{
        font-size: 20px;
    }
    .mess7{
        margin : 30px ;
        padding : 20px ;
        border-bottom: solid 3px #87CEFA;
        background-color : rgb(233, 233, 233) ;       
    }
    .mess7_2{
        font-size: 20px;
    }
    .mess8{
        margin : 30px ;
        padding : 20px ;
        border-bottom: solid 3px #87CEFA;
        background-color : rgb(233, 233, 233) ;        
    }
    .mess8_2{
        font-size: 20px;
    }
    .mess9{
        margin : 30px ;
        padding : 20px ;
        border-bottom: solid 3px #87CEFA;
        background-color : rgb(233, 233, 233) ;        
    }
    .mess9_2{
        font-size: 20px;
    }
    #input1:focus {
        border: 2px solid #ff9900; 
        z-index: 10;
        outline: 0;
    }
    #input1{
        width: 250px;
        height: 10em;
    }

</style>

                <!-- <p id="inhtml"></p>
                <script>
                    const messstr = "{{messlist}}"
                    const inhtmljs = document.getElementById("inhtml")
                    inhtmljs.innerHTML = messstr
                </script> -->
                <script type="text/javascript">
                    var if_ctrl = 0;
                    var if_r = 0;
                    function is_ctrl(pressKey){
                            if(pressKey==17){ //ctrl
                                    return 1;
                            } else if (navigator.userAgent.match(/macintosh/i)){
                                    if (pressKey == 224 && navigator.userAgent.match(/firefox/i)){
                                            return 1;
                                    } else if (pressKey == 91 || pressKey == 93){
                                            return 1;
                                    }
                            }
                            return 0;
                    }
                    function disable_reload(e){
                            if(navigator.userAgent.match(/msie/i) && window.event){
                                    window.event.returnValue=false;
                                    window.event.keyCode=0
                            } else
                            if (navigator.userAgent.match(/macintosh/i) || e.preventDefault){
                                    e.preventDefault();
                                    e.stopPropagation();
                            }
                            return false;
                    }
                    function catchkeydown(e){
                            var pressKey;
                            if (eval(e)){
                                    pressKey=e.keyCode;
                            } else {
                                    pressKey=event.keyCode;
                            }
                            if(is_ctrl(pressKey)==1){ //ctrl
                                    if_ctrl=1;
                                    if(if_r==1){return disable_reload(e);}
                            }
                            if(pressKey==82){ //r
                                    if_r=1;
                                    if(if_ctrl==1){return disable_reload(e);}
                            }
                            if(pressKey==116){ //f5
                                    if (navigator.userAgent.match(/safari/i) 
                                            && !navigator.userAgent.match(/chrome/i)){
                                            window.location="%_myname_%?n=%_n_%&i=%_i_%";
                                            return true;
                                    } else {
                                            return disable_reload(e);
                                    }
                            }
                    }
                    function catchkeyup(e){
                            var pressKey;
                            if (eval(e)){
                                    pressKey=e.keyCode;
                            } else {
                                    pressKey=event.keyCode;
                            }
                            if(is_ctrl(pressKey)==1){ //ctrl
                                    if_ctrl=0;
                                    if(if_r==1){return disable_reload(e);}
                            }
                            if(pressKey==82){ //r
                                    if_r=0;
                                    if(if_ctrl==1){return disable_reload(e);}
                            }
                            if(pressKey==116){ //f5
                                    if (navigator.userAgent.match(/safari/i) 
                                            && !navigator.userAgent.match(/chrome/i)){
                                            window.location="%_myname_%?n=%_n_%&i=%_i_%";
                                    } else {
                                            return disable_reload(e);
                                    }
                            }
                    }
                    document.onkeydown = catchkeydown;
                    document.onkeyup = catchkeyup;
                    </script>
    </body>
</html>
50moji.html
<h1>1文字以上50文字以内</h1>
nokigou.html
<h1>1文字以上50文字以内</h1>
Hiroyuki01234
高校二年生の初心者です。高校になってからプログラミングをはじめました。
nnn-school
IT×グローバル社会を生き抜く“創造力”を身につけ、世界で活躍する人材を育成する。
https://nnn.ed.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away