#******************************************************************************# # ファイル名:main.py # バージョン:Ver1.0 # 機能: # 作成日:2024/11/25 # 更新日:2024/12/9 W006 #*******************************************************************************# import os import json from flask import Flask, render_template, request # --- 追加 6-1 request file_path = 'KDjson.json' app = Flask(__name__) @app.route('/') def hello_show(): return 'Hello World!' @app.route('/index') def index(): insert_dict = { 'insert_1': 'insert_1部分です。', 'insert_2': 'insert_2部分です。', } return render_template('index.html', title='Webアプリテスト', insert_dict=insert_dict) @app.route('/kakeibo', methods=['GET', 'POST']) #--- 修正6-1 def kd(): # 既存ファイルを確認 if not os.path.exists(file_path): # 無ければ作成 with open( file_path, mode='w', encoding="UTF-8" ) as open_json: initial_list = [{ "month" : [] , # "月" "day" : [] , # "日" "content" : [] , # "内訳" "amount" : [] # "金額" } ] json.dump( initial_list, open_json, indent=4, ensure_ascii=False) # GET送信 受信時 #--- 修正6-2 if request.method == 'GET': # JSONファイルを読み込んで、辞書型リストを作成 with open( file_path, mode='r', encoding="UTF-8") as open_json: json_load_list = json.load(open_json) return render_template('kakeibo_test_json/kd.html', title='kakeibo', pay_list=json_load_list) # POST送信 受信時 --- 追加6-2 if request.method == 'POST': # JSONファイルを読み込んで、辞書型リストを作成 with open( file_path, mode='r', encoding="UTF-8") as open_json: json_load_list = json.load(open_json) # 画面上で入力された情報を取得し、辞書データを作成 add_dict = {"month":request.form.get('month'), "day":request.form.get('day'), "content":request.form.get('content'), "amount":request.form.get('amount') } # 辞書データを辞書型リストに追加 json_load_list.append(add_dict) # JSONファイルに書き込み with open(file_path, mode='w',encoding="UTF-8") as open_json: json.dump(json_load_list, open_json ,indent=4,ensure_ascii=False) # 更新した辞書型リストを送信し、HTMLをレンダリング return render_template('kakeibo_test_json/kd.html', title='kakeibo', pay_list=json_load_list) if __name__ == '__main__': app.run() |

0 件のコメント:
コメントを投稿