Python, Flask, PostgreSQLで画面作成(2)
21/03/22
しばらく放置してしまったので、最初からやり直した。 目的はFlaskでPostgreSQLの内容を画面に表示すること。 実質4時間ほどで完成。
■ 参考URL
python postgreSQLのライブラリpsycopg2の使い方メモ - Qiita
- postgreSQLに対象のテーブルを作成
id:number title:string body:string
準備 venvを作成しておく
Flask、psycopg2インストール
pip install Flask pip install psycopg2
- PycharmでFlaskを動作させる設定
FLASK_APP=main.py FLASK_DEBUG=1 flask run
- PycharmでFlaskを動作させる設定
FLASK_APP=main.py FLASK_DEBUG=1 flask run
- main.pyを作成する。
from flask import Flask, render_template
import psycopg2, psycopg2.extras
app = Flask(__name__)
def get_connection():
# postgreSQLに接続(接続情報は環境変数、PG_XXX)
connection = psycopg2.connect( \
host='localhost', \
user='flask', \
password='flask', \
database='flask', \
port=int('5432'))
# クライアントプログラムのエンコードを設定(DBの文字コードから自動変換してくれる)
connection.set_client_encoding('utf-8')
# select結果を辞書形式で取得するように設定
connection.cursor_factory = psycopg2.extras.DictCursor
return connection
@app.route('/')
def main():
conn = get_connection()
cur = conn.cursor()
sql = 'SELECT * FROM entry'
cur.execute(sql)
# 引数ありの場合
#sql = 'SELECT * FROM entry where id = %(target_id)s'
#cur.execute(sql, {'target_id': (target_id,)})
members = cur.fetchall()
cur.close()
conn.close()
return render_template('dbtest.html', title='flask test', members=members)
## おまじない
if __name__ == "__main__":
app.run(debug=True)
templatesフォルダを作成する。
templates/layout.htmlを作成する。
templates/dbtest.htmlを作成する。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% block content %}
<!-- ここにメインコンテンツを書く -->
{% endblock %}
</body>
</html>
{% extends "layout.html" %}
{% block content %}
<h3>DbTest</h3>
<ul>
{% for member in members %}
<li>{{ member.title }} : {{ member.body }}</li>
{% endfor %}
</ul>
{% endblock %}