如何实现JS前端与Python后台的结合

您所在的位置:网站首页 js怎么连接服务器服务端 如何实现JS前端与Python后台的结合

如何实现JS前端与Python后台的结合

2024-06-04 09:39| 来源: 网络整理| 查看: 265

  这篇笔记是帮助那些,想把自己的python模型展示在web网页上的朋友们,具体来说就是在javascript的前端与python的后台之间实现数据的传输。   我自己的网站就是用这个方法写的,感兴趣的朋友可以戳:http://www.gwylab.com/works.html。

  先说明一下,对于我们这种穷学生,网页服务器用的是空间(我是租不起GPU服务器的。。),也就是云虚拟主机的分割,仅支持php,不支持python和java,所以训练好的python模型没法在网站后台跑。。   但是python模型在自己/实验室的电脑上是能跑的,于是我们就可以想办法把前端数据跨域传给本地计算机上的python接口,下面就要介绍一种用websocket进行数据传输的方法。   其实js对于websocket的支持是很不错的,传输、解码都很快(毕竟WebSocket是HTML5出的),但是python对于web就有很多问题,所以这篇经验的重点在于python对websocket的传输与加、解码。我们先来看一下websocket的协议格式: 在这里插入图片描述   根据这张图我们便能在python端一步步写出读取数据的方法:

  第一步get opcode:

def getOpcode(self): first8Bit = self.con.recv(1) first8Bit = struct.unpack('B', first8Bit)[0] opcode = first8Bit & 0b00001111 return opcode

  第二步get datalength:

def getDataLength(self): second8Bit = self.con.recv(1) second8Bit = struct.unpack('B', second8Bit)[0] masking = second8Bit >> 7 dataLength = second8Bit & 0b01111111 #print("dataLength:",dataLength) if dataLength var host = "ws://" + $("serverIP").value + ":" + $("serverPort").value + "/"; document.getElementById("btnConnect").value = "连接中"; document.getElementById("btnConnect").disabled = true; socket = new WebSocket(host); try { socket.onopen = function (msg) { document.getElementById("btnConnect").value = "连接成功"; document.getElementById("btnSend").disabled = ""; //alert("连接成功!"); }; socket.onmessage = function (msg) { if (typeof msg.data == "string") { displayContent(msg.data); if(msg.data=="Receive:100%"){ current=0; total=0; } else if(msg.data.substr(0,7)=="Receive"){ var str1=msg.data.split(':')[1]; var str2=str1.split('/')[0]; picsend(parseInt(str2)) } } else { alert("非文本消息"); } }; socket.onerror = function (error) { alert("Error:"+ error.name); }; socket.onclose = function (msg) { document.getElementById("btnConnect").value = "连接"; document.getElementById("btnConnect").disabled = ""; document.getElementById("btnSend").disabled = true;//alert("连接关闭!"); }; } catch (ex) { log(ex); } } async function send() { var str = document.getElementById("sendText").value; socket.send(str); } async function picsend(pos){ beforetime=new Date().getTime(); current=pos; socket.close(); connect(); while(document.getElementById("btnConnect").value != "连接成功") {await sleep(200);} var str = document.getElementById("sendText").value; socket.send(str.substring(pos)); } window.onbeforeunload = function () { try { socket.close(); socket = null; } catch (ex) { } }; function $(id) { return document.getElementById(id); } Date.prototype.Format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } function displayContent(msg) { $("txtContent").value += "\r\n" +new Date().Format("yyyy/MM/dd hh:mm:ss")+ ": " + msg; $("txtContent").scrollTop = $("txtContent").scrollHeight; } function onkey(event) { if (event.keyCode == 13) { send(); } }

  【后台Python】:

from threading import Thread import struct import time import hashlib import base64 import socket import time import types import multiprocessing import os mode = "initialize" pic_size = 0 pic_receive = 0 pic = "" pic_repeat = [] class returnCrossDomain(Thread): def __init__(self, connection): Thread.__init__(self) self.con = connection self.isHandleShake = False def run(self): global mode global pic_size global pic_receive global pic global pic_repeat while True: if not self.isHandleShake: # 开始握手阶段 header = self.analyzeReq() secKey = header['Sec-WebSocket-Key']; acceptKey = self.generateAcceptKey(secKey) response = "HTTP/1.1 101 Switching Protocols\r\n" response += "Upgrade: websocket\r\n" response += "Connection: Upgrade\r\n" response += "Sec-WebSocket-Accept: %s\r\n\r\n" % (acceptKey.decode('utf-8')) self.con.send(response.encode()) self.isHandleShake = True if(mode=="initialize"): mode = "get_order" print('response:\r\n' + response) # 握手阶段结束 #读取命令阶段 elif mode == "get_order": opcode = self.getOpcode() if opcode == 8: self.con.close() self.getDataLength() clientData = self.readClientData() print('客户端数据:' + str(clientData)) # 处理数据 ans = self.answer(clientData) self.sendDataToClient(ans) if (ans != "Unresolvable Command!" and ans != "hello world"): pic_size = int(clientData[3:]) pic_receive = 0 pic = "" pic_repeat=[] print("需要接收的数据大小:", pic_size) mode = "get_pic" #读取图片阶段 elif mode == "get_pic": opcode = self.getOpcode() if opcode == 8: self.con.close() self.getDataLength() clientData = self.readClientData() print('客户端数据:' + str(clientData)) pic_receive += len(clientData) pic += clientData if pic_receive


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3