LoginSignup
20
23

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-05-09

はじめに

こんにちは、Niohと申します。
現在中小企業にて経理を行っています。
そこでいつも遭遇する『何を』『どこに』頼んでいいかわからないという問題を解決するため、電話帳をWEBアプリとして作り、簡単に共有できるようにすることにしました。

『Googleスプレッドシートでええやないか』

と即言われました。確かにその通りです。
それでも実装するのはFlaskなどのモジュールの扱い方を知りたかったからです。

必要な機能

  1. Basic認証 →最低限実装したい
  2. 検索機能
  3. 登録機能
  4. 表示機能

以上の機能が必要なのかなと思いました。

しかし正直これじゃBasic認証のところで躓くこと必至でしたのでまずは使う流れに沿って部品を作っていきます。

  1. ログインする
  2. 表示される
  3. 検索する
  4. 登録する

プラットフォーム

pythonで作りたかったのでFlaskを使って作ります。

FlaskとはWEBアプリケーションフレームワークでPythonでWEBアプリを作るにはこれかDjangoというものを使うそうです。

ユーザー ⇔ 電話帳DB

の仲立ちとして

ユーザー ⇔ ホームページ ⇔ Python(Flask) ⇔ 電話帳DB

という風に機能してくれます。

インストールなどはコチラを見ればわかりやすいかと思いました。

helloworld.py

from flask import Flask
app = Flask(__name__) #初期化

@app.route(/) 
# ルーティング(例えばhttp://www.name.com/ で実行するアプリケーション
# http://www.name.com/self にて実行したい場合はこちらを
# @app.route(/self) に変更する

def hello_world():
   return "Hello World!"

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

これをターミナルで実行すればOK

 1.ログインについて

まずはflaskでBasic認証を参考にします。

pip install Flask-HTTPAuth

リンク先だと全部小文字になってますが大文字も混ざってるみたい。

意外?に簡単

ソースはこんな感じ

Basic_auth.py

from flask import Flask
from flask_httpauth import HTTPBasicAuth

app = Flask(__name__)
auth = HTTPBasicAuth() #authオブジェクトの作成

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 index():
    return "Hello, %s!" % auth.username()

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

こちらを若干改変して使います。

2.表示させる

DB⇔ブラウザを実装します。

まずはJinja2について
Jinja2はFlaskで使用するテンプレートエンジンです。HTMLの内部に記述し、
APPフォルダ内に『templates』フォルダを作成、そこにJinja2を用いて書いたHTMLを仕込みます。

---app.py
------|--templatesフォルダ
------|--templates.html

てな感じで用意してtemplates.htmlをいじる感じ。

ここは正直{% for ~~ %} ~~{% endfor %}だけ覚えときましょう。あとはネストしながら使いまわします。

つぎにDBについて
sqlite3のモジュールを使います。
コチラに関してはpython-izmを参考にさせていただきました。
SQLITEの使い方はDBonlineを参考にさせていただきました。

Sqliteの使い方はSQLITE BrowserでTable作った後はSELECT、INSERT UPDATE以外は最初は覚える必要ないと思いました。

適宜使えるようになっていこうかと思います。

sqlite3モジュールに関しても構文だけ覚えます。

sample.py

import sqlite3

conn = sqlite3.connect("【DB名とパス】")
cursor = conn.cursor()

cursor.execute("【SQL構文】")

conn.commit() #これで保存する select文の時は参照のみなのでつけなくてOK
cursor.close()
conn.close()

これがセット。
【コツ】
SQL構文の中に変数を入れるときは例えば【"select ? from tables",(タプル)】で変数を代入しますが、
変数が一つの時は(変数 ,)といった形式でたとえ1個だけの時もタプルを作らないと失敗します。

そんな感じでこんな感じで作りました。

app.py
#-*- coding:utf-8 -*-
#! usr/env/python

from flask import Flask,render_template
import csv
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("/")

def hello():
    return ("hello world")

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

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

    cursor.execute("select * from contacts ")
    contacts_data = cursor.fetchall() #リストで取り出す

    cursor.close()
    conn.close()
    return render_template("index.html",contacts = contacts_data)

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>ID</th>
            <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>

これでBasic認証と表示部分は実装できました。
続きはこちら↓

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

思ったこと

実際セキュリティ等のことはほとんどわからないのでわかる方どーかわかりやすくご教授願います。

20
23
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
20
23