Published Date : 2021年1月15日21:40

Part 3 - Pythonを使って複利による利息の計算をするアプリを作ろう
Part 3 - Create an app that calculates compound interest using Python


This blog has an English translation


ニコニコ動画にアップした動画のまとめ記事です。

This is a summary blog post about a video I uploaded to NicoNico.

細かい部分は動画を参考にしてください。

Please refer to the video for details.


目次

Table of Contents




① 動画の説明
① Video Description



警告:

このアプリは大雑把に大体の見積りを計算して楽しむ為のツールです。

計算の詳細や、端数の処理等は各金融機関等によって異なります。

このアプリを使って何かしらの損害が発生したとしても、私は一切の責任を負いません。

このアプリを使って何かしらの損害が発生したとしても、私は一切の責任を負いません。

Warning:

This application is used to calculate rough estimates and enjoy them.

The details of calculations and the treatment of fractions differ depending on the financial institution.

​I will not be liable for any damage caused by using this app.

前回までに作成したPythonスクリプトのアプリをFlaskを使ってWEBアプリに作成し直してみましょう。

Use Flask to re-create the previously written Python script as a web application.

いつものように、templatesフォルダとstaticフォルダを作成します。

As usual, create the templates and static folders.

そして、前回の動画シリーズ同様にBootstrapとJQueryをstaticフォルダにコピペして、さらにJSフォルダを作成します。

Then, as in the previous video series, copy and paste Bootstrap and JQuery into a static folder and create a JS folder.

作業用フォルダ内にアプリケーション用のPythonスクリプトファイルを作成します。

Create an Python script file for your application in the working folder.

flask app folder/
    static/
        bootstrap-4.5.3-dist/
            js/
            css/
        js/
            calculate.js
    templates/
        application.html
    application.py

いつものように、必要なモジュールをインポートして、JSONを扱えるようにJSONモジュール、端数処理用のmathモジュールとDecimalモジュールをそれぞれインポートします。

As usual, import the modules you need, import the JSON modules to handle JSON, and import the math and Decimal modules for rounding, respectively.

application.py
from flask import Flask, render_template, request, jsonify
import json
from math import ceil
from decimal import Decimal, ROUND_HALF_UP

アプリケーションのインスタンスを作成し、指定したURLへアクセスがあった場合の処理を書きます。

Create an instance of the application and write what happens if the specified URL is accessed.

application.py
app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def reserve_month():
    if request.method == 'GET':
        return render_template('application.html')

GETリクエストがあった時はそのままアプリケーション用のHTMLをブラウザに表示させます。

When a GET request is made, HTML for the application is displayed in the browser.

debugをTrueにすれば、サーバーを再起動しなくてもファイルの変更を反映できます。

You can set debug to True to reflect file changes without restarting the server.

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

templatesフォルダ内にアプリケーション用のHTMLファイルを作成します。

Create an HTML file for your application in the templates folder.

タイトルを作成して、BootstrapとJSファイル、JQueryへのパスを記述します。

Create a title and describe the path to Bootstrap, JS files, and JQuery.

templates/application.html
<!DOCTYPE html>
<html lang="ja-jp">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="../static/bootstrap-4.5.3-dist/css/bootstrap.min.css">

    <title>毎月積立複利計算アプリ</title>
</head>

<body>


    <script src="../static/bootstrap-4.5.3-dist/js/jquery-3.5.1.min.js"></script>
    <script src="../static/bootstrap-4.5.3-dist/js/bootstrap.min.js"></script>
    <script src="../static/js/calculate.js"></script>
</body>

</html>

AJAXによる非同期処理で計算結果を表示させたいので、その処理をJSファイルに書き込みます。

We want to display the result of the calculation in the asynchronous processing by AJAX, so we write the processing to the JS file.

計算ボタンが押された時に、インプットタグやチェックボタンの数値を変数に収めてから、AJAXを使いPOSTメソッドで指定したURLにデータを送るようにします。

When the calculation button is pressed, the input tag or the numeric value of the check button is stored in a variable, and then data is sent to the URL specified by the POST method using AJAX.

この処理の内容は前回とほぼ変わりませんので、詳しくは前回の動画を参考にしてください。

The content of this process is almost the same as last time, so please refer to the previous video for details.

アプリケーション用のHTMLファイルに、計算に必要な数値を入力するフォームをBootstrapのCSSを利用して書き込みます。

In your application's HTML file, use Bootstrap's CSS to create a form in which you enter the numbers you need to calculate.

内容は前回の動画シリーズとほぼ変わりませんが、今回はform-rowを使用して、横並びに表示させるようにします。

The content is almost the same as the previous video series, but this time, I will use form-row to display horizontally.

JSファイルに戻り、IDからインプットタグの数値を取り出し、JSONに変換します。

Return to the JS file, retrieve the input tag number from the ID, and convert it to JSON.

そのIDをHTMLファイルのインプットタグにコピペします。

Copy and paste the ID into the input tag of the HTML file.

Placeholderや最小値と最大値は各自で自由に設定してください。

Set the placeholder and the minimum and maximum values as you like.

ひとまずアプリケーションの表示を確かめてみましょう。

Let's check the application display for now.

アプリケーション用のHTMLに戻り、計算ボタンとリセットボタンを作成しましょう。

Return to the HTML for your application and create the calculation and reset buttons.

計算結果を表示させる領域も作成しておきます。

You should also create an area to display the results of the calculation.

アプリケーション用のPythonスクリプトファイルに戻り、POSTリクエストされた時の処理を書いていきます。

Return to the Python script file for your application and write what to do when a POST request is made.

application.py
if request.method == 'POST':
    try:
        年利 = float(request.json['annualInterestRate']) / 100
        初期金額 = int(request.json['initialPrincipal']) * 10000
        毎月の積立金 = int(request.json['monthlyReserve']) * 10000
        積立年数 = int(request.json['period'])

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

前回同様にtry/exceptionを使用して、JSONから値を取り出し変数に収めていくと同時に例外処理も書いていきます。

As before, we use try/exception to take the values out of JSON and put them into variables, as well as write exception handling.

取り敢えず挙動を確かめて見るために、適当な文字列をJSONにダンプして、レスポンスとして返してみましょう。

For now, to see what it does, I'll dump a appropriate string to JSON and return it as a response.

適当な値を入力して、計算ボタンを押してサーバーにリクエストを送り、ブラウザ側でコンソールを開き、レスポンスされた値を確認してみましょう。

Enter an appropriate value, press the Calculate button to send a request to the server, and open the console on the browser side to see the response.

挙動を確認したら、リセットボタンが押された時の処理をJSファイルに書きます。

After checking the behavior, write the action when the reset button is pressed to the JS file.

それでは入力した値がきちんとリセットされる事を確認してみてください。

Then, please check that the entered value is reset properly.



以上です。お疲れ様です。

That's all. Thank you for your hard work.

各自で創意工夫してもっと良いアプリに仕上げてください。

Please devise your own ideas and make it a better application.