Python - 使用 Flask 构建问答应用项目



在这里,我们将使用 Python Flask 创建一个问答应用程序。 Flask 是一个轻量级的 Python Web 应用框架。选项包括选择测验、回答问题以及在应用程序上查看结果。它具有用于处理测验会话的动态路由,并可以使用 HTML 模板和 CSS 来实现用户界面,使其更加精致。

安装

使用 pip 安装 Flask −

pip install flask

问答应用项目代码文件

以下是创建问答应用项目的代码文件 −

1. 文件:app.py

from flask import Flask, render_template, request, redirect, url_for, session
app = Flask(__name__)
app.secret_key = 'your_secret_key'
# Example quiz data
quiz_data = {
   "quizzes": {
      "General Knowledge": [
         {
            "question": "What is the capital of France?",
            "options": ["Paris", "London", "Berlin", "Madrid"],
            "answer": "Paris"
         },
         {
            "question": "Which planet is known as the Red Planet?",
            "options": ["Earth", "Mars", "Jupiter", "Venus"],
            "answer": "Mars"
         },
         {
            "question": "Who wrote 'To Kill a Mockingbird'?",
            "options": ["Harper Lee", "Mark Twain", "J.K. Rowling", "Jane Austen"],
            "answer": "Harper Lee"
         },
         {
            "question": "What is the largest ocean on Earth?",
            "options": ["Atlantic Ocean", "Indian Ocean", "Arctic Ocean", "Pacific Ocean"],
            "answer": "Pacific Ocean"
         },
         {
            "question": "What is the smallest country in the world?",
            "options": ["Monaco", "San Marino", "Vatican City", "Liechtenstein"],
            "answer": "Vatican City"
         },
         {
            "question": "In which year did the Titanic sink?",
            "options": ["1912", "1905", "1898", "1923"],
            "answer": "1912"
         },
         {
            "question": "What is the hardest natural substance on Earth?",
            "options": ["Gold", "Iron", "Diamond", "Platinum"],
            "answer": "Diamond"
         },
         {
            "question": "Which element has the chemical symbol 'O'?",
            "options": ["Oxygen", "Gold", "Silver", "Osmium"],
            "answer": "Oxygen"
         },
         {
            "question": "Who painted the Mona Lisa?",
            "options": ["Leonardo da Vinci", "Vincent van Gogh", "Claude Monet", "Pablo Picasso"],
            "answer": "Leonardo da Vinci"
         },
         {
            "question": "What is the longest river in the world?",
            "options": ["Nile", "Amazon", "Yangtze", "Mississippi"],
            "answer": "Nile"
         }
      ],
      "Science": [
         {
            "question": "What is the chemical symbol for water?",
            "options": ["H2O", "O2", "CO2", "HO2"],
            "answer": "H2O"
         },
         {
            "question": "Who developed the theory of relativity?",
            "options": ["Isaac Newton", "Albert Einstein", "Galileo Galilei", "Nikola Tesla"],
            "answer": "Albert Einstein"
         },
         {
            "question": "What is the powerhouse of the cell?",
            "options": ["Nucleus", "Mitochondria", "Ribosome", "Endoplasmic Reticulum"],
            "answer": "Mitochondria"
         },
         {
            "question": "What planet is known for its rings?",
            "options": ["Saturn", "Jupiter", "Uranus", "Neptune"],
            "answer": "Saturn"
         },
         {
            "question": "What is the main gas found in the air we breathe?",
            "options": ["Oxygen", "Nitrogen", "Carbon Dioxide", "Hydrogen"],
            "answer": "Nitrogen"
         },
         {
            "question": "What is the chemical symbol for gold?",
            "options": ["Au", "Ag", "Pb", "Fe"],
            "answer": "Au"
         },
         {
            "question": "What is the speed of light?",
            "options": ["300,000 km/s", "150,000 km/s", "100,000 km/s", "200,000 km/s"],
            "answer": "300,000 km/s"
         },
         {
            "question": "Who is known as the father of modern physics?",
            "options": ["Isaac Newton", "Albert Einstein", "Niels Bohr", "Richard Feynman"],
            "answer": "Albert Einstein"
         },
         {
            "question": "What is the chemical formula for methane?",
            "options": ["CH4", "C2H6", "C3H8", "C4H10"],
            "answer": "CH4"
         },
         {
            "question": "What force keeps us grounded on Earth?",
            "options": ["Gravity", "Magnetism", "Friction", "Electromagnetism"],
            "answer": "Gravity"
         }
      ]
   }
}

@app.route('/')
def index():
   return render_template('index.html', quizzes=quiz_data["quizzes"])

@app.route('/start_quiz/<quiz_name>')
def start_quiz(quiz_name):
   session['quiz_name'] = quiz_name
   session['current_question'] = 0
   session['score'] = 0
   return redirect(url_for('quiz_question'))

