0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flask】PostgreSQLを導入してデータの保存を可能にしよう!(Windows)

Posted at

1. 概要

この記事では、FlaskでWebアプリを開発するために、バックエンドデータベースとしてPostgreSQLを導入する手順をまとめます。

2. PostgreSQLのインストーラーをダウンロード

1. 以下のリンクからインストールして下さい!

👉 https://www.enterprisedb.com/downloads/postgres-postgresql-downloads

2. Windows を選択

3. Download the installer をクリック

4. バージョン15.13 Windows x86-64 のインストーラーを選んでください!

次はPostgreSQLをインストールしていきます!

3. PostgreSQLをインストール

  1. インストール先はデフォルトでOK
  2. パスワード: postgres
  3. ポート番号はデフォルトの 5432
  4. StackBuilder:今回はキャンセルして下さい!

4. pgAdmin4 で DB & テーブルを作成

1. Add New Server をクリック

2. 名前を 「アプリ名」 にする(以降dbnameと記載)

3. Connection を記入する

  • Host name/address: localhost
  • Password: postgres
  • Save password をチェック

4. サーバーに接続

  1. 左メニュー「Servers > PostgreSQL 15」右クリック → Connect Server
  2. パスワードは postgres(初期設定)を入力

5. データベース「postgres」を確認

Servers > PostgreSQL 15 > Databases > (dbname) が表示されていればOK。

6. テーブル作成

  1. (dbname)SchemaspublicTables 右クリック → CreateTable



  2. 設定画面で以下を入力:
  • Name:(好きな名前)
  • 「Columns」タブに移動して以下を設定:

※ 自分が保存したいデータの分だけ追加してね!

7. pgAdminでテーブルにデータが入るか確認

  1. (作成したデーブル名) を右クリック → View/Edit DataAll Rows
  2. データ一覧画面が出る
  3. 最初は空欄でOK(あとでFlaskからINSERT)

5. ライブラリのインストール

コマンドプロンプト
pip install psycopg2-binary
pip install python-dotenv

6.app.pyの編集

1. DBと接続

app.py
from flask import g
import psycopg2
from dotenv import load_dotenv
import os
load_dotenv()

app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY")

# DB接続を取得(1リクエストごと)
def get_db():
    if 'conn' not in g:
        g.conn = psycopg2.connect(
            dbname=os.getenv("DB_NAME"),
            user=os.getenv("DB_USER"),
            password=os.getenv("DB_PASSWORD"),
            host=os.getenv("DB_HOST"),
            port=os.getenv("DB_PORT")
        )
    return g.conn

# リクエスト終了時に接続を閉じる
@app.teardown_appcontext
def close_connection(exception):
    conn = g.pop('conn', None)
    if conn is not None:
        conn.close()

2. .env ファイルを作成

app.pyと同じ階層に .env ファイルを作成し、以下のコードを記述してください。

.env
DB_NAME=(dbname) # ここだけ自分の作成した名前に変更してね
DB_USER=postgres
DB_PASSWORD=postgres
DB_HOST=localhost
DB_PORT=5432
SECRET_KEY=your-secret-key

3. gitignore ファイルを作成

app.pyと同じ階層に .gitignore ファイルを作成し、以下のコードを記述してください。

.gitignore
.env
__pycache__/
*.pyc

4. POST時にデータをINSERT

app.py
if request.method == "POST":
    値1 = request.form["フォームの名前1"]
    値2 = request.form["フォームの名前2"]

    # 処理

    try:
        conn = get_db()
        with conn.cursor() as cur:
            cur.execute("INSERT INTO 作成したテーブル名 (カラム1, カラム2) VALUES (%s, %s)", (値1, 値2))
            conn.commit()
    except Exception as e:
        conn.rollback()
        flash("データの保存に失敗しました。")

※カラムの個数分追加してね!

5. GET時にデータを取得

app.py
try:
    conn = get_db()
    with conn.cursor() as cur:
        cur.execute("SELECT * FROM 作成したテーブル名 ORDER BY created_at DESC")
        rows = cur.fetchall()
    if not rows:
        flash("データが存在しません。")
except Exception as e:
    flash("データの取得に失敗しました。")
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?