This commit is contained in:
30404 2024-07-03 14:08:43 +08:00
parent c1dc6dc9f7
commit 3219a1ac95
17 changed files with 254 additions and 151 deletions

View File

@ -62,3 +62,7 @@
margin-top: -12px; margin-top: -12px;
color: #525252; color: #525252;
} }
#TF{
position: absolute;
margin-left: 1200px;
}

View File

@ -9,6 +9,7 @@ import axios from 'axios';
// //
function Marking(){ function Marking(){
const teacher_ID=localStorage.getItem('islogin') const teacher_ID=localStorage.getItem('islogin')
const currentTime = new Date().toLocaleString()
if(teacher_ID==null){ if(teacher_ID==null){
alert('登录过期,请重新登录') alert('登录过期,请重新登录')
window.location.href='http://36.138.114.105:30294/' window.location.href='http://36.138.114.105:30294/'
@ -59,10 +60,6 @@ function Marking(){
const ClassChange=(event)=>{ const ClassChange=(event)=>{
setClassID(event.target.value) setClassID(event.target.value)
} }
const click=()=>{
console.log(ClassID);
console.log(MarkData);
}
return( return(
<div className='body-right-mark'> <div className='body-right-mark'>
@ -80,13 +77,13 @@ function Marking(){
<img src={Test} alt="" width='35px' height='35px'/> <img src={Test} alt="" width='35px' height='35px'/>
<p> <p>
<p className='p-mark'><span>实训ID:{MarkData[key][0][10]}</span>{eval(MarkData[key][0][11])}</p> <p className='p-mark'><span>实训ID:{MarkData[key][0][10]}</span>{eval(MarkData[key][0][11])}</p>
<span>{MarkData[key][0][6]}</span><span></span> <div id='TF'>{MarkData[key][0][6]>currentTime?'未开始':''}</div>
<span>{MarkData[key][0][6]}</span>
</p> </p>
</li> </li>
</Link> </Link>
))} ))}
</ul> </ul>
<button onClick={click}>asda</button>
</div>} </div>}
</div> </div>
) )

View File