@app.route('/quiz_question', methods=['GET', 'POST'])
def quiz_question():
   quiz_name = session.get('quiz_name')
   current_question = session.get('current_question', 0)  # Default to 0 if not set
   quiz_questions = quiz_data["quizzes"].get(quiz_name, [])

   if request.method == 'POST':
      selected_option = request.form.get('option')
      correct_answer = quiz_questions[current_question]['answer']

      # Check if the selected answer is correct
      if selected_option == correct_answer:
         session['score'] = session.get('score', 0) + 1  # Increment score if the answer is correct
         feedback = "Correct! Well done."
      else:
         feedback = f"Wrong! The correct answer is {correct_answer}."

      # Move to the next question
      session['current_question'] = current_question + 1
      session['feedback'] = feedback

      if session['current_question'] >= len(quiz_questions):
         return redirect(url_for('quiz_result'))

   return redirect(url_for('quiz_question'))

   # Handle GET request: get current question data
   if current_question < len(quiz_questions):
      current_question_data = quiz_questions[current_question]
      feedback = session.pop('feedback', '')  # Remove feedback from session
      return render_template('quiz_question.html', question_data=current_question_data, current_question=current_question + 1, total_questions=len(quiz_questions), feedback=feedback)
   else:
      return redirect(url_for('quiz_result'))

@app.route('/quiz_result')
def quiz_result():
   score = session.get('score', 0)  # Default to 0 if score is not found
   quiz_name = session.get('quiz_name')
   total_questions = len(quiz_data["quizzes"].get(quiz_name, []))  # Handle case where quiz_name might not be found

   return render_template('quiz_result.html', score=score, total_questions=total_questions)

if __name__ == '__main__':
   app.run(debug=True)

2. 文件:index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Quiz Platform</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<header>
   <h1>Welcome to the Quiz Platform</h1>
</header>
<div class="container">
<h1>Select a Quiz</h1>
<ul>
   {% for quiz in quizzes %}
   <li><a href="{{ url_for('start_quiz', quiz_name=quiz) }}">{{ quiz }}</a></li>
   {% endfor %}
</ul>
</div>
</body>
</html>

3. 文件 (quiz_question.html)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Question</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<header>
   <h1>Quiz Question</h1>
</header>
<div class="container">
   <h2>Question {{ current_question }} of {{ total_questions }}</h2>
   <form method="post">
      <p>{{ question_data['question'] }}</p>
      {% for option in question_data['options'] %}
      <div>
         <input type="radio" id="{{ option }}" name="option" value="{{ option }}">
         <label for="{{ option }}">{{ option }}</label>
      </div>
      {% endfor %}
      <button type="submit">Submit</button>
   </form>
   <p>{{ feedback }}</p>
</div>
</body>
</html>

4. 文件:(quiz_result.html)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Result</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<header>
   <h1>Quiz Result</h1>
</header>
<div class="container">
   <h2>Your Score</h2>
   <p>You scored {{ score }} out of {{ total_questions }}.</p>
   <a href="{{ url_for('index') }}">Return to Home</a>
</div>
</body>
</html>

5. 文件 (styles.css)

body {
   font-family: Arial, sans-serif;
   background-color: #f4f4f4;
   margin: 0;
   padding: 0;
}

header {
   background-color: #333;
   color: #fff;
   padding: 10px 0;
   text-align: center;
}

.container {
   max-width: 800px;
   margin: 20px auto;
   padding: 20px;
   background: #fff;
   box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1, h2 {
   color: #333;
}

ul {
   list-style-type: none;
   padding: 0;
}

li {
   margin: 10px 0;
}

a {
   text-decoration: none;
   color: #007bff;
}

a:hover {
   text-decoration: underline;
}

form div {
   margin: 10px 0;
}

input[type="radio"] {
   margin-right: 10px;
}

button {
   background-color: #007bff;
   color: #fff;
   border: none;
   padding: 10px 20px;
   cursor: pointer;
}

button:hover {
   background-color: #0056b3;
}

背景图片文件

Background Image

文件结构

File Structure

使用应用程序的步骤

  • **设置虚拟环境** − 创建并激活一个虚拟空间。
  • **安装依赖项** − 您可以使用安装 Python 时使用的 pip 来安装 Flask,使用命令 pip install Flask,如下面的图片所示。
  • **运行应用程序** − 通过运行代码启动 Flask,并在 Web 浏览器中打开应用程序。
  • **与应用程序交互** − 完成问卷,回答问题并查看您的分数。

输出

可以通过 http://127.0.0.1:5000/ 访问该应用程序。转到您的隐身标签。

Output

搜索后,您将看到此界面 −

interface

您可以选择任何一个,我选择常识 −

interface

成功完成测验后,您将看到 −

interface
python_projects_from_basic_to_advanced.htm
广告