flaskでcssを使いたい

cssファイルはtemplatesフォルダ配下には作らない
↓これはダメ
$ tree
.
├── app.py
└── templates
├── css
│   └── style.css
└── index.html

staticというフォルダを作り、その中にcssファイルを入れる
$ tree
.
├── app.py
├── static
│   └── style.css
└── templates
└── index.html

templateからは以下で読み込む

	<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" type="text/css">

flask JSONを返却する

jsonifyを使用する

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
app.config['JSON_SORT_KEYS'] = False

@app.route('/hello')
def hello():
	data = [
		{"name": "山田"},
		{"age": 30}
	]
	return jsonify({
			'status' : 'OK',
			'data' : data
		})

if __name__ == "__main__":
	app.run(debug=True, host='192.168.56.10', port=8000)

flask formからPOST

formを受け取る側はmethodsを指定する必要あり

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/form')
def form(name=None):
	return render_template('post.html')

@app.route('/hello', methods=["POST"])
def hello():
	if request.method == 'POST':
		name = request.form['name']
	else:
		name = 'no name.'

	return render_template('hello.html', title='flask test', name=name)

if __name__ == "__main__":
	app.run(debug=True, host='192.168.56.10', port=8000)

queryをgetで取得する場合
=> request.args.getで取得する
http://192.168.56.10:8000/hello?name=yoko

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/hello')
def hello():
	name = request.args.get('name')

	return render_template('hello.html', title='flask test', name=name)

if __name__ == "__main__":
	app.run(debug=True, host='192.168.56.10', port=8000)

flask パラメータとルーティング

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/hello/<name>')
def hello(name=None):

	return render_template('hello.html', title='flask test', name=name)

if __name__ == "__main__":
	app.run(debug=True, host='192.168.56.10', port=8000)

flask データベース利用

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 %}

flask テンプレートの利用

templates/layout.html

<!doctype html>
<html>
<head>
	<title>{{ title }}</title>
</head>
<body>
	{% block content %}
	{% endblock %}
</body>
</html>

templates/hello.html

{% extends "layout.html" %}
{% block content %}
<h3></h3>
こんにちは。{{ name }}さん。
{% endblock %}

hello.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello():
	name = "Hoge"
	return render_template('hello.html', title='flask test', name=name)

if __name__ == "__main__":
	app.run(debug=True, host='192.168.56.10', port=8000)

flask入門

$ flask –version
Python 3.8.10
Flask 2.0.2
Werkzeug 2.0.2

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
	return '<html><body><h1>sample</h1></body></html>'

if __name__ == '__main__':
	app.run(debug=True, host='192.168.33.10', port=8000)

template/index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
            integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
            integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
            crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
            integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
            crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type=text/css href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
	<header>
		<div class="navbar navbar-dark bg-dark box-shadow">
            <div class="container d-flex justify-content-between">
                <a href="/" class="navbar-brand d-flex align-items-center">
                    <strong>サンプル</strong>
                </a>
            </div>
        </div>
	</header>
	<div class="content container">
		<h2>値の表示</h2>
        <p>値1:{{ values.val1 }}</p>
        <p>値2:{{ values.val2 }}</p>
	</div>
</body>
</html>

app.py

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
	values = {"val1": 100, "val2": 200}
	return render_template("index.html", values=values)

if __name__ == '__main__':
	app.run(debug=True, host='192.168.33.10', port=8000)