LoginSignup
1
1

More than 1 year has passed since last update.

Flaskを開発サーバーで起動させてみた

Posted at

準備

flaskと、jinja2が必須となります。

# pip install flask
# pip install jinja2

基本構成

最低限の機能だけで動かすのであれば、以下の構成だけでよいです。

  • index.py : 裏処理プログラム、ルーティングを書いたり、色々な処理を書く
  • templates : HTMLテンプレートを保存するディレクトリ(名称変更不可)
  • index.html : HTMLテンプレートファイル
# tree
.
├── index.py
└── templates
    └── index.html

プログラムを書いてみる

設定したブックマークを表示させるだけのページを作成する。

index.py
from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
def index():
    site = {
        'title':'ブックマーク'
    }
    pages = [
        {
            'title':'Google',
            'url':'http://google.com'
        },
        {
            'title':'Yahoo!',
            'url':'http://www.yahoo.co.jp'
        },
    ]
    return render_template(
        'index.html',
        site = site,
        pages = pages,
    )

index.pyから引数として受け取ったsitepagesのデータは、
マスタッシュ構文を使って、{{ site.title }}のように呼び出すことができます。
テンプレートタグ{% if ~ %}や、{% for ~ %}を使って、HTMLテンプレート内で条件分岐させたり、ループ処理させたりすることができます。

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ site.title }}</title>
</head>
<body>
    <h1>{{ site.title }}</h1>
    {% if pages == [] %}
        <p>データがありません。</p>
    {% else %}
        <table border="1">
            <tr>
                <th>タイトル</th>
                <th>URL</th>
            </tr>
            {% for page in pages %}
                <tr>
                    <td>{{ page.title }}</td>
                    <td><a href="{{ page.url }}">{{ page.url }}</a></td>
                </tr>
            {% endfor %}
        </table>
    {% endif %}
</body>
</html>

開発サーバーを起動

事前準備

環境変数を設定します。

# export FLASK_APP=index

開発サーバーを起動する

以下のコマンドで開発サーバーを起動します。
特に何も指定しなければ、デフォルトで127.0.0.1:5000で起動するので、
localhostで動かしている場合は、http://127.0.0.1:5000でWEBサーバーに接続できます。

# flask run

アドレスやポートを指定して起動

コンテナで起動する場合など、アドレスやポート指定したい場合もあると思います。
以下のオプションを指定することで、任意のアドレス、ポート番号で起動することができます。
こちらは、0.0.0.0のアドレスで、80番ポートで起動させる例になります。

# flask run -h 0.0.0.0 -p 80

Pythonファイル内に記述して起動する

app.run()をPythonファイル内に記述して実行するという手段もあります。
python index.pyコマンドで、index.pyを実行すると、
0.0.0.0のアドレスで、80番ポートで起動します。

index.py
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=80, debug=True)
1
1
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
1
1