单击按钮代码后,将我重定向到“/结果”而不是“/测试”,请帮我修复它
quiz.py(主要代码):
import os
from random import shuffle
from flask import Flask, session, request, redirect, render_template, url_for
from db_scripts import get_question_after, get_quises, check_answer
def start_quiz(quiz_id):
session['quiz'] = quiz_id
session['last_question'] = 0
session['answers'] = 0
session['total'] = 0
def end_quiz():
session.clear()
def quiz_form():
q_list = get_quises()
return render_template('start.html', q_list=q_list)
def index():
if request.method == 'GET':
start_quiz(-1)
return quiz_form()
else:
quest_id = request.form.get('quiz')
start_quiz(quest_id)
return redirect(url_for('test', _method='POST'))
def save_answers():
answer = request.form.get('ans_text')
quest_id = request.form.get('q_id')
session['last_question'] = quest_id
session['total'] += 1
if check_answer(quest_id, answer):
session['answers'] += 1
def test():
if not ('quiz' in session) or int(session['quiz']) < 0:
return redirect(url_for('index'))
else:
if request.method == 'POST':
save_answers()
return redirect(url_for('test'))
next_question = get_question_after(session['last_question'], session['quiz'])
if next_question is None or len(next_question) == 0:
return redirect(url_for('result'))
else:
answers_list = [
next_question[2], next_question[3], next_question[4], next_question[5]
]
shuffle(answers_list)
return render_template('test.html', question=next_question[1], quest_id=next_question[0], answers_list=answers_list)
def result():
html = render_template('result.html', right=session['answers'], total=session['total'])
end_quiz()
return html
folder = os.getcwd()
app = Flask(__name__, template_folder=folder, static_folder=folder)
app.add_url_rule('/', 'index', index, methods=['post', 'get'])
app.add_url_rule('/test', 'test', test, methods=['post', 'get'])
app.add_url_rule('/result', 'result', result, methods=['post', 'get'])
app.config['SECRET_KEY'] = 'ThisIsSecretSecretSecretLife'
if __name__ == "__main__":
app.run()
开始.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<style>
body {
background-color: #D1E9F5;
color: #555555;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
text-align: center;
}
h2 {
color: #6CB4D6;
font-size: 24px;
margin-bottom: 20px;
}
form {
display: inline-block;
padding: 20px;
background-color: #F0F8FF;
border-radius: 10px;
}
select {
width: 100%;
padding: 10px;
font-size: 18px;
border: 2px solid #6CB4D6;
border-radius: 5px;
background-color: #F0F8FF;
color: #555555;
margin-bottom: 10px;
}
input[type="submit"] {
width: 100%;
padding: 10px;
font-size: 18px;
border: none;
border-radius: 5px;
background-color: #6CB4D6;
color: #FFFFFF;
cursor: pointer;
}
</style>
<title>Викторина</title>
</head>
<body>
<div class="container">
<h2>Выберите викторину:</h2>
<form method="post" action="{{ url_for('test') }}">
<select name="quiz">
{% for id, name in q_list %}
<option value="{{id}}">{{name}}</option>
{% endfor %}
</select>
<p><input type="submit" value="Выбрать"></p>
</form>
</div>
</body>
</html>
和 db_scripts.py(带有脚本的库)
import sqlite3
from random import randint
db_name = 'quiz.sqlite'
conn = None
cursor = None
def open():
global conn, cursor
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
def close():
cursor.close()
conn.close()
def do(query):
cursor.execute(query)
conn.commit()
def clear_db():
''' убивает все таблицы '''
open()
query = '''DROP TABLE IF EXISTS quiz_content'''
do(query)
query = '''DROP TABLE IF EXISTS question'''
do(query)
query = '''DROP TABLE IF EXISTS quiz'''
do(query)
close()
def create():
open()
cursor.execute('''PRAGMA foreign_keys=on''')
do('''CREATE TABLE IF NOT EXISTS quiz (
id INTEGER PRIMARY KEY,
name VARCHAR)'''
)
do('''CREATE TABLE IF NOT EXISTS question (
id INTEGER PRIMARY KEY,
question VARCHAR,
answer VARCHAR,
wrong1 VARCHAR,
wrong2 VARCHAR,
wrong3 VARCHAR)'''
)
do('''CREATE TABLE IF NOT EXISTS quiz_content (
id INTEGER PRIMARY KEY,
quiz_id INTEGER,
question_id INTEGER,
FOREIGN KEY (quiz_id) REFERENCES quiz (id),
FOREIGN KEY (question_id) REFERENCES question (id) )'''
)
close()
def show(table):
query = 'SELECT * FROM ' + table
open()
cursor.execute(query)
print(cursor.fetchall())
close()
def show_tables():
show('question')
show('quiz')
show('quiz_content')
def add_questions():
questions = [
('Сколько месяцев в году имеют 28 дней?', 'Все', 'Один', 'Ни одного', 'Два'),
('Каким станет зеленый утес, если упадет в Красное море?', 'Мокрым?', 'Красным', 'Не изменится', 'Фиолетовым'),
('Какой рукой лучше размешивать чай?', 'Ложкой', 'Правой', 'Левой', 'Любой'),
('Что не имеет длины, глубины, ширины, высоты, а можно измерить?', 'Время', 'Глупость', 'Море', 'Воздух'),
('Когда сетью можно вытянуть воду?', 'Когда вода замерзла', 'Когда нет рыбы', 'Когда уплыла золотая рыбка', 'Когда сеть порвалась'),
('Что больше слона и ничего не весит?', 'Тень слона', 'Воздушный шар', 'Парашют', 'Облако'),
('Что такое у меня в кармашке?', 'Кольцо', 'Кулак', 'Дырка', 'Бублик')
]
open()
cursor.executemany('''INSERT INTO question (question, answer, wrong1, wrong2, wrong3) VALUES (?,?,?,?,?)''', questions)
conn.commit()
close()
def add_quiz():
quizes = [
('Викторина 1', ),
('Викторина 2', ),
('Викторина-непоймикакая', )
]
open()
cursor.executemany('''INSERT INTO quiz (name) VALUES (?)''', quizes)
conn.commit()
close()
def add_links():
open()
cursor.execute('''PRAGMA foreign_keys=on''')
query = "INSERT INTO quiz_content (quiz_id, question_id) VALUES (?,?)"
answer = input("Добавить связь (y / n)?")
while answer != 'n':
quiz_id = int(input("id викторины: "))
question_id = int(input("id вопроса: "))
cursor.execute(query, [quiz_id, question_id])
conn.commit()
answer = input("Добавить связь (y / n)?")
close()
def get_question_after(last_id=0, vict_id=1):
''' возвращает следующий вопрос после вопроса с переданным id
для первого вопроса передается значение по умолчанию '''
open()
query = '''
SELECT quiz_content.id, question.question, question.answer, question.wrong1, question.wrong2, question.wrong3
FROM question, quiz_content
WHERE quiz_content.question_id == question.id
AND quiz_content.id > ? AND quiz_content.quiz_id == ?
ORDER BY quiz_content.id '''
cursor.execute(query, [last_id, vict_id] )
result = cursor.fetchone()
close()
return result
def get_quises():
''' возвращает список викторин (id, name)
можно брать только викторины, в которых есть вопросы, но пока простой вариант '''
query = 'SELECT * FROM quiz ORDER BY id'
open()
cursor.execute(query)
result = cursor.fetchall()
close()
return result
def check_answer(q_id, ans_text):
query = '''
SELECT question.answer
FROM quiz_content, question
WHERE quiz_content.id = ?
AND quiz_content.question_id = question.id
'''
open()
cursor.execute(query, str(q_id))
result = cursor.fetchone()
close()
# print(result)
if result is None:
return False # не нашли
else:
if result[0] == ans_text:
# print(ans_text)
return True # ответ совпал
else:
return False # нашли, но ответ не совпал
def get_quiz_count():
''' необязательная функция '''
query = 'SELECT MAX(quiz_id) FROM quiz_content'
open()
cursor.execute(query)
result = cursor.fetchone()
close()
return result
def get_random_quiz_id():
query = 'SELECT quiz_id FROM quiz_content'
open()
cursor.execute(query)
ids = cursor.fetchall()
rand_num = randint(0, len(ids) - 1)
rand_id = ids[rand_num][0]
close()
return rand_id
def main():
clear_db()
create()
add_questions()
add_quiz()
show_tables()
add_links()
show_tables()
# print(get_question_after(0, 3))
# print(get_quiz_count())
# print(get_random_quiz_id())
pass
if __name__ == "__main__":
main()
这里还有完整文件夹的链接 - https://drive.google.com/drive/folders/1QscF375wa5aANxMjbCwAD5lJ4T_PIUQ3?usp=drive_link
我尝试使用 hlml 代码本身来使用“def index”,但 id 没有帮助
你的代码说
next_question = get_question_after(session['last_question'], session['quiz'])
if next_question is None or len(next_question) == 0:
return redirect(url_for('result'))
既然你说提交表格会将你重定向到
/result
,那就意味着上述条件已经满足。如果您期望获得 next_question
的值,那么您应该弄清楚为什么这种情况没有发生(也许您没有将其保存在会话中,而会话正是您的代码期望从中获取值的位置)