Converting a Python program into a Web app
Notes on how to turn code written in Python into a Web app.
First, let's start with Hello World.
Hello World code (app.py)
Create the code for a Hello World Web app.
from flask import Flask
# Flaskアプリケーションのインスタンスを作成します。
# Flaskはこの `app` という名前の変数を見つけに来ます。
app = Flask(__name__)
# ルートURL ('/') にアクセスがあったときに、以下の関数を実行するよう設定します。
@app.route('/')
def hello_world():
# ブラウザに 'Hello, World!' という文字列を返します。
return 'Hello, World!'Create a virtual environment
In the case of Windows, it seems PowerShell does not recognize long paths, so we will create a virtual environment.
Check if you are in the folder containing the program at the terminal prompt. My environment's prompt looks like the following. If it is different, use cd to move to it.
PS C:\python\simple_test>Once you have confirmed the prompt, execute the following commands in order.
Set-ExecutionPolicy RemoteSigned -Scope Process.\.venv\Scripts\Activate.ps1After doing this, if (.venv) appears before the prompt, the virtual environment is activated.
(.venv) PS C:\python\simple_test>Install Flask
Install "Flask," a framework for turning Python into a Web app.
pip install FlaskRun the app
python -m flask runThen, "Running on http://○○○○" and a local IP address will appear in the terminal, so enter the IP address into your browser.
A red Warning appears, but it is just saying "This is a development version for a local environment, so do not install it on a server," so it will work in a local environment.
It appeared. Hello, World!

Execute CTRL+C in the terminal to stop the program and return to the prompt.
A Web app that has an HTML input for a name and returns a greeting
HTML input form
Place a file named index.html inside the templates folder.
c:\python\simple_test\
├── .venv\
├── app.py
├── templates\
│ └── index.html <= ここ
└── ... (他のゲームの.pyファイル)index.html
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>挨拶アプリ</title>
</head>
<body>
{% if name %}
<h1>こんにちは、{{ name }}さん!</h1>
<a href="/">戻る</a>
{% else %}
<h1>あなたの名前を教えてください</h1>
<form method="post">
<input type="text" name="username" placeholder="名前を入力" required>
<input type="submit" value="送信">
</form>
{% endif %}
</body>
</html>
App that returns a greeting (app.py)
from flask import Flask, render_template, request
# Flaskアプリケーションのインスタンスを作成します。
# Flaskはこの `app` という名前の変数を見つけに来ます。
app = Flask(__name__)
# ルートURL ('/') にアクセスがあったときに、以下の関数を実行するよう設定します。
# methods=['GET', 'POST'] を追加して、ページの表示とフォームの受信の両方に対応させます。
@app.route('/', methods=['GET', 'POST'])
def greet():
if request.method == 'POST':
# フォームが送信された場合 (POSTリクエスト)
user_name = request.form['username']
# 'name'という変数にユーザー名を渡して、index.htmlを描画します。
return render_template('index.html', name=user_name)
# ページに初めてアクセスした場合 (GETリクエスト)
# 何も渡さずにindex.htmlを描画します(フォームが表示されます)。
return render_template('index.html')Run the app
python -m flask runWhen I ran the app and entered the IP address into the browser, it returned a greeting.


Turning Rock Paper Scissors into an app
Game code (janken.py)
import random
def determine_winner(user_choice, computer_choice):
"""勝敗を判定して結果の文字列を返す関数"""
if user_choice == computer_choice:
return "あいこです!"
elif (user_choice == "グー" and computer_choice == "チョキ") or \
(user_choice == "チョキ" and computer_choice == "パー") or \
(user_choice == "パー" and computer_choice == "グー"):
return "あなたの勝ちです!🎉"
else:
return "コンピュータの勝ちです!残念!"
def play_janken():
"""じゃんけんゲームを実行する関数"""
options = ["グー", "チョキ", "パー"]
print(f"あなたの手: {user_choice}")
print(f"コンピュータの手: {computer_choice}\n")
result = determine_winner(user_choice, computer_choice)
print(result)
def main():
"""ゲームのメインループ"""HTML for Rock Paper Scissors (janken.html)
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>じゃんけんゲーム</title>
</head>
<body>
<h1>じゃんけんゲーム</h1>
<p>あなたの手を選んでください!</p>
<form method="post">
<button type="submit" name="hand" value="グー">グー ✊</button>
<button type="submit" name="hand" value="チョキ">チョキ ✌️</button>
<button type="submit" name="hand" value="パー">パー ✋</button>
</form>
{% if result %}
<hr>
<h2>結果</h2>
<p>あなたの手: {{ user_hand }}</p>
<p>コンピュータの手: {{ computer_hand }}</p>
<h3>{{ result }}</h3>
<a href="/janken">もう一度!</a>
{% endif %}
</body>
</html>Flask app (app.py)
from flask import Flask, render_template, request
import random
# janken.py から determine_winner 関数をインポート
from janken import determine_winner
# Flaskアプリケーションのインスタンスを作成します。
app = Flask(__name__)
# ルートURL ('/') にアクセスがあったときに、以下の関数を実行するよう設定します。
# ページに初めてアクセスした場合 (GETリクエスト)
# 何も渡さずにindex.htmlを描画します(フォームが表示されます)。
return render_template('index.html')
@app.route('/janken', methods=['GET', 'POST'])
def janken_game():
if request.method == 'POST':
# ユーザーがボタンを押した場合 (POST)
user_hand = request.form['hand']
options = ["グー", "チョキ", "パー"]
computer_hand = random.choice(options)
result = determine_winner(user_hand, computer_hand)
# 結果をHTMLに渡して描画
return render_template('janken.html',
user_hand=user_hand,
computer_hand=computer_hand,
result=result)
# ページに初めてアクセスした場合 (GET)
# 初期ページを表示
return render_template('janken.html')Run the app

It's local, but I was able to run it in the browser!
Next, I hope I can get it published.
I hope this is helpful to someone.
