LoginSignup
0
3

More than 1 year has passed since last update.

(自分用)Flask_7(Flaskからデータベースを開く)

Last updated at Posted at 2020-06-22

項目

  1. Flaskからデータベースを開く
    (今日は疲れてるのでこれだけで)

1.Flaskからデータベースを開く

python
from flask import Flask, render_template
import pymysql
app = Flask(__name__)

def getConnection():
    return pymysql.connect(
        host='localhost',
        db='mydb',
        user='root',
        password='',
        charset='utf8',
        cursorclass=pymysql.cursors.DictCursor
    )

@app.route('/')
def select_sql():
    connection = getConnection()

    sql = "SELECT * FROM players"
    cursor = connection.cursor()
    cursor.execute(sql)
    players = cursor.fetchall()

    cursor.close()
    connection.close()

    return render_template('view.html', players = players)
  • python側に関しては基本的には今までの組み合わせ
  • 前回やったimport pymysqlでPython内でMySQLを使えるようにしている
  • def getConnection():return pymysql.connect()で、getConnection()を呼び出した時に、dbを呼び出す材料が手に入るようになっている
  • connection = getConnection()connectionに呼び出す情報を入れて
  • 下の幾つかは前回と同じ動き
  • そんでFlaskの手順でreturnに代入した変数を入れてhtml側でも使えるようにしている
view.html
{% for player in players %}
    <p>{{ player }}</p>
{% endfor %}
  • なんの変哲もないpy側から渡された変数をfor文で表示する儀式
  • これ入れればとりあえずOK

あとは普通にFlaskを起動すれば完了(一応下に起動のあれも載せておく)

ターミナルとか
$ cd <作業ディレクトリが入ってるフォルダ名とか>
$ FLASK_APP=<作業pyディレクトリ名> FLASK_ENV=development flask run

2.終わりに

  • かなり短い
  • SQLでデータ削除とかAWS本格的に借りて動かすのとかは明日(今日?)にお預け
0
3
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
3