Browse Source

125454

master
lichong 9 months ago
parent
commit
44a773a05f
  1. 79
      api/main.py
  2. 1
      front/package.json
  3. 26
      front/src/api/student.js
  4. 0
      front/src/api/teacher.js
  5. 20
      front/src/component/table.vue
  6. 1
      front/src/plugins/axios.js
  7. 16
      front/src/router/index.js
  8. 2
      front/src/views/home.vue
  9. 8
      front/src/views/login.vue
  10. 171
      front/src/views/student.vue
  11. 25
      front/src/views/teacher.vue
  12. 22
      test.py

79
api/main.py

@ -11,53 +11,47 @@ app = Flask(__name__)
client = MongoClient("mongodb://localhost:27019/")
db = client["back"]
collection = db["users"]
# sockitIo
socketio = SocketIO()
# 解决跨域问题
socketio.init_app(app, cors_allowed_origins="*")
# sockitIo解决跨域问题
socketMsg = SocketIO(app, cors_allowed_origins="*")
socketVedio = SocketIO(app, cors_allowed_origins="*")
# 用来存放客户端的 sid,即 session id
# 可以不单独定义字典存放 sid与namespace,flask-socketio 默认将 sid 存放在 room 中
socket_pool = {}
# Websocket 通过namespace 和 sid 标识具体客户端
# 第一个 Websocket 类
# 第一个 Websocket 类用于聊天
class MyCustomNamespace(Namespace):
name_space = "/msg"
# 连接成功调用的方法
def on_connect(self):
global socket_pool
print("connect..")
print("-----------------")
print(self.server.manager)
print(self.socketio)
print("-----------------")
print(request.namespace)
socket_pool[request.sid] = self.name_space
print(socket_pool)
print(1, socket_pool)
print(2, "Client connected")
print(3, "-----------------")
# 断开连接调用的方法
def on_disconnect(self):
global socket_pool
print("disconnect...")
print(4, "disconnect...")
del socket_pool[request.sid]
print(socket_pool)
print(5, socket_pool)
# 往 接收客户端标消息识为 'message' 的方法
def on_message(self, data):
print(data)
print(6, data)
# 把消息发送到客户端的 'response' 标识的方法中, 一般是 on_response()
emit("response", "123", to=request.sid)
print("--------------")
print(request.sid)
print("--------------")
print(socketio.server.manager.rooms)
print(7, "--------------")
print(8, request.sid)
print(9, "--------------")
print(10, socketio.server.manager.rooms)
# 往 接收客户端标消息识为 'hello' 的方法
def on_hello(self, data):
print("hello world")
print(11, "hello world")
# 发送消息
def send(self, data):
@ -68,26 +62,26 @@ class MyCustomNamespace(Namespace):
# 为了详细展示不同类,这里就不做继承
# 第二个 Websocket 类
# 第二个 Websocket 类用于视频
class MyCustomNamespace1(Namespace):
name_space = "/vedio"
def on_connect(self):
global socket_pool
print("connect..")
print(request.namespace)
print(12, "connect..")
print(13, request.namespace)
socket_pool[request.sid] = self.name_space
print(socket_pool)
print(14, socket_pool)
def on_disconnect(self):
global socket_pool
print("disconnect...")
print(15, "disconnect...")
del socket_pool[request.sid]
print(socket_pool)
print(16, socket_pool)
def on_message(self, data):
print(data)
print(17, data)
emit("response", "123")
self.send("asd")
@ -96,12 +90,16 @@ class MyCustomNamespace1(Namespace):
emit("response", data, namespace=self.name_space)
socketMsg.on_namespace(MyCustomNamespace("/msg"))
socketVedio.on_namespace(MyCustomNamespace("/vedio"))
@app.route("/sendMsg")
def sendMsg():
for sid, namespace_value in socket_pool.items():
print(sid)
print(18, sid)
emit("response", "123456", namespace=namespace_value, to=sid)
print("ok")
print(19, "ok")
return "ok"
@ -188,10 +186,11 @@ def insert_data():
# 获取到POST过来的数据,转为json形式
userJson = json.loads(resData)
admin = isAdmin(userJson["id"])
print(777, userJson, admin)
if admin:
if userJson["subType"] is "add":
_id = ObjectId()
print(77337, str(_id))
userItem = {
"_id": _id,
"xuexiaomingcheng": userJson["xuexiaomingcheng"],
"xuexiaodaihao": userJson["xuexiaodaihao"],
"zhuanyemingcheng": userJson["zhuanyemingcheng"],
@ -206,7 +205,7 @@ def insert_data():
"kaoshileixing": userJson["kaoshileixing"],
"kaoshikemu": userJson["kaoshikemu"],
"kaoshishijianduan": userJson["kaoshishijianduan"],
"kaoshilianjie": "", # 需要自动生成一个链接
"kaoshilianjie": "/student/" + str(_id), # 需要自动生成一个链接
"isAdmin": 0,
"isExit": 1,
"chuangjianshijian": time.strftime(
@ -244,7 +243,15 @@ def query_data():
"hasError": False,
}
else:
return {"code": 200, "msg": "您不是管理员用户", "list": [], "hasError": True}
mongoId = ObjectId(userJson["id"])
userObj = collection.find_one({"_id": mongoId, "isExit": 1})
userObj["_id"] = str(userObj["_id"]) # 将ObjectId转换为字符串
return {
"code": 200,
"msg": "查询成功",
"list": [userObj],
"hasError": False,
}
# 更新用户
@ -324,4 +331,6 @@ def updatePassword():
if __name__ == "__main__":
initData()
app.run(debug=True)
# app.run(debug=True)
socketMsg.run(app, debug=True)
# socketVedio.run(app, debug=True)

1
front/package.json

@ -17,6 +17,7 @@
"nprogress": "^0.2.0",
"papaparse": "^5.4.1",
"qs": "^6.11.2",
"socket.io-client": "^4.7.5",
"sqids": "^0.3.0",
"unplugin-auto-import": "^0.17.4",
"unplugin-vue-components": "^0.26.0",

26
front/src/api/student.js

@ -0,0 +1,26 @@
import _axios from "@/plugins/axios";
//修改用户
export function updateUser(data) {
return _axios({
url: `/v1/updateUser`,
method: "POST",
data: { id: localStorage.getItem("userId"), ...data },
});
}
//查找用户
export function getUser(data) {
return _axios({
url: `/v1/getUser`,
method: "POST",
data: { id: localStorage.getItem("userId"), ...data },
});
}
//修改密码
export function updatePassword(data) {
return _axios({
url: `/v1/updatePassword`,
method: "POST",
data: { id: localStorage.getItem("userId"), ...data },
});
}

0
front/src/api/user.js → front/src/api/teacher.js

20
front/src/component/table.vue

@ -15,6 +15,16 @@
<template v-else-if="headerItem.type === 'array'">
{{ $_.join(scope.row[headerItem.prop], ",") }}
</template>
<template v-else-if="headerItem.type === 'datetimerange'">
{{ _.join(scope.row[headerItem.prop], "——") }}
</template>
<template v-else-if="headerItem.type === 'link'">
<el-link :underline="false" :href="`${baseUrl}${scope.row[headerItem.prop]}`" target="_blank"
v-if="_.trim(scope.row[headerItem.prop])">
{{ scope.row[headerItem.prop] }}
</el-link>
<span v-else></span>
</template>
<template v-else-if="headerItem.type === 'password'"> ****** </template>
<template v-else>
{{ scope.row[headerItem.prop] }}
@ -43,6 +53,7 @@
</el-table>
</template>
<script>
import _ from "lodash"
export default {
name: "app",
emits: ["detailInfo", "editInfo"],
@ -65,9 +76,14 @@ export default {
},
},
data() {
return {};
return {
_: _,
baseUrl: "",
};
},
async mounted() {
this.baseUrl = window.location.origin
},
async mounted() { },
methods: {
detailInfo(item) {
this.$emit("detailInfo", item);

1
front/src/plugins/axios.js

@ -1,6 +1,5 @@
import axios from "axios";
import qs from "qs";
import router from "@/router/index.js";
let config = {
baseURL: "",
timeout: 600 * 1000,

16
front/src/router/index.js

@ -6,13 +6,19 @@ const routes = [
path: "/",
name: "home",
component: home,
redirect: "/user",
redirect: "/teacher",
children: [
{
path: "user",
name: "user",
component: () => import("../views/user.vue"),
},]
path: "teacher",
name: "teacher",
component: () => import("../views/teacher.vue"),
},
{
path: "student/:id",
name: "student",
component: () => import("../views/student.vue"),
}
]
},
{
path: "/login",

2
front/src/views/home.vue

@ -46,7 +46,7 @@ export default {
}
this.userName = localStorage.getItem("userName")
let isAdmin = localStorage.getItem("isAdmin")
if (isAdmin) {
if (isAdmin === "1") {
this.avatarUrl = teacher
} else {
this.avatarUrl = student

8
front/src/views/login.vue

@ -30,7 +30,7 @@
<script>
import {
loginFun, //
} from "@/api/user";
} from "@/api/teacher";
import md5 from "md5"
export default {
name: "login",
@ -65,7 +65,11 @@ export default {
localStorage.setItem("userId", this.$_.get(res, ["list", 0, "_id"], ""))
localStorage.setItem("userName", this.$_.get(res, ["list", 0, "xueshengxingming"], ""))
localStorage.setItem("isAdmin", this.$_.get(res, ["list", 0, "isAdmin"], 0))
this.$router.push("/user")
if (this.$_.get(res, ["list", 0, "isAdmin"], 0)) {
this.$router.push("/teacher")
} else {
this.$router.push("/student")
}
} else {
ElMessage.error(res.msg);
localStorage.clear()

171
front/src/views/student.vue

@ -0,0 +1,171 @@
<template>
<el-row :gutter="20">
<el-col :span="6">
<el-card>
<template #header>
<div>
<span>考生信息</span>
</div>
</template>
<p v-for="(userItem, userIndex) in userInfo" :key="userIndex">
<template v-if="userItem.type === 'datetimerange'">
<div>
<span>{{ userItem.lable }}</span>
<span>{{ _.join(userData[userItem.prop], "——") }}</span>
</div>
</template>
<template v-else-if="userItem.type === 'text'">
<div>
<span>{{ userItem.lable }}</span>
<span>{{ userData[userItem.prop] }}</span>
</div>
</template>
</p>
<template #footer>
<el-button type="primary" @click="connectTeacher">联系老师</el-button>
</template>
</el-card>
</el-col>
<el-col :span="6">
<el-card>
<template #header>
<div>
<span>实时作弊信息</span>
</div>
</template>
<p>实时作弊信息</p>
</el-card>
</el-col>
<el-col :span="12">
视频
</el-col>
</el-row>
</template>
<script>
import _ from "lodash";
import { io } from "socket.io-client";
import {
getUser, //user
} from "@/api/student";
export default {
name: "student",
components: {},
data() {
return {
_: _,
userId: "",
// ,
userInfo: [
{
lable: "学校名称",
prop: "xuexiaomingcheng",
type: "text"
},
{
lable: "学校代号",
prop: "xuexiaodaihao",
type: "text"
},
{
lable: "专业名称",
prop: "zhuanyemingcheng",
type: "text"
},
{
lable: "专业代号",
prop: "zhuanyedaihao",
type: "text"
},
{
lable: "年级",
prop: "nianji",
type: "text"
},
{
lable: "班级",
prop: "banji",
type: "text"
},
{
lable: "学生姓名",
prop: "xueshengxingming",
type: "text"
},
{
lable: "学号",
prop: "xuehao",
type: "text"
},
{
lable: "考试类型",
prop: "kaoshileixing",
type: "text"
},
{
lable: "考试科目",
prop: "kaoshikemu",
type: "text"
},
{
lable: "考试时间段",
prop: "kaoshishijianduan",
type: "datetimerange"
},
],
userData: {},
socketMsg: io("http://localhost:3000/msg"),
socketVedio: io("http://localhost:3000/vedio")
};
},
watch: {},
computed: {},
async mounted() {
this.userId = _.get(this.$route, ["params", "id"], "")
await this.getUser()
this.initMsg()
},
methods: {
async getUser() {
let res = await getUser({
id: this.userId
})
this.userData = res.list[0]
},
initMsg() {
this.socketMsg.on("connect", (data) => {
console.log(data);
});
this.socketMsg.on("data", (data) => {
console.log(data);
});
this.socketMsg.on("disconnect", (data) => {
console.log(data);
});
this.socketMsg.on('response', (data) => {
this.messages.push({ id: Date.now(), text: data.data });
});
},
initVedio() {
this.socketVedio.on("connect", (data) => {
console.log(data);
});
this.socketVedio.on("data", (data) => {
console.log(data);
});
this.socketVedio.on("disconnect", (data) => {
console.log(data);
});
this.socketVedio.on('response', (data) => {
this.messages.push({ id: Date.now(), text: data.data });
});
},
connectTeacher() {
this.socketMsg.emit('message', "this.message");
}
},
beforeUnmount() { },
};
</script>
<style scoped></style>

25
front/src/views/user.vue → front/src/views/teacher.vue

@ -47,9 +47,9 @@ import {
updateUser, //user
getUser, //user
updatePassword,//
} from "@/api/user";
} from "@/api/teacher";
export default {
name: "user",
name: "teacher",
components: { vueTable, changeItem },
data() {
return {
@ -60,14 +60,14 @@ export default {
prop: "xuexiaomingcheng",
label: "学校名称",
type: "text",
tableShow: true,
tableShow: false,
formShow: true
},
{
prop: "xuexiaodaihao",
label: "学校代号",
type: "text",
tableShow: true,
tableShow: false,
formShow: true
},
{
@ -81,14 +81,14 @@ export default {
prop: "zhuanyedaihao",
label: "专业代号",
type: "text",
tableShow: true,
tableShow: false,
formShow: true
},
{
prop: "nianji",
label: "年级",
type: "text",
tableShow: true,
tableShow: false,
formShow: true
},
{
@ -116,7 +116,7 @@ export default {
prop: "mima",
label: "密码",
type: "text",
tableShow: true,
tableShow: false,
formShow: true
},
{
@ -130,7 +130,7 @@ export default {
prop: "zuobiqingkuang",
label: "作弊情况",
type: "text",
tableShow: true,
tableShow: false,
formShow: true
},
{
@ -147,6 +147,13 @@ export default {
tableShow: true,
formShow: true
},
{
prop: "kaoshilianjie",
label: "考试链接",
type: "link",
tableShow: true,
formShow: true
},
{
prop: "kaoshishijianduan",
label: "考试时间段",
@ -282,7 +289,7 @@ export default {
cancelButtonText: "取消",
type: "error",
}).then(async () => {
let res = await delUser({ subType: "del", ids: delData });
let res = await delUser({ ids: delData });
await this.init();
ElMessage({
message: res.msg,

22
test.py

@ -0,0 +1,22 @@
from flask import Flask, render_template
from flask_socketio import SocketIO, emit, Namespace
from threading import Thread, Event
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins="*")
class MyCustomNamespace(Namespace):
def on_connect(self):
print('Client connected')
def on_disconnect(self):
print('Client disconnected')
def on_message(self, message):
emit('response', {'data': 'Got it!'}, broadcast=True)
socketio.on_namespace(MyCustomNamespace('/test'))
if __name__ == '__main__':
socketio.run(app, debug=True)
Loading…
Cancel
Save