from flask import Flask, render_template, request, redirect, url_for, session, send_file import random import pandas as pd from fpdf import FPDF app = Flask(__name__) app.secret_key = 'your_secret_key_here' # セッションの安全な署名に必要なキー valence_dict = { "H": 1, # 水素 "He": 0, # ヘリウム "Li": 1, # リチウム "Be": 2, # ベリリウム "B": 3, # ホウ素 "C": 4, # 炭素 "N": 3, # 窒素 "O": 2, # 酸素 "F": 1, # フッ素 "Ne": 0, # ネオン "Na": 1, # ナトリウム "Mg": 2, # マグネシウム "Al": 3, # アルミニウム "Si": 4, # ケイ素 "P": 3, # リン "S": 2, # 硫黄 "Cl": 1, # 塩素 "Ar": 0, # アルゴン "K": 1, # カリウム "Ca": 2, # カルシウム "Ti": 4, # チタン "V": 5, # バナジウム "Cr": 6, # クロム "Mn": 7, # マンガン "Fe": 3, # 鉄 "Ni": 2, # ニッケル "Cu": 2, # 銅 "Zn": 2, # 亜鉛 "Se": 2, # セレン "Br": 1, # 臭素 "I": 1, # ヨウ素 "Xe": 0, # キセノン "Ba": 2, # バリウム "W": 6, # タングステン "Pt": 2, # 白金 "Au": 3, # 金 "Hg": 2, # 水銀 "Pb": 4, # 鉛 } questions = {f"What is the valence of {element}?": str(valence) for element, valence in valence_dict.items()} def get_random_question(): question = random.choice(list(questions.keys())) return question, questions[question] @app.route('/', methods=['GET', 'POST']) def quiz(): if 'current_question' not in session: # セッションに現在の問題がない場合は新しいものを取得 session['current_question'], session['current_answer'] = get_random_question() result = None if request.method == 'POST': user_input = request.form['user_input'] if user_input == session['current_answer']: result = '正解です!' else: result = '不正解です。正解は{}です。'.format(session['current_answer']) return render_template('quiz.html', question=session['current_question'], result=result) @app.route('/next', methods=['POST']) def next_question(): session.pop('current_question') # 現在の問題をセッションから削除 session.pop('current_answer') return redirect(url_for('quiz')) @app.route('/download_pdf', methods=['GET']) def download_pdf(): df = pd.DataFrame(list(questions.items()), columns=['Question', 'Answer']) class PDF(FPDF): def header(self): self.set_font('Arial', 'B', 12) self.cell(0, 10, 'Questions and Answers', 0, 1, 'C') def chapter_title(self, title): self.set_font('Arial', 'B', 12) self.cell(0, 10, title, 0, 1, 'L') self.ln(2) # 行間を削減 def chapter_body(self, body): self.set_font('Arial', '', 12) self.multi_cell(0, 8, body) # 行間を削減 self.ln() def add_question_answer(self, question, answer, x_offset): self.set_xy(x_offset, self.get_y()) self.chapter_title(question) self.set_x(x_offset) self.chapter_body(answer) self.set_x(x_offset) self.cell(90, 0, border=1) # 枠線を追加 pdf = PDF() pdf.add_page() column_width = pdf.w / 2 - 20 # 2段組の設定 for index, row in df.iterrows(): x_offset = 10 if index % 2 == 0 else pdf.w / 2 + 10 if index % 2 == 0 and index != 0: pdf.ln() # 新しい行に移動 pdf.add_question_answer(row['Question'], row['Answer'], x_offset) pdf_output = '/tmp/questions.pdf' pdf.output(pdf_output) return send_file(pdf_output, as_attachment=True) if __name__ == '__main__': app.run(debug=True, port=7860, host="0.0.0.0")