Published Date : 2020年10月2日7:41

【python, flask】賃金階級年齢階級別労働者割合のWEBアプリ part1
【python, flask】Web application for ratio of workers by wage class and age group part 1


This blog has an English translation


YouTubeにアップした動画、「【python, flask】賃金階級年齢階級別労働者割合のWEBアプリ part1」の補足説明の記事です。

Here's a little more about the 「【python, flask】Web application for ratio of workers by wage class and age group part 1」 video I uploaded to YouTube.


目次

Table of Contents




① 動画の説明
① Video Description



前回の続きです。

This is the continuation of the last time.

厚生労働省が公表している[平成30年賃金構造基本統計調査の概況]を使ったWEBアプリケーションを、

Let's create a web application using the Ministry of Health, Labor and Welfare's [Overview of the 2018 Basic Survey on Wage Structure]

PythonのFlaskを使用して作成してHerokuにアップしてみましょう。

and upload it to Heroku using Python's Flask.

今回はFlaskを使ってWEBアプリケーションがどのように動くかの確認だけ行います。

This time we will only use Flask to see how the web application works.

まずPython3の標準モジュールのvenvを使って仮想環境を構築します。

First, we build a virtual environment using the standard Python 3 module venv.

c:\Users\user> mkdir "your/project/folder"
c:\Users\user> cd "your project folder"
c:\Users\user\your project folder> python -m venv "your virtual environment name"
activate
c:\Users\user\your project folder> your virtual environment name/Scripts/activate
(your virtual environment name) c:\Users\user\your project folder> 
deactivate
(your virtual environment name) c:\Users\user\your project folder> deactivate
c:\Users\user\your project folder> 

こうすることで今回のWEBアプリの開発環境と自分達が普段使っているPythonの環境を分けて、

By doing this way, we can separate the development environment of the WEB application from the Python environment that

WEBアプリの開発に必要なモジュールのみを使うことができます。

we usually use, and use only the modules necessary for developing the WEB application.

準備ができたらFlaskをインストールします。

When you are ready, install Flask.

pip install Flask

まずはローカル環境で開発していきましょう。

First, let's develop in the local environment.

ちなみに[app_test]は先ほど用意したPythonの仮想環境のフォルダです。

By the way, [app_test] is the Python virtual environment folder we prepared earlier.

適当な作業用フォルダを準備して、[templates]フォルダを作ります。

Set up a working folder and create a [templates] folder.

project folder/
    app_test/
    templates/
        index.html
    app.py

この中にHTMLファイルを作成して、Flaskの[render_template()メソッド]を使ってそのファイルを指定すると、

You can create an HTML file in it, specify it using Flask's [render_template() method],

自動でHTMLを認識してブラウザに表示してくれます。

and it will automatically recognize the HTML and display it in your browser.

Pythonの変数をHTMLファイル内の波括弧に入れるとJinja2と呼ばれるテンプレートエンジンがそれをHTMLで使えるようにしてくれます。

When you put Python variables in curly braces in an HTML file, a template engine called Jinja2 makes them available to HTML.

<p>{{ pyhton variable }}</p>

ではアプリを実際に動かすPythonファイルを作成しましょう。

Now let's create a Python file to actually run the app.

必要なライブラリをインポートして、アプリケーションのオブジェクトを作成します。

Create objects for the application by importing the required libraries.

このオブジェクトのroute()メソッドにURLのディレクトリを指定すると、下に用意した関数が動く仕組みです。

If you specify the directory of the URL in the route () method of this object, the function below will work.

"/"を指定すると、URLのディレクトリが無い、通常のURLでアクセスした場合の動作になります。

When "/" is specified, the operation is performed when the URL is accessed with a normal URL without a directory.

そしてindex関数は先ほど用意した[templatesフォルダ]の中の[index.html]をブラウザに表示させます。

The index function displays the [index.html] from the [templates folder] in the browser.

Python変数をrender_templateメソッドに渡してやると、先ほどのHTMLファイルの中でJinja2が認識してくれます。

If you pass a Python variable to the render_template() method, Jinja2 will recognize it in the HTML file.

app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    title = 'title'
    description = 'description'

    return render_template('index.html', title=title, description=description)

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

ちなみに、この"__name__"は、Pythonの特殊なグローバル変数と呼ばれるもので、

Incidentally, this "__name__" is called a special Python global variable,

プログラム実行前に自動で変数が割り当てられます。

and is automatically assigned before the program is executed.

分かりやすく言うと、Pythonのプログラムがコマンドラインで直接呼ばれ時は、

In a nutshell, when a Python program is called directly on the command line,

"__name__"変数に"__main__"という文字が入ります。

the "__name__" variable contains the word "__main__".

そして、Pyhonプログラム内でimportして呼ばれた場合は、

and when called by import within the Pyhon program,

"__name__"変数には"Pythonプログラムのファイル名"が入ります。

the "__name__" variable will contain the "The file name of the Python program".

***my_module.py***

def print_name_variable():
    print(__name__)

if __name__ == "__main__":
    print_name_variable()

***call_a_module.py***

import my_module

my_module.print_name_variable()

***command line****

C:\Users\user> python my_module.py
__main__

C:\Users\user> python call_a_module.py
my_module

ちなみにモジュール側のファイルのif文を外すと何も表示されません。

By the way, if you remove the if statement from the module's file, nothing is displayed.

***my_module.py***

def print_name_variable():
    print(__name__)

***command line****
C:\Users\user> python my_module.py

C:\Users\user> python call_a_module.py
my_module

つまり、そのPythonファイルをコマンドラインから実行できるMainファイルにしたいか、したくないか、

That is, it exists to make it clear whether you want the Python file to be a Main file that

モジュールとしてインポートしてから、実行したいファイルにしたいかを分けるためにこのような記法が存在しています。

you can run from the command line, or not, or import it as a module and then run it.

この[app.py]を動かすとサーバーが起動しますので、ローカルホストで指定された5000番ポートでブラウザからアクセスすると、

This [app.py] will start the server, so if you access it from your browser on the local host on port 5000,

C:\Users\user> python app.py
Starting development server at http://127.0.0.1:5000/
Quit the server with CTRL-BREAK.    
            

指定した文字列が表示されていることが確認できます。

you will see the specified string.

次のパート2では、ユーザーが年収と年齢をセレクトしてボタンを押すと、結果を表示させる機能を実装していきましょう。

In Part 2, we'll implement a feature that lets users select their annual income and age, press a button, and see the results.



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

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