Pythonで作ったプログラムをWebアプリに変換
Pythonで作ったコードをWebアプリ化する方法をメモ。
まずは、ハローワールドから
ハローワールドのコード(app.py)
ハローワールドのWebアプリのコードを作ります。
from flask import Flask
# Flaskアプリケーションのインスタンスを作成します。
# Flaskはこの `app` という名前の変数を見つけに来ます。
app = Flask(__name__)
# ルートURL ('/') にアクセスがあったときに、以下の関数を実行するよう設定します。
@app.route('/')
def hello_world():
# ブラウザに 'Hello, World!' という文字列を返します。
return 'Hello, World!'仮想環境を作る
Windowsの場合、PowerShellが長いパスを認識しないみたいなので、仮想環境を作ります。
ターミナルのプロンプトで、プログラムがあるフォルダにいるか確認します。自分の環境のプロンプトは以下の感じ。違ったら、cd で移動します。
PS C:\python\simple_test>プロンプトの確認ができたら、以下のコマンドを順番に実行。
Set-ExecutionPolicy RemoteSigned -Scope Process.\.venv\Scripts\Activate.ps1これをした後に、プロンプトの前に(.venv)がついていたら仮想環境が有効化されています。
(.venv) PS C:\python\simple_test>Flaskをインストール
PythonをWebアプリにするフレームワーク「Flask」をインストールします。
pip install Flaskアプリを実行
python -m flask runすると、ターミナルに、「Running on http://○○○○」とローカルのIPアドレスが出るのでブラウザにIPアドレスを入力します。
赤いWarningが出てますが「これはローカル環境での開発版なので、サーバーにインストールしちゃダメです」という物なので、ローカル環境では動きます。
出ました。Hello,World!

ターミナルでCTRL+Cを実行して、プログラムを停止してプロンプトに戻ります。
名前を入力するHTMLと挨拶を返すWEBアプリ
HTMLの入力フォーム
index.htmlというファイルをtemplatesフォルダの中に入れます。
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.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')アプリを実行
python -m flask runアプリを実行して、ブラウザにIPアドレスを入れると挨拶を返してくれました。


ジャンケンをアプリ化
ゲームのコード(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(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.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')アプリを実行

ローカルだけどブラウザで実行できました!
次は、公開までできればいいなあ。
誰かの参考になれば幸いです。
