MySQLにデータが入っています
mysql> select * from users;
+——–+———————-+
| number | name |
+——–+———————-+
| 2 | Achraf Hakimi |
| 4 | Manuel Ugarte |
| 5 | Marquinhos |
| 7 | Kylian Mbappé |
| 8 | Fabián Ruiz |
| 10 | Neymar |
| 11 | Marco Asensio |
| 14 | Juan Bernat |
| 18 | Renato Sanches |
| 99 | Gianluigi Donnarumma |
+——–+———————-+
10 rows in set (0.00 sec)
$ pip3 install PyMySQL
hello.py
from flask import Flask, render_template
import pymysql
app = Flask(__name__)
@app.route('/')
def hello():
db = pymysql.connect(
host='localhost',
user='hoge',
password='fuga',
db='test',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor,
)
cur = db.cursor()
sql = "select * from users"
cur.execute(sql)
users = cur.fetchall()
cur.close()
db.close()
return render_template('hello.html', title='flask test', users=users)
if __name__ == "__main__":
app.run(debug=True, host='192.168.56.10', port=8000)
templates/hello.html
{% extends "layout.html" %}
{% block content %}
<h3>一覧</h3>
<ul>
{% for user in users %}
<li>{{ user.number }} : {{ user.name }}</li>
{% endfor %}
</ul>
{% endblock %}