LoginSignup
2
1

More than 5 years have passed since last update.

flaskでhello world的なことを

Last updated at Posted at 2018-09-16

はじめに

「Pythonでシフト作成ツールの作成」の連載の第1項です。

シフト作成ツールを作りつつ、pythonでのツール作成を学んでいきます。

1:flaskでhello world的なことを
2:pytestでflaskのテストを実施

flaskのチュートリアルを参考にユーザ情報をポストして擬似ログインするところまでを実装してhello world的な学習を。
flaskの基本的な使い方などを学ぶことを目的としています。

工程

ディレクトリ構成

まずプロジェクトのディレクトリを以下の様に作成。

├ test
├ work scheduler
 ├ __init__.py
 ├ login.py
 ├ static
   ├ css
   └ js
 └ templates
   ├ layout.html
   └ login.html
├ README.md
├ requirements.txt
├ runserver.py
├ setup.cfg
└ setup.py

flaskではhtml関連をroot配下のtemplatesディレクトリに収納しておくことでrender_templateを呼び出した際に自動で探してくれる。
url_forでstaticを指定した際も同様にstaticディレクトリから読み込みを行ってくれる。

上記はあくまでデフォルトでの仕様なので、変更もできます。

view

login.html
{% extends "layout.html" %}
{% block body %}
<form method="post">
    <input type="text" name="login_id" required />
    <input type="password" name="password" required />
    <button type="submit">Login</button>
</form>
{% endblock %}

{% %}は式を記載でき、controllerから受け取った情報を処理したりできます。

上記はlayout.htmlとして定義しているhtmlを大枠として呼び出し、blockで埋め込みする箇所として確保されている領域にソースをインジェクションしている。今回はblockの箇所としてbodyを指定している。

layoutには基本的に常に表示しておくものを出しておけばいいと思います。バナーとかメニューとか...
あと私はscriptをbody内に入れたくなかったのでcssとかscriptを定義したりもしてます。

layout.htmlの方は以下の様にしてます。

layout.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        ...
    </head>
    <body>
        <nav>
            ...
        </nav>
        <div>
            {% for message in get_flashed_messages() %}
                <div class="flash">{{ message }}</div>
            {% endfor %}
            {% block body %}{% endblock %}
        </div>
    </body>
</html>

また、{{ }}で変数の表示も行えます。

layout.html内の{{ message }}はflaskの機能のflashにて吐き出したメッセージをget_flashed_messages()にて取得して表示してます。

変数を渡すにはrender_templateの際に変数を名前付き引数として渡せばその名称で辞書化されますので使用できます。

return render_template('hogehoge.html', variable1=variable, variable2='this is variable')といった感じです。
あとはこのポスト結果を受け取って判定処理を行えば取りあえず擬似ログインはできます。

controller

ここでアプリの設定や擬似ログイン処理を書いています。

__init__.py

from flask import Flask, render_template, request, url_for, redirect, session


app = Flask(__name__)
app.secret_key = 'hogehoge secrete key'


@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if request.form['login_id'] != 'admin' and request.form['password'] != 'pass':
            flash('Not logged in')
            return render_template('login.html')
        session['logged_in'] = True
        flash('You were logged in')
        return redirect(url_for('menu.html'))
    return render_template('login.html')

app.run(debug=True)

Flask(__name__)にてflaskのinstanceを作成しています。引数にmoduleのパッケージ名を指定するのでここでは__name__を渡しています。

app.secret_keysessionを使うために必要な値です。flashの際にも必要となります。
キーは適当に変更してください。

routeにてこの処理のトリガーになるurlを指定します。
今回は画面が他にないので / でログイン画面表示とログイン処理のトリガーを兼ねてます。

formで画面入力を取得して、ログインに失敗したらエラーメッセージを表示してます。

ログインに成功するとsessionにlogged_inキーをTrueにしてます。
ただ、menu.htmlが存在しないのでnot foundのエラーが出ますが。

取りあえずはこれでflaskのhello worldっぽいことができる様になります。

次項

今回のソースのテストを作ります。

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