LoginSignup
1
4

More than 5 years have passed since last update.

flaskで電話帳用のWEBアプリを作ってみる その3

Last updated at Posted at 2017-05-13

flaskで電話帳用のWEBアプリを作ってみる その1
(SQLITEとの接続、Flaskで表示させる)
flaskで電話帳用のWEBアプリを作ってみる その2
(FlaskにおけるPOST,GETの扱い方)
flaskで電話帳用のWEBアプリを作ってみる その3
(登録フォームを追加)
flaskで電話帳用のWEBアプリを作ってみる その4
(検索フォームを追加)

前回まで

  • 表示部分
  • POSTメソッドの受け取り方

をそれぞれ学べたので次は登録です。
登録は受け取ったPOSTメソッドをタプルにしてSqliteに登録するだけなのでソースのみ貼り付けます。
app.py
sampledb.dbのスキーマ
index.html
form.html
のソースをそれぞれ貼ります。

また、表示をかっこよくするためにBootstrapを使用しています。
form.htmlは後でindex.htmlと合体させるためにボタンでの表示/非表示に対応させています。

SQliteのスキーマ

sampledb.db

CREATE TABLE `contacts` (
    `id`    INTEGER PRIMARY KEY AUTOINCREMENT,
    `name`  TEXT UNIQUE,
    `phone_num` TEXT UNIQUE,
    `Commentary`    TEXT,
    `yomigana`  TEXT
);

app.py

app.py
# -*- coding:utf-8 -*_

from flask import Flask,request,render_template,redirect,url_for
import sqlite3
from flask_httpauth import HTTPBasicAuth

app = Flask(__name__)
auth = HTTPBasicAuth()

users = {"john":"hello","susan":"bye"}

@auth.get_password
def get_pw(username):
    if username in users:
        return users.get(username)
    return None

@app.route("/")
@auth.login_required

def basicview():
    conn = sqlite3.connect("sampledb.db")
    cursor = conn.cursor()

    cursor.execute("select name,phone_num,Commentary from contacts order by yomigana")
    result = cursor.fetchall()

    cursor.close()
    conn.close()

    return render_template("index.html",contacts = result)

@app.route("/register")
def hello():
    return render_template("form.html")

@app.route("/add_entry" ,methods = ["POST"])

def add_ent():
    conn = sqlite3.connect("sampledb.db")
    cursor = conn.cursor()
    cursor.execute("insert into contacts (name,yomigana,phone_num,Commentary) values (?,?,?,?)",
                    (request.form["Name"],request.form["Kana"],request.form["Num"],request.form["Comm"]))

    conn.commit()
    cursor.close()
    conn.close()

    try:
        print(request.form["Name"])
    finally:

        return redirect(url_for("basicview"))

if __name__ == '__main__':
    app.run(debug = True)

レイアウト部分

index.html
<!DOCTYPE html>

<html lang="en">
  <head>
      <meta charset = "utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container">
      <div class="header">
        <h3 class="text-muted">電話帳</h3>
        <div class = "table-responsive">
        <table class = "table table-bordered table-hover">
          <tr>
            <th>Name</th>
            <th>Number</th>
            <th>Comment</th>
          </tr>
          {% for num in contacts %}
          <tr>
            {% for name in num %}
              <td>{{name}}</td>
            {% endfor %}
          </tr>
          {% endfor %}
        </table>
      </div>
      </div>
    </div>
  </body>
</html>

form.html
<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset = "utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
  </head>
  <body>
    <button type = "button" class = "btn btn-default" data-toggle ="collapse" data-target="#collapseSamp">
      登録
    </button>

    <div class = "collapse" id = "collapseSamp"
      <div class ="well">
        <form action = "{{url_for("add_ent")}}" method = "POST" class="form-inline">
          <input name = "Name" placeholder="名前">
          <input name = "Kana" placeholder="カナ">
          <input name = "Num" placeholder="電話番号">
          <input name = "Comm" placeholder="コメント">
          <input type ="submit" value = "送信">
        </form>
      </div>
    </div>
  </body>
</html>

思ったこと

  • Bootstrapはその都度ググってOKなのだろうか、覚えることが多すぎてヤバい
  • デコレータがわからない。やってるうちに覚えられるようになるのだろうか。

次回はform.htmlとindex.htmlを合体させ、検索のを行えるようにしたいと思います。

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4