软件部阶段性任务--flask与数据库篇 1

num_19 2024-10-31 21:01:34

前言

这是一个阶段性任务,请完成下列要求,并将完成结果以博客的方式展示(界面+代码)

 

任务

请在你们可爱的组长给的html页面与python框架中完成要求

 

要求

实现一个登录界面,用户名是123456,密码是123456

输对了就跳转到我给的另一个html页面

输出了会报错(这个我已经写好了,不用管这一步)

 

HTML页面(前端):

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>学生登录系统</title>
</head>
<body>
    <h2>学生登录</h2>
    <form id="loginForm">
        用户名: <input type="text" id="username"><br>
        密码: <input type="password" id="password"><br>
        <button type="button" onclick="login()">登录</button>
    </form>

    <script>
        function login() {
            var username = document.getElementById('username').value;
            var password = document.getElementById('password').value;

            // 这里使用fetch发送请求到后端进行验证
            fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            })
            .then(response => response.json())
            .then(data => {
                if(data.success) {
                    // 登录成功,跳转到学生主页
                    window.location.href = '/student-home';
                } else {
                    alert('用户名或密码错误');
                }
            })
            .catch(error => console.error('Error:', error));
        }
    </script>
</body>
</html>

test.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f7f7f7;
        }
        .container {
            max-width: 1200px;
            margin: auto;
            padding: 20px;
        }
        header {
            background: #3498db;
            color: #fff;
            padding: 20px 0;
            text-align: center;
        }
        header h1 {
            margin: 0;
        }
        .card {
            background: #fff;
            margin-bottom: 20px;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .card h2 {
            margin-top: 0;
            color: #3498db;
        }
        form label {
            display: block;
            margin: 10px 0 5px;
            color: #555;
        }
        form input[type="text"],
        form input[type="number"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        form input[type="submit"] {
            background: #3498db;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        form input[type="submit"]:hover {
            background: #2980b9;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #3498db;
            color: white;
        }
        tr:hover {
            background-color: #f1f1f1;
        }
        footer {
            background: #333;
            color: #fff;
            text-align: center;
            padding: 10px 0;
            position: fixed;
            bottom: 0;
            width: 100%;
        }
    </style>
</head>
<body>
    <header>
        <div class="container">
            <h1>学生管理系统</h1>
        </div>
    </header>

    <div class="container">
        <div class="card">
            <h2>添加学生信息</h2>
            <form id="addStudentForm">
                <label for="studentId">学号:</label>
                <input type="text" id="studentId" name="studentId">

                <label for="studentName">姓名:</label>
                <input type="text" id="studentName" name="studentName">

                <label for="studentAge">年龄:</label>
                <input type="number" id="studentAge" name="studentAge">

                <input type="button" value="添加学生" onclick="addStudent()">
            </form>
        </div>

        <div class="card">
            <h2>修改学生信息</h2>
            <form id="editStudentForm">
                <label for="editStudentId">学号:</label>
                <input type="text" id="editStudentId" name="editStudentId">

                <label for="editStudentName">姓名:</label>
                <input type="text" id="editStudentName" name="editStudentName">

                <label for="editStudentAge">年龄:</label>
                <input type="number" id="editStudentAge" name="editStudentAge">

                <input type="button" value="修改学生" onclick="editStudent()">
            </form>
        </div>

        <div class="card">
            <h2>删除学生信息</h2>
            <form id="deleteStudentForm">
                <label for="deleteStudentId">学号:</label>
                <input type="text" id="deleteStudentId" name="deleteStudentId">

                <input type="button" value="删除学生" onclick="deleteStudent()">
            </form>
        </div>

        <div class="card">
            <h2>查询学生信息</h2>
            <form id="queryStudentForm">
                <label for="queryStudentId">学号:</label>
                <input type="text" id="queryStudentId" name="queryStudentId">

                <input type="button" value="查询学生" onclick="queryStudent()">
            </form>
            <table id="studentsTable" class="table">
                <thead>
                    <tr>
                        <th>学号</th>
                        <th>姓名</th>
                        <th>年龄</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 学生数据将在这里动态插入 -->
                </tbody>
            </table>
        </div>
    </div>

    <footer>
        <p>学生管理系统 &copy; 2024</p>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function addStudent() {
            var data = {
                id: document.getElementById('studentId').value,
                name: document.getElementById('studentName').value,
                age: document.getElementById('studentAge').value
            };
            fetch('/api/add_student', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            })
            .then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                // 清空表单
                document.getElementById('addStudentForm').reset();
            })
            .catch((error) => {
                console.error('Error:', error);
            });
        }

        function editStudent() {
            var data = {
                id: document.getElementById('editStudentId').value,
                name: document.getElementById('editStudentName').value,
                age: document.getElementById('editStudentAge').value
            };
            fetch('/api/edit_student', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            })
            .then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                // 清空表单
                document.getElementById('editStudentForm').reset();
            })
            .catch((error) => {
                console.error('Error:', error);
            });
        }

        function deleteStudent() {
            var studentId = document.getElementById('deleteStudentId').value;
            fetch('/api/delete_student', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ id: studentId }),
            })
            .then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                // 清空表单
                document.getElementById('deleteStudentForm').reset();
            })
            .catch((error) => {
                console.error('Error:', error);
            });
        }

        function queryStudent() {
            var studentId = document.getElementById('queryStudentId').value;
            fetch('/api/query_student', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ id: studentId }),
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log('Success:', data);
                // 确保每次都清空表格
                var table = document.getElementById('studentsTable').getElementsByTagName('tbody')[0];
                table.innerHTML = ''; // 清空表格
        
                // 检查返回的数据是否有效
                if (data && data.id && data.id.length > 0) {
                    var len = data.id.length;
                    for (let i = 0; i < len; i++) {
                        var row = table.insertRow(i);
                        var cell1 = row.insertCell(0);
                        var cell2 = row.insertCell(1);
                        var cell3 = row.insertCell(2);
                        cell1.innerHTML = data.id[i];
                        cell2.innerHTML = data.name[i];
                        cell3.innerHTML = data.age[i];
                    }
                } else {
                    // 没有找到学生时的处理
                    var row = table.insertRow(0);
                    var cell = row.insertCell(0);
                    cell.setAttribute('colspan', '3');
                    cell.innerHTML = 'No students found.';
                }
            })
            .catch((error) => {
                console.error('Error:', error);
                // 显示错误信息
                var table = document.getElementById('studentsTable').getElementsByTagName('tbody')[0];
                table.innerHTML = '<tr><td colspan="3">Error loading student data: ' + error.message + '</td></tr>';
            });
        }
    </script>
