計算機科学のブログ

ほしい物リスト

Python - Building a Webapp: Web Development - Flask, HTML, Jinja

Head First Python: A Learner’s Guide to the Fundamentals of Python Programming, A Brain-Friendly GuidePaul Barry(著)、 O’Reilly Mediaの Chapter 7.(Building a Webapp: Web Development)、EXERCISE(75/124)の解答を求めてみる。

コード

webapp/app.py

import os

from flask import Flask, render_template, session

import swimclub

app = Flask(__name__)
app.secret_key = 'You will never guess'


@app.get('/')
def index():
    return render_template(
        'index.html.j2',
        title='Welcome to the Swimclub system',
    )


def populate_date():
    if 'swimmers' not in session:
        session['swimmers'] = {}
        filenames = os.listdir(swimclub.FOLDER)
        filenames.remove('.DS_Store')
        for filename in filenames:
            name, *_ = swimclub.read_swim_data(filename)
            if name not in session['swimmers']:
                session['swimmers'][name] = []
            session['swimmers'][name].append(name)


@app.get('/swimmers')
def display_swimmers():
    populate_date()
    return str(sorted(session['swimmers']))


@app.get('/files/<swimmer>')
def get_swimmers_file(swimmir):
    populate_date()
    return str(session['swimmers'][swimmir])


if __name__ == '__main__':
    app.run(debug=True)

拡張子はVisual Studio Codeがファイルを開いた時に認識してくれるように、本書の「html」ではなく「html.j2」に変更。

Jinja HTML

webapp/templates/base.html.j2

<html>

<head>
    <title>{{title}}</title>
</head>

<body>
    <h3>{{title}}</h3>
    {% block body%}
    {% endblock%}
</body>

</html>

webapp/templates/index.html.j2

{% extends 'base.html.j2' %}
{% block body %}
<p>
    This is the Coach's swimclub system.
    Begin by selecting a <a href="/swimmers">swimmer</a> to work with.
</p>
{% endblock%}