@ -9,8 +9,22 @@ function StudentLink(){
const testID=useParams()['key'] const testID=useParams()['key']
const sumbitScore=async()=>{
try{
const sumbitScoreSrc=await axios.post('/api/teacher/UpdateTest',{
score,
testID
})
}catch{
alert('提交出错')
}
}
const submit=()=>{ const submit=()=>{
console.log(TestLink); console.log('a');
sumbitScore()
alert('批改成功')
window.location.href='http://localhost:3000/teacher/mark'
} }
const [TestLink,setTestLink]=useState() const [TestLink,setTestLink]=useState()
@ -28,6 +42,15 @@ function StudentLink(){
NotMarkTestFunc() NotMarkTestFunc()
},[]) },[])
const [score,setscore]=useState([])
const handleInputChange = (event) => {
const { name, value } = event.target;
setscore({
...score,
[name]: value
});
}
return( return(
<div className='body-right-studentlink'> <div className='body-right-studentlink'>
<table> <table>
@ -42,8 +65,8 @@ function StudentLink(){
{Object.keys(TestLink).map((key)=>( {Object.keys(TestLink).map((key)=>(
<tr key={key}> <tr key={key}>
<td>{key}</td> <td>{key}</td>
<td><Link to={TestLink[key][6]}>{TestLink[key][6]}</Link></td> <td><Link to={TestLink[key][6]} target="_blank">{TestLink[key][6]}</Link></td>
<td><input type="text" name="" id="" /></td> <td><input type="text" onChange={handleInputChange} name={TestLink[key][0]}/></td>
</tr> </tr>
))} ))}
</tbody>} </tbody>}

View File

@ -5,11 +5,11 @@ import { useLocation } from 'react-router-dom';
import io, { Socket } from "socket.io-client"; import io, { Socket } from "socket.io-client";
export default function WebSSH({ ip = "10.233.183.99", port = "22", password = "123456", user = "dmdba" }) { export default function Test({ ip = "10.106.152.68", port = "22", password = "123456", user = "dmdba" }) {
const location = useLocation(); const location = useLocation();
const terminalObj = useRef<HTMLDivElement | null>(null); const terminalObj = useRef(null);
const [terminal, setTerminal] = useState<Terminal | null>(null); const [terminal, setTerminal] = useState(null);
const [socket, setSocket] = useState<Socket | null>(null); const [socket, setSocket] = useState(null);
useEffect(() => { useEffect(() => {
if (terminal === null) { if (terminal === null) {
@ -19,7 +19,7 @@ export default function WebSSH({ ip = "10.233.183.99", port = "22", password = "
useEffect(() => { useEffect(() => {
if (terminal !== null) { if (terminal !== null) {
terminal.open(terminalObj.current as HTMLDivElement); terminal.open(terminalObj.current);
const newSocket = io("ws://36.138.114.105:32087"); const newSocket = io("ws://36.138.114.105:32087");
setSocket(newSocket); setSocket(newSocket);
@ -38,7 +38,7 @@ export default function WebSSH({ ip = "10.233.183.99", port = "22", password = "
newSocket.emit("heartbeat"); newSocket.emit("heartbeat");
}, 1000); }, 1000);
newSocket.on("output", (data: string) => { newSocket.on("output", (data) => {
terminal.write(data); terminal.write(data);
}); });
@ -54,7 +54,7 @@ export default function WebSSH({ ip = "10.233.183.99", port = "22", password = "
} }
}, [socket, ip, port, password, user]); }, [socket, ip, port, password, user]);
function pasteContent(event: React.MouseEvent) { function pasteContent(event) {
navigator.clipboard.readText().then((content) => { navigator.clipboard.readText().then((content) => {
socket?.emit("input", content); socket?.emit("input", content);
}); });

View File

@ -1,15 +1,33 @@
import axios from 'axios';
import './Trainmanage.css' import './Trainmanage.css'
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
// import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
// import axios from 'axios'; // import axios from 'axios';
function TrainManage(){ function TrainManage(){
const teacher_ID=localStorage.getItem('islogin')
const [Data,setData]=useState()
//
const getTrainfunc=async()=>{
try{
const getTrainSrc=await axios.post('/api/teacher/getTrain',{
teacher_ID,
})
setData(getTrainSrc.data['data'])
}catch{
alert('aaaa')
}
}
useEffect(()=>{
getTrainfunc()
},[])
return( return(
<div className='body-trainmanage'> <div className='body-trainmanage'>
<p>已批改的试卷</p> <p>已批改的试卷</p>
<div className='line'></div> <div className='line'></div>
<div className='train-list-trainmanage'> {Data&&<div className='train-list-trainmanage'>
<ul className='ul1-trainmanage'> <ul className='ul1-trainmanage'>
<li> <li>
<span>111</span> <span>111</span>
@ -31,7 +49,10 @@ function TrainManage(){
</li> </li>
</ul> </ul>
<Link to='/teacher/SendTrain' className='sendtestpage'>前往发布实训</Link> <Link to='/teacher/SendTrain' className='sendtestpage'>前往发布实训</Link>
</div> </div>}
<button onClick={()=>{
console.log(Data);
}}></button>
</div> </div>
) )
} }

View File

@ -12,21 +12,11 @@ import { max, min } from 'lodash';
// //
function Home(){ function Home(){
const [isChecked,setisChecked]=useState(false) const [isChecked,setisChecked]=useState(false)
// const student_ID=localStorage.getItem('islogin')
// useEffect(()=>{ if(student_ID==null){
// if (!isChecked){ window.location.href='http://localhost:3000/signin'
// const is_login=localStorage.getItem('islogin') alert('未登录,请前往登录')
// if(!is_login){ }
// alert('')
// window.location.href='/signin'
// }else{
// console.log(is_login);
// console.log('');
// setisChecked(true)
// }
// //login
// }
// },[]);//
// //
const [lesson, setLesson] = useState([]); const [lesson, setLesson] = useState([]);

View File

@ -8,6 +8,7 @@ import moment from 'moment';
// //
function SubjectPage(){ function SubjectPage(){
const student_ID=localStorage.getItem('islogin') const student_ID=localStorage.getItem('islogin')
if(student_ID==null){ if(student_ID==null){
alert('登录过期,请重新登录') alert('登录过期,请重新登录')
window.location.href='http://36.138.114.105:30294/' window.location.href='http://36.138.114.105:30294/'
@ -33,11 +34,6 @@ function SubjectPage(){
test() test()
},[]) },[])
const click=()=>{
console.log(testdata);
console.log(FalseData);
console.log(NotFalse);
}
return( return(
<div className="body"> <div className="body">
@ -68,7 +64,6 @@ function SubjectPage(){
</div> </div>
))} ))}
</div> </div>
<button>更多历史</button>
{ NotFalse&& result&&<div className='test-subject'> { NotFalse&& result&&<div className='test-subject'>
{Object.keys(NotFalse).map((key)=>{ {Object.keys(NotFalse).map((key)=>{
return( return(

View File

@ -9,7 +9,7 @@ import arrowright from '../img/arrowright.jpg'
import bottom from '../img/bottom.jpg' import bottom from '../img/bottom.jpg'
import top from '../img/top.jpg' import top from '../img/top.jpg'
import axios from 'axios'; import axios from 'axios';
import Test from '../../../TeacherPages/TestManage/Test';
function Operation2() { function Operation2() {
const student_ID=localStorage.getItem('islogin') const student_ID=localStorage.getItem('islogin')
const { operateID } = useParams(); const { operateID } = useParams();
@ -32,8 +32,6 @@ function Operation2() {
} }
// //
const terminalObj = useRef(null);
let sock = null;
const [terminal, setTerminal] = useState(null); const [terminal, setTerminal] = useState(null);
useEffect(()=>{ useEffect(()=>{
@ -42,7 +40,6 @@ function Operation2() {
Train1() Train1()
setisTrue(true) setisTrue(true)
if (terminal == null){ if (terminal == null){
setTerminal(new Terminal({ setTerminal(new Terminal({
cols: 80, cols: 80,
@ -63,52 +60,6 @@ function Operation2() {
} }
// useEffect(() => {
// if (terminal == null){
// setTerminal(new Terminal({
// cols: 80,
// rows: 27,
// fontSize: 23
// }));
// }
// }, [])
// useEffect(() => {
// if (terminal != null){
// terminal.open(terminalObj.current );
// // sock = new WebSocket("ws://192.168.0.40:8765");
// sock = new WebSocket(Src);
// terminal.onData((data) => {
// sock?.send(data);
// });
// terminal.onSelectionChange((a, b) => {
// if (terminal.hasSelection()){
// navigator.clipboard.writeText(terminal.getSelection());
// }
// })
// setInterval(() => {
// sock?.send("heartbeat");
// }, 1000);
// sock.addEventListener("message", function (event) {
// console.log(event.data);
// terminal.write(event.data);
// });
// }
// }, [terminal])
function pasteContent(event) {
navigator.clipboard.readText().then((content) =>{
sock?.send(content);
})
event.preventDefault();
}
//
const DEL=()=>{
//
}
// //
// const { OperationId } = useParams(); // const { OperationId } = useParams();
const [countdown, setCountdown] = useState(0); const [countdown, setCountdown] = useState(0);
@ -203,7 +154,9 @@ function Operation2() {
{ isTrue&&TrainData&& { isTrue&&TrainData&&
<div> <div>
<p>{TrainData['operateID'][3][0]}</p> <p>{TrainData['operateID'][3][0]}</p>
<div style={{width: "1430px",position:'absolute',right:'0'}} ref={terminalObj} onContextMenu={pasteContent}></div> <Test/>
<div className=''><button>检测</button></div>
</div>} </div>}
{/* 达梦数据库连接⬆ */} {/* 达梦数据库连接⬆ */}

View File

@ -26,11 +26,7 @@ import Marking from '../TeacherPages/MarkingPages/Marking';
import SendTrain from '../TeacherPages/Trainmanage/SendTrain' import SendTrain from '../TeacherPages/Trainmanage/SendTrain'
import TrainManage from '../TeacherPages/Trainmanage/Trainmanage' import TrainManage from '../TeacherPages/Trainmanage/Trainmanage'
import StudentLink from '../TeacherPages/MarkingPages/StudentLink'; import StudentLink from '../TeacherPages/MarkingPages/StudentLink';
import Test from '../TeacherPages/TestManage/Test.tsx' import Test from '../TeacherPages/TestManage/Test';
import SendTrain from '../TeacherPages/Trainmanage/SendTrain';
import TrainManage from '../TeacherPages/Trainmanage/Trainmanage';
// (exam)使 // (exam)使
const MainLayout = ({ headerNav:HeaderNav }) => { const MainLayout = ({ headerNav:HeaderNav }) => {
return ( return (

View File

@ -4,7 +4,7 @@ module.exports = function(app) {
app.use( app.use(
'/api', // 如果请求路径匹配'/api',则进行代理 '/api', // 如果请求路径匹配'/api',则进行代理
createProxyMiddleware({ createProxyMiddleware({
target: 'http://127.0.0.1:5000', // 目标后端服务地址 target: 'http://36.138.114.105:32087/', // 目标后端服务地址
changeOrigin: true, changeOrigin: true,
}) })
); );

View File

@ -12,6 +12,8 @@ from flask import Flask, render_template, request, jsonify, send_from_directory,
from flask_cors import CORS from flask_cors import CORS
from flask_socketio import SocketIO, emit, disconnect from flask_socketio import SocketIO, emit, disconnect
import logging import logging
import os
print(os.getcwd())
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__, static_folder="public") app = Flask(__name__, static_folder="public")
CORS(app) CORS(app)
@ -257,11 +259,14 @@ def SendTrainTest():
TrainJudge=data['TrainJudge'] TrainJudge=data['TrainJudge']
Hour=data['HourValue'] Hour=data['HourValue']
Min=data['MinValue'] Min=data['MinValue']
StopTime=data['StopTime'] startTime=convert_iso_to_database_format(data['startDate'])
endTime=convert_iso_to_database_format(data['endDate'])
Class=data['selectedItems'] Class=data['selectedItems']
Train=data['Train'] Train=data['Train']
teacher_id=data['teacher_ID'] teacher_id=data['teacher_ID']
SendTrainTestFunc(TrainChoice, TrainCompletion, TrainJudge, Hour, Min, StopTime,Class,Train,teacher_id) SendTrainTestFunc(TrainChoice, TrainCompletion, TrainJudge, Hour, Min,Class,Train,teacher_id,startTime,endTime)
SendLink()
TeacherMark(Class, teacher_id)
return '发布成功' return '发布成功'
@ -272,20 +277,44 @@ def Find_details():
result=Find_details_Func(ID) result=Find_details_Func(ID)
print(result) print(result)
return jsonify({'TestScore':result}) return jsonify({'TestScore':result})
@app.route('/api/teacher/NotMarkTest',methods=["POST"])
def NotMarkTest():
testID=request.json['testID']
result=NotMarkTestFunc(testID)
return jsonify({'result':result})
@app.route('/api/teacher/UpdateTest',methods=["POST"])
def UpdateTest():
testID=request.json['testID']
score=request.json['score']
submitScoreFunc(score,testID)
print('修改成功')
return '修改成功'
@app.route('/api/teacher/getTrain',methods=["POST"])
def GetTrain():
teacherID=request.json['teacher_ID']
data=getTrainFunc(teacherID)
return jsonify({'data':data})
@app.route("/api/teacher/list_pods") # 列出pod @app.route("/api/teacher/list_pods") # 列出pod
def teacher_list_pods(): def teacher_list_pods():
return list_pods() return jsonify(list_pods())
@app.route("/api/teacher/list_services") # 列出服务 @app.route("/api/teacher/list_services") # 列出服务
def teacher_list_services(): def teacher_list_services():
return list_services() return list_services()
@app.route("/api/teacher/create_pod") # 创建服务 0为项目实训 1为安装实训 @app.route("/api/teacher/create_pod") # 创建服务 1为项目实训 0为安装实训
def teacher_create_pod(): def teacher_create_pod():
return create_pod(1, "test") create_pod(1, "test2")
@app.route("/api/teacher/delete_pod") # 删除服务 @app.route("/api/teacher/delete_pod") # 删除服务
def teacher_delete_pod(): def teacher_delete_pod():
return delete_pod("test") return delete_pod("test2")
@app.route("/api/teacher/check_pod") # 检测数据库是否安装成功 若成功返回OK 否则返回NO @app.route("/api/teacher/check_pod") # 检测数据库是否安装成功 若成功返回OK 否则返回NO
def teacher_check_pod(): def teacher_check_pod():

View File

@ -17,8 +17,8 @@ spec:
runAsGroup: 0 runAsGroup: 0
resources: resources:
limits: limits:
cpu: '1' cpu: '0.2'
memory: 1Gi memory: 0.3Gi
requests: requests:
cpu: '0.25' cpu: '0.1'
memory: 0.5Gi memory: 0.2Gi

View File

@ -15,8 +15,8 @@ spec:
runAsGroup: 0 runAsGroup: 0
resources: resources:
limits: limits:
cpu: '1' cpu: '0.2'
memory: 1Gi memory: 0.3Gi
requests: requests:
cpu: '0.25' cpu: '0.1'
memory: 0.5Gi memory: 0.2Gi

6
python/del.py Normal file
View File

@ -0,0 +1,6 @@
import k8s_func
studentList=['s20240103-44']
for i in studentList:
k8s_func.delete_pod(i)
print("delete")

View File

@ -6,25 +6,29 @@ from kubernetes import client, config
from flask import jsonify from flask import jsonify
import dmPython import dmPython
# Load in-cluster config # Load in-cluster config
config.load_incluster_config() config.load_incluster_config()
v1 = client.CoreV1Api() v1 = client.CoreV1Api()
namespace = open("/var/run/secrets/kubernetes.io/serviceaccount/namespace").read() namespace = open("/var/run/secrets/kubernetes.io/serviceaccount/namespace").read()
IP = "36.138.114.105" IP = "36.138.114.105"
def list_pods(): def list_pods():
ret = v1.list_namespaced_pod(namespace, watch=False) ret = v1.list_namespaced_pod(namespace, watch=False)
return { return ({
"list": [{ "list": [{
"name": item.metadata.name, "name": item.metadata.name,
"ip": item.status.pod_ip "ip": item.status.pod_ip
} for item in ret.items] } for item in ret.items]
} })
def list_services(): def list_services():
ret = v1.list_namespaced_service(namespace) ret = v1.list_namespaced_service(namespace)
return { return {
"list": [ "list": [{
item.to_dict() "ip": item.spec.cluster_ip,
for item in ret.items] "name": item.metadata.name,
"ports": [port.to_dict() for port in item.spec.ports]
} for item in ret.items]
} }
def create_pod(type, name): def create_pod(type, name):
@ -38,7 +42,7 @@ def create_pod(type, name):
body=pod_manifest, body=pod_manifest,
namespace=namespace namespace=namespace
) )
print(f"pod '{resp.metadata.name}' 创建成功") # print(f"pod '{resp.metadata.name}' 创建成功")
# 创建 Service # 创建 Service
with open(f"assets/type{type}-service.yaml") as f: with open(f"assets/type{type}-service.yaml") as f:
service_pod = yaml.safe_load(f) service_pod = yaml.safe_load(f)
@ -49,20 +53,23 @@ def create_pod(type, name):
body=service_pod, body=service_pod,
namespace=namespace namespace=namespace
) )
print(f"服务 '{resp.metadata.name}' 创建成功") # print(f"服务 '{resp.metadata.name}' 创建成功")
if type == 1: if type == 1:
# 创建成功,再次查询,拿到端口 # 创建成功,再次查询,拿到端口
service = v1.read_namespaced_service(name=name + "-service", namespace=namespace) service = v1.read_namespaced_service(name=name + "-service", namespace=namespace)
print(service) # print(service)
print("访问地址:" + IP + ":" + str(service.spec.ports[0].node_port)) # print("访问地址:" + IP + ":" + str(service.spec.ports[0].node_port))
else: else:
service = v1.read_namespaced_service(name=name + "-service", namespace=namespace) service = v1.read_namespaced_service(name=name + "-service", namespace=namespace)
print(service) # print(service)
print("访问地址:" + IP + ":" + str(service.spec.ports[0].node_port)) # print("访问地址:" + IP + ":" + str(service.spec.ports[0].node_port))
return f"{IP} {service.spec.ports[0].node_port}" return "cjcg"
# create_pod(0,'20240101-zt-9-0')
def delete_pod(name): def delete_pod(name):
v1.delete_namespaced_pod(name=name, namespace=namespace) v1.delete_namespaced_pod(name=name, namespace=namespace)
print('deleting pod ' + name)
v1.delete_namespaced_service(name=name + "-service", namespace=namespace) v1.delete_namespaced_service(name=name + "-service", namespace=namespace)
return "删除成功" return "删除成功"

View File

@ -4,10 +4,18 @@ from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes from Crypto.Random import get_random_bytes
import base64 import base64
import datetime import datetime
import k8s_func
db = dmPython.connect(user='SYSDBA', password='dameng!!', host="36.138.114.105", port="32522") db = dmPython.connect(user='SYSDBA', password='dameng!!', host="36.138.114.105", port="32522")
def convert_iso_to_database_format(iso_datetime_str):
# 解析 ISO 8601 格式的日期时间字符串为 datetime 对象
iso_datetime = datetime.datetime.fromisoformat(iso_datetime_str.replace('Z', '+00:00'))
# 格式化为数据库需要的日期时间格式
formatted_datetime_str = iso_datetime.strftime('%Y-%m-%d %H:%M:%S')
return formatted_datetime_str
#获取题目 #获取题目
def choice_question_func(ID): def choice_question_func(ID):
@ -223,6 +231,7 @@ def train_question():
testID=None testID=None
TrainName="" TrainName=""
studentList=[]
# train_question() # train_question()
def SendTrainTestFunc(TrainChoice,TrainCompletion,TrainJudge,Hour,Min,Class,Train,teacher_id,startTime,endTime): def SendTrainTestFunc(TrainChoice,TrainCompletion,TrainJudge,Hour,Min,Class,Train,teacher_id,startTime,endTime):
TrainChoice = json.dumps(TrainChoice) TrainChoice = json.dumps(TrainChoice)
@ -232,7 +241,6 @@ def SendTrainTestFunc(TrainChoice,TrainCompletion,TrainJudge,Hour,Min,Class,Trai
Train=json.dumps(Train) Train=json.dumps(Train)
global TrainName global TrainName
TrainName=Train TrainName=Train
cursor = db.cursor() cursor = db.cursor()
cursor.execute(f'INSERT INTO TRAINTEST (CHOICE,COMPLE,JUDGE,HOUR,MIN,RELEASETIME,STOPTIME,CLASS,SUBJECT,TEACHER_ID,Train) VALUES' cursor.execute(f'INSERT INTO TRAINTEST (CHOICE,COMPLE,JUDGE,HOUR,MIN,RELEASETIME,STOPTIME,CLASS,SUBJECT,TEACHER_ID,Train) VALUES'
f'(?,?,?,?,?,?,?,?,?,?,?)',(TrainChoice,TrainCompletion,TrainJudge,Hour,Min,startTime,endTime,Class,'Train',teacher_id,Train)) f'(?,?,?,?,?,?,?,?,?,?,?)',(TrainChoice,TrainCompletion,TrainJudge,Hour,Min,startTime,endTime,Class,'Train',teacher_id,Train))
@ -249,20 +257,11 @@ def SendTrainTestFunc(TrainChoice,TrainCompletion,TrainJudge,Hour,Min,Class,Trai
end = 'false' end = 'false'
# 将试卷分配到每一个学生 # 将试卷分配到每一个学生
zero='https://www.baidu.com/'
one='https://www.douyin.com/'
global studentList
studentList=student_list
for i in student_list: cursor.execute(f"SELECT ID FROM TRAINTEST WHERE RELEASETIME=? ", (startTime))
if Train=='达梦数据库连接':
cursor.execute("INSERT INTO TrainScore (STUDENT_ID,CLASS,TEST_ID,TF,LINK) VALUES (?,?,?,?,?)",
(i, i[0:6], test_id, end,zero))
else:
cursor.execute("INSERT INTO TrainScore (STUDENT_ID,CLASS,TEST_ID,TF,LINK) VALUES (?,?,?,?,?)",
(i, i[0:6], test_id, end,one))
# 发布实训的时候根据实训不同给予不同链接
cursor.execute(f"SELECT ID FROM TRAINTEST WHERE RELEASETIME=? ", (now_time))
test_id = cursor.fetchall()[0][0] test_id = cursor.fetchall()[0][0]
global testID global testID
testID=test_id testID=test_id
@ -272,6 +271,50 @@ def SendTrainTestFunc(TrainChoice,TrainCompletion,TrainJudge,Hour,Min,Class,Trai
return '发布成功' return '发布成功'
num=5
def SendLink():
global TrainName
global studentList
global testID
cursor = db.cursor()
print('进入到函数')
if TrainName.find(r'["\u524d\u7aef\u4e0e\u6570\u636e\u5e93\u7ed3\u5408"]') != -1:
print('s')
for i in studentList:
print(i)
name ='s'+str(i)+'-'+str(testID)
k8s_func.create_pod(1, name)
item = k8s_func.list_services()
for j in item['list']:
if j['name'] == name + '-service':
Link = 'http://36.138.114.105/' + str(j['ports'][0]['node_port'])
Link2 = 'http://36.138.114.105/' + str(j['ports'][1]['node_port'])
Link3 = 'http://36.138.114.105/' + str(j['ports'][2]['node_port'])
cursor.execute(f"INSERT INTO TRAINSCORE VALUES (?,?,?,?,?,?,?,?,?)",(
i,i[0:6],testID,'false','NULL','NULL',Link,Link2,Link3
))
else:
pass
else:
for i in studentList:
name = 'n' + str(i) + '-' + str(testID)
k8s_func.create_pod(0,name)
item = k8s_func.list_services()
for j in item['list']:
if j['name'] == name + '-service':
Link = j['ip']
cursor.execute(f"INSERT INTO TRAINSCORE VALUES (?,?,?,?,?,?,?,?,?)", (
i, i[0:6], testID, 'false', 'NULL', 'NULL', Link, 'NULL', 'NULL'
))
print('加入链接成功')
db.commit()
cursor.close()
def TeacherMark(CLASS,ID): def TeacherMark(CLASS,ID):
global testID global testID
global TrainName global TrainName
@ -280,20 +323,11 @@ def TeacherMark(CLASS,ID):
if TrainName.find(r'["\u524d\u7aef\u4e0e\u6570\u636e\u5e93\u7ed3\u5408"]') != -1: if TrainName.find(r'["\u524d\u7aef\u4e0e\u6570\u636e\u5e93\u7ed3\u5408"]') != -1:
for i in eval(strClass): for i in eval(strClass):
cursor.execute(f'INSERT INTO TEACHERMARK VALUES(?,?,?,?) ', (ID,testID,'false', i)) cursor.execute(f'INSERT INTO TEACHERMARK VALUES(?,?,?,?) ', (ID,testID,'false', i))
else:
print(TrainName)
db.commit() db.commit()
cursor.close() cursor.close()
# def Find_dic(dic):
# # 获取字典的键,并按照从大到小的顺序排序
# keys_sorted = sorted(dic.keys(), reverse=True)
#
# # 取最后三个键
# last_three_keys = keys_sorted[:3]
#
# # 创建一个新的字典,仅包含排序后的最后三个键及其对应的值
# dic_last_three = {key: dic[key] for key in last_three_keys}
#
# return dic_last_three # 返回一个新字典,该字典仅包含排序后的最后三个键及其对应的值
def Find_details_Func(ID): def Find_details_Func(ID):
@ -324,7 +358,7 @@ def MarkTrainFunc(ClassID,teacher_ID):
# MarkTrainFunc('202401','111111') # MarkTrainFunc('202401','111111')
def NotMarkTest(testID): def NotMarkTestFunc(testID):
cursor = db.cursor() cursor = db.cursor()
dic={} dic={}
cursor.execute(f'SELECT * FROM TRAINSCORE WHERE TEST_ID=?',(testID)) cursor.execute(f'SELECT * FROM TRAINSCORE WHERE TEST_ID=?',(testID))
@ -334,5 +368,23 @@ def NotMarkTest(testID):
return dic return dic
NotMarkTest('9') # NotMarkTest('9')
def submitScoreFunc(score,testID):
cursor = db.cursor()
for i in score:
cursor.execute(f'UPDATE TRAINSCORE SET TRAINRESULT=? WHERE TEST_ID=? AND STUDENT_ID=?', (score[i], testID,i))
cursor.execute(f'UPDATE TEACHERMARK SET TF=? WHERE TRAINID=?',('true',testID))
db.commit()
return 'SELECT'
# score= {'20240101':'123','20240102':'132','20240103':'321'}
# submitScoreFunc(score,'9')
def getTrainFunc(teacherID):
cursor = db.cursor()
cursor.execute(f'SELECT * FROM TRAINTEST WHERE TEACHER_ID=?',(teacherID))
data = cursor.fetchall()
return data

30
python/test.py Normal file
View File

@ -0,0 +1,30 @@
import json
import dmPython
import k8s_func
db = dmPython.connect(user='SYSDBA', password='dameng!!', host="36.138.114.105", port="32522")
cursor=db.cursor()
studentList=['20240101','20240102']
testID='5'
type1=2
for i in studentList:
if type1==1:
name='s'+i+'-'+testID
# k8s_func.create_pod(type1,name)
item=k8s_func.list_services()
for j in item['list']:
if j['name']==name+'-service':
Link = 'http://36.138.114.105/' + str(j['ports'][0]['node_port'])
Link2 = 'http://36.138.114.105/' + str(j['ports'][1]['node_port'])
Link3 = 'http://36.138.114.105/' + str(j['ports'][2]['node_port'])
else:
name='n'+i+'-'+testID
# k8s_func.create_pod(0,name)
item=k8s_func.list_services()
for j in item['list']:
if j['name']==name+'-service':
Link=j['ip']
print(Link)