Flask

Flask を使った簡単なWEBシステム

-- 以下をプロジェクトのフォルダ構成とします。
--
/ api-runner
|-- / templates
  |-- / apis
    |--  api1_form.html
  |--  index.html
  |--  result.html
|--  app.py
flask-apl >> pwd

Path
----
C:\python-prj\flask-apl

flask-apl >> .\myenv\Scripts\activate
(myenv) flask-apl >> python app.py
 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 117-690-870
ブラウザで確認
http://127.0.0.1:5000/
api1_form.html
<h2>API 1 テスト</h2>
<form method="post" action="/run/1">
  <label>パラメータ1: <input type="text" name="param1"></label><br>
  <label>トークン(任意): <input type="text" name="token"></label><br>
  <button type="submit">実行</button>
</form>
<a href="/">← 戻る</a>
index.html
<h2>APIテストメニュー</h2>
<ul>
  <li><a href="/api/1">API 1 テスト</a></li>
  <li><a href="/api/2">API 2 テスト</a></li>
  <li><a href="/api/3">API 3 テスト</a></li>
</ul>
result.html
<h2>API 実行結果</h2>
<pre>{{ result }}</pre>
<a href="/">← メニューへ戻る</a>
app.py
from flask import Flask, render_template, request
import subprocess

app = Flask(__name__)

# トップページ(ランチャー)
@app.route('/')
def index():
    return render_template('index.html')

# 各APIごとの入力画面
@app.route('/api/<api_id>')
def api_form(api_id):
    try:
        return render_template(f'apis/api{api_id}_form.html')
    except:
        return f"API {api_id} の入力画面が見つかりません", 404

# API実行(フォームからPOST)
@app.route('/run/<api_id>', methods=['POST'])
def run_api(api_id):
    param1 = request.form.get('param1')
    token = request.form.get('token')

    api_urls = {
        '1': 'https://httpbin.org/get',
        '2': 'https://httpbin.org/uuid',
        '3': 'https://httpbin.org/ip',
    }

    url = api_urls.get(api_id)
    if not url:
        return "無効なAPI", 400

    curl_cmd = ['curl', '-s', url]
    if param1:
        curl_cmd += ['--data-urlencode', f'param1={param1}']
    if token:
        curl_cmd += ['-H', f'Authorization: Bearer {token}']

    try:
        result = subprocess.check_output(curl_cmd, text=True)
    except Exception as e:
        return f"curl実行エラー: {str(e)}", 500

    return render_template('result.html', result=result)

if __name__ == '__main__':
    app.run(debug=True)
スポンサーリンク
タイトルとURLをコピーしました