検証環境

  • Python 3.10.8
  • Flask 2.2.2
  • Werkzeug 2.2.2

はじめに

FlaskはPythonのWebアプリケーションフレームワークであり、Djangoのようなフルスタックフレームワークと違い、軽量で簡単に実行できる。
今回は、Flaskを使用した簡単なWebアプリケーションを作成する。

pipでFlaskをインストールする

% pip3 install flask

バージョン確認

% python3 -m flask --version 
Python 3.10.8
Flask 2.2.2
Werkzeug 2.2.2

最小構成で実行してみる

ディレクトリ構成

% pwd
/work/flask-project
% ls
server.py

コード

# server.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello'

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

@app.route('/') でurlのパスとマッピングする。
上記では、index関数をルートurlとマッピングしている。

プログラム実行

% python3 server.py

上記のように実行し、localhost:8000 に接続すると、"Hello" と表示される。

htmlファイルを表示する

3章では、Webページに "Hello" という文字列を index 関数の戻り値として返すことで表示した。
では、実際のhtmlファイルを表示したいときはどうするか。
それは render_template 関数を戻り値にすることで実現できる。
htmlファイルは、templatesディレクトリに配置する必要がある (templates以外の名前だと動作しない) 。
また、render_template をインポートする必要がある。

ディレクトリ構成

% ls
__pycache__ server.py   templates

% ls templates
index.html

コード

# server.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8000)
<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
  <head>
  </head>
  <body>

    <h1>Hello from index.html</h1>

  </body>
</html>

実行画面

先ほどと同じように接続すると、以下のような画面が表示される。

CSSとJavaScriptを読み込む

ディレクトリ構成

以下の様な構成にし、staticディレクトリ配下にCSSファイルとJavaScriptファイルを配置する。
staticという名前でないと動作しない。

% ls
__pycache__ server.py   static      templates
% ls static
index.css   index.js

コード

CSSやJavaScriptを読み込むには、以下の様に{{ url_for() }} を使用する。

<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
  <head>
    <link rel="stylesheet" href="{{url_for('static', filename='index.css')}}">
    <script src="{{url_for('static', filename='index.js')}}"></script>
  </head>
  <body>

    <h1>Hello</h1>
    <h2 id='test'>World</h2>

  </body>
</html>
/* index.css */
h1 {
  color: red;
}
// index.js
window.onload = function() {
  var e = document.getElementById('test');

  e.style.color = 'blue';
}

実行画面

pythonの値をhtmlに埋め込む

Flask は Jinja2 というテンプレートエンジンを使用でき、htmlファイルに簡単にpythonの値を埋め込むことができる。

Jinja2インストール

pip3 install jinja2

コード

# server.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():

    s = "abc"
    lis = ["a1", "a2", "a3"]
    dic = {"name":"John", "age":24}
    bl = True

    return render_template('index.html', s=s, lis=lis, dic=dic, bl=bl)

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

render_template の第二引数以降に値を指定することで、値を渡すことが出来る。

<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
  <head>
  </head>
  <body>
    <p>{{ s }}</p>
    <hr>

    <ul>
    {% for x in lis %}
      <li>{{ x }}</li>
    {% endfor %}
    </ul>
    <hr>

    <p>{{ "name: %s age: %s" % (dic["name"], dic["age"]) }}</p>
    <hr>

    {% if bl %}
      <p>True</p>
    {% else %}
      <p>False</p>
    {% endif %}
  </body>
</html>

実行画面

GET/POSTで値を渡す

コード

以下の index.html ではボタンを二つ作成し、/test に get と post リクエストを投げられるようにしている。

<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
  <head>
  </head>
  <body>

    <form action="/test" method="get">
      <button name="get_value" value="from get">get submit</button>
    </form>

    <form action="/test" method="post">
      <button name="post_value" value="from post">post submit</button>
    </form>

  </body>
</html>

GET/POST で値を取得するには、request をインポートする。

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/test', methods=['GET', 'POST'])
def test():
    if request.method == 'GET':
        res = request.args.get('get_value')
    elif request.method == 'POST':
        res = request.form['post_value']

    return res

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

@app.route('/test', methods=['GET', 'POST'])
で GET と POST の受け取りを指定している。
GET だけ受け取るときは、methods=['GET'] のようにする。

また、get の値を取得するには、request.args.get 関数を、post の値を取得するには、request.form から取得出来る。

実行画面

index.html

get submit ボタンを押した時の画面

post submit ボタンを押した時の画面


0件のコメント

コメントを残す

アバタープレースホルダー

メールアドレスが公開されることはありません。 が付いている欄は必須項目です