搭建一个考试系统,使其具有自动判卷,查询,统计等功能,代码书写
时间: 2023-10-16 13:09:51 浏览: 104
这是一个比较复杂的项目,需要设计合理的数据库结构和后端逻辑,以下是一个简单的代码示例:
1. 数据库设计
考试系统需要存储考生信息、试题信息、考试记录等数据,因此需要设计相应的表结构。这里给出一个简化的表结构示例:
```
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `exam` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`start_time` datetime NOT NULL,
`end_time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `question` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`exam_id` int(11) NOT NULL,
`content` text NOT NULL,
`answer` text NOT NULL,
PRIMARY KEY (`id`),
KEY `exam_id` (`exam_id`),
CONSTRAINT `question_ibfk_1` FOREIGN KEY (`exam_id`) REFERENCES `exam` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `record` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`exam_id` int(11) NOT NULL,
`score` int(11) NOT NULL,
`submit_time` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `exam_id` (`exam_id`),
CONSTRAINT `record_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `record_ibfk_2` FOREIGN KEY (`exam_id`) REFERENCES `exam` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
2. 后端代码
接下来是后端代码的示例,使用了Python的Flask框架:
```python
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@hostname/database'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
password = db.Column(db.String(50), nullable=False)
class Exam(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
start_time = db.Column(db.DateTime, nullable=False)
end_time = db.Column(db.DateTime, nullable=False)
class Question(db.Model):
id = db.Column(db.Integer, primary_key=True)
exam_id = db.Column(db.Integer, db.ForeignKey('exam.id', ondelete='CASCADE'), nullable=False)
content = db.Column(db.Text, nullable=False)
answer = db.Column(db.Text, nullable=False)
class Record(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False)
exam_id = db.Column(db.Integer, db.ForeignKey('exam.id', ondelete='CASCADE'), nullable=False)
score = db.Column(db.Integer, nullable=False)
submit_time = db.Column(db.DateTime, nullable=False)
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
user = User.query.filter_by(name=data['name'], password=data['password']).first()
if user:
return jsonify({'result': 'success'})
else:
return jsonify({'result': 'failure'})
@app.route('/exam', methods=['GET'])
def get_exams():
exams = Exam.query.all()
result = [{'id': exam.id, 'title': exam.title, 'start_time': exam.start_time, 'end_time': exam.end_time} for exam in exams]
return jsonify(result)
@app.route('/exam/<int:exam_id>/question', methods=['GET'])
def get_questions(exam_id):
questions = Question.query.filter_by(exam_id=exam_id).all()
result = [{'id': question.id, 'content': question.content} for question in questions]
return jsonify(result)
@app.route('/exam/<int:exam_id>/submit', methods=['POST'])
def submit_exam(exam_id):
data = request.get_json()
user_id = data['user_id']
answers = data['answers']
questions = Question.query.filter_by(exam_id=exam_id).all()
score = 0
for i, question in enumerate(questions):
if question.answer == answers[i]:
score += 1
record = Record(user_id=user_id, exam_id=exam_id, score=score, submit_time=datetime.now())
db.session.add(record)
db.session.commit()
return jsonify({'result': 'success', 'score': score})
if __name__ == '__main__':
app.run()
```
3. 前端界面
最后是前端界面的示例,使用了Bootstrap框架:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>考试系统</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>考试系统</h1>
<form id="login-form">
<div class="form-group">
<label for="name">用户名</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">登录</button>
</form>
<hr>
<div id="exam-list">
<h2>考试列表</h2>
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>标题</th>
<th>开始时间</th>
<th>结束时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div id="question-list">
<h2>试题列表</h2>
<div class="panel-group" id="accordion">
</div>
<button type="button" class="btn btn-primary" id="submit-btn" style="display: none;">提交</button>
</div>
</div>
<script>
$(function() {
$('#login-form').submit(function(event) {
event.preventDefault();
var name = $('#name').val();
var password = $('#password').val();
$.ajax({
url: '/login',
type: 'POST',
dataType: 'json',
data: JSON.stringify({name: name, password: password}),
contentType: 'application/json',
success: function(data) {
if (data.result == 'success') {
loadExams();
} else {
alert('登录失败');
}
},
error: function() {
alert('网络错误');
}
});
});
function loadExams() {
$.get('/exam', function(data) {
var tbody = $('#exam-list table tbody');
tbody.empty();
for (var i = 0; i < data.length; i++) {
var exam = data[i];
var tr = $('<tr></tr>');
tr.append($('<td></td>').text(exam.id));
tr.append($('<td></td>').text(exam.title));
tr.append($('<td></td>').text(exam.start_time));
tr.append($('<td></td>').text(exam.end_time));
var td = $('<td></td>');
var button = $('<button></button>').text('开始考试').addClass('btn btn-primary');
button.click(function(exam_id) {
return function() {
loadQuestions(exam_id);
}
}(exam.id));
td.append(button);
tr.append(td);
tbody.append(tr);
}
});
}
function loadQuestions(exam_id) {
$.get('/exam/' + exam_id + '/question', function(data) {
var accordion = $('#accordion');
accordion.empty();
for (var i = 0; i < data.length; i++) {
var question = data[i];
var panel = $('<div></div>').addClass('panel panel-default');
var heading = $('<div></div>').addClass('panel-heading');
var title = $('<h4></h4>').addClass('panel-title');
var link = $('<a></a>').attr('data-toggle', 'collapse').attr('data-parent', '#accordion')
.attr('href', '#collapse' + i).text(question.content);
title.append(link);
heading.append(title);
panel.append(heading);
var body = $('<div></div>').addClass('panel-collapse collapse').attr('id', 'collapse' + i);
var inner = $('<div></div>').addClass('panel-body');
inner.append($('<textarea></textarea>').addClass('form-control').attr('rows', '5').attr('name', 'answer-' + i));
body.append(inner);
panel.append(body);
accordion.append(panel);
}
$('#submit-btn').show();
$('#submit-btn').unbind('click').click(function() {
submitExam(exam_id);
});
});
}
function submitExam(exam_id) {
var answers = [];
$('#question-list textarea').each(function() {
answers.push($(this).val());
});
$.ajax({
url: '/exam/' + exam_id + '/submit',
type: 'POST',
dataType: 'json',
data: JSON.stringify({user_id: 1, answers: answers}),
contentType: 'application/json',
success: function(data) {
alert('得分:' + data.score);
},
error: function() {
alert('网络错误');
}
});
}
loadExams();
});
</script>
</body>
</html>
```
以上代码仅供参考,实际项目还需要进一步完善和优化。
阅读全文