</body>
</html>

Python代码框架(后端):

index.py

from flask import Flask, request, jsonify, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

@app.route('/')
def main():
    return render_template('index.html')


#---------------------------------
#在这里写代码






#---------------------------------

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

 

README(这只是个说明):

index.html 的登录按钮会发送用户名和密码两个信息,会以{
    'username':'123456',
    'password':'123456'
}
的json格式以post的访问方式访问 '/login' 这个路由

'/login'路由的返回值如下:
登录成功就 return {'success': True}
登录失败就 return {'success': False}

!!!所有数据请均用json收发

index.html会在登录成功后访问 '/student-home' 这个路由
请你返回 test.html 作为回应,

就像我们访问 '/' 这个路由时,
我们会返回 index.html一样


所以你们要按照要求来编写 '/login' 和 '/student-home' 这两个路由

文件框架如下:

templates文件夹(自己创建)与index.py在同一级,index.html与test.html在templates下 ,这点尤其重要,不然index.py会找不到网页

如何建立???:

ctrl +c ,ctrl +v 上面的两个html代码 和 index.py初始框架

最好在给好的index.py框架中写代码,不然的话可能会弹不出网页

 

如何展示你们的成果???

看下面

 

 

就可以发帖了

 

帖子格式:

 

标题:xxxxx

任务内容:xxxxxxx

代码:xxxxx

呈现效果:xxxxx

 

1.这个任务中:index.py的代码请务必展示出来

2.呈现效果可以截图一些你们觉得具有代表性的,看个人喜好

 

附加内容:

这个是我们写的相关教程(文档)

flask:https://bbs.csdn.net/topics/619384791

数据库:https://bbs.csdn.net/topics/619386272

 

 

如果你们不喜欢看文档,也可以看视频

三个小时的:

https://www.bilibili.com/video/BV1pa4y117iE/?buvid=XXA80F6AA6BD0338E86160B365B03D7E6BC51&from_spmid=main.my-history.0.0&is_story_h5=false&mid=R4iIMhInfhtNHKdX7y138Q%3D%3D&p=22&plat_id=116&share_from=ugc&share_medium=android&share_plat=android&share_session_id=ff1b8d81-0f5c-4d3a-be24-8d9a55a2bdd4&share_source=WEIXIN&share_tag=s_i&spmid=united.player-video-detail.0.0&timestamp=1730466252&unique_k=5YnaC3s&up_id=3546600301398045

更长时间的:

https://www.bilibili.com/video/BV17r4y1y7jJ/?buvid=XXA80F6AA6BD0338E86160B365B03D7E6BC51&from_spmid=main.my-history.0.0&is_story_h5=false&mid=R4iIMhInfhtNHKdX7y138Q%3D%3D&p=14&plat_id=116&share_from=ugc&share_medium=android&share_plat=android&share_session_id=477050fd-9cae-4a2a-9c88-42b6675e4d24&share_source=WEIXIN&share_tag=s_i&spmid=united.player-video-detail.0.0&timestamp=1730466293&unique_k=65S58M1&up_id=349929259

 

这未必是就最好的,因人而异,重点是自主学习的能力

 

json是什么?:

戳我:https://www.runoob.com/json/json-tutorial.html

 

 

...全文
526 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

40

社区成员

发帖
与我相关
我的任务
社区描述
开放原子开源深大社团,致力于推动开源文化普及,培育和发掘开源人才,繁荣校园开源生态。
harmonyos经验分享 高校 广东省·深圳市
社区管理员
  • 趴抖
  • 辰风已久
  • num_19
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