LoginSignup
2
6

More than 3 years have passed since last update.

FlaskでPostgreSQLと連携した読書記録簿を作った

Posted at

はじめに

土日で勉強がてら、ちょっとした読書記録簿を作りました。
画面はこちら。
画面.png

機能としては、読んだ本を登録することと、登録された本のリストを見ることくらいです。

ソースコード

ソースコードは以下の通りです。htmlは見たままなので割愛します。

app.py
from flask import Flask, render_template,url_for,request,redirect
from sqlalchemy import create_engine
import pandas
import psycopg2

'''
参考にしたサイト
https://tanuhack.com/pandas-postgres-readto/

'''

# PostgreSQLの接続情報
connection_config = {
    'user': 'user',
    'password': 'password',
    'host': 'localhost',
    'port': '5432',
    'database': 'mydb'
}

# psycopg2を使ったDB接続
connection = psycopg2.connect(**connection_config)

# dfの作成
df = pandas.read_sql(sql='SELECT * FROM books;', con=connection) 
header = ['id','書籍名','著者','読了日','評価']
record = df.values.tolist() # DataFrameのインデックスを含まない全レコードの2次元配列のリスト

app = Flask(__name__)

@app.route('/')
def index():
    #indexを読み込むたびにDBからのSELECT文更新
    df = pandas.read_sql(sql='SELECT * FROM books;', con=connection) 
    record = df.values.tolist()
    return render_template('index.html',  header=header, record=record)

@app.route('/result', methods=['GET','POST'])
def addition():
    if request.method == "POST":
        # レコード数再取得が必要
        df = pandas.read_sql(sql='SELECT * FROM books;', con=connection) 
        record = df.values.tolist() 

        # POSTの内容を元にINSERT文の値取得、idは現在のレコード数+1
        book_id = len(record)+1
        res1 = request.form['書籍名']
        res2 = request.form['著者']
        res3 = request.form['読了日']
        res4 = request.form['評価']
        dict1={'id':[book_id],'name':[res1],'writer':[res2],'read_day':[res3],'rank':[res4]}

        # DBに飛ばすにはSQLAlchemy必要
        engine = create_engine('postgresql://{user}:{password}@{host}:{port}/{database}'.format(**connection_config))
        df = pandas.DataFrame(data=dict1)
        df.to_sql('books', con=engine, if_exists='append', index=False)
        return redirect(url_for('index'))

## おまじない
if __name__ == "__main__":
    app.run(debug=True)

概要としては、PostgreSQLに読んだ本のテーブルがあり、SELECT文でDataFrameとして取得した内容をリスト化し、render_templateでindex.htmlに送って「あなたが読んだ本」として表示させます。
そして、読んだ本の登録は入力フォームに情報を入力し、登録ボタンを押すことでPOSTメソッドとして処理されます。idは最新の番号を自動で割り振り、他は入力フォームから取得し、1行の辞書型のデータを作ります。
最後に、辞書型のデータをDataFrameに変換し、df.to_sqlでDBにINSERT文を飛ばせばデータが追加されます。

課題

・デプロイできなかった
 herokuを使おうとしたんですが、デプロイしたものがうまく起動せずに断念しました。
 原因ははっきりしていないのですが、生の環境でやったのが影響していそうだったので、virtualenvを使うべきだったと思います。

・機能不足
 ご覧の通り、データを追加する機能しかありません。登録情報を修正したり、消したかったらコマンドプロンプトで直接DBを見に行かなければいけません。

今後に向けて

とりあえず、最低限やりたかったDBとウェブページの連携(DBからの取得とDBへの追記)はできたので及第点にしちゃいます。
次は読書記録簿をリメイクするのか別のものを作るか決めていませんが、virtualenvをつかい、少しずつherokuにデプロイする、という作成スタイルでやりたいと思います。

2
6
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
2
6