2
3

More than 1 year has passed since last update.

Flask入門②~htmlの扱い~

Last updated at Posted at 2021-12-09

はじめに

前回の続きで、今回はhtmlを扱います。
(どこまでできるかな)

環境

  • windows10
  • flask2.0.2
  • python3.8.10

コード内でのhtml設定

文字の大きさ変更

flask1.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return '<h1>Hello world</h1>' #メインタイトル

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

image.png
h1タグで設定したことで、文字が大きく表示されました。h3にすると小さくなったのがわかります。
image.png

装飾

色を変更してみた。

flask2.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask

app = Flask(__name__)

#色を指定
@app.route('/')
def index():
    return '<h1><font color="darkgreen">Python</font><br></h1>'

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

image.png

なんとなくpythonっぽい色(?)になりました。

htmlファイルの読み込み

pyファイルにhtmlタグを書き込むのはカスタマイズ性に欠けるので、htmlファイルから読み込む練習をしました。
下記のようなファイル階層にしています(templatesはこの名前にしないとエラーが発生する)。

directory/
|__flask3.py
|__templates/
      |__index.html

htmlファイル

今回の練習でhtmlを初めて扱いました。これも今後勉強が必要だなあ・・・

index.html
<!DOCTYPE html>
<html lang=”ja”>
<head>
<meta charset=”UTF-8″>
</head>
<body>
<title>Flask練習</title>

<span style="text-decoration: underline;"><font color="red"><h2>ショートケーキ</h2><font></span>

<p><font color="black">スポンジとクリームが層になり、上にイチゴが乗ったケーキを指すことが多いです。<br/>
ただし一般的な定義はないそうです。なのでこれがショートケーキだ主張すれば、何でも該当します(極端に言えば)
<font></p>

<span style="text-decoration: underline;"><font color="khaki"><h2>チーズケーキ</h2><font></span>

<p><font color="black">チーズを使ったケーキです。<br/>
チーズケーキは種類があり、スフレチーズケーキ、ベイクドチーズケーキ、レアチーズケーキに大別されます。<br/>
<font></p>

<span style="text-decoration: underline;"><font color="peru"><h2>ロールケーキ</h2><font></span>

<p><font color="black">スポンジ生地にクリームやフルーツを置いて巻いたものです。<br/>
スポンジの外側にクリームがあるもの、ないもの両方存在します。<br/>
<font></p>

</body>
</html>

flaskの利用

htmlファイルを読み込みます。

flask3.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html') #htmlファイルの表示

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

image.png

実行するとちゃんと項目ごとに色分けされて表示されました。

まとめ

  • htmlファイルを読み込んで表示できた。

次回は画像の読み込みを練習します。

2
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
2
3