Bootstrap

实训记录(五):后端与算法对接(一)

后端与算法对接(一)

后端与算法进行交互采用socket的方式,网页后端作为客户端,算法作为服务端。

网页

客户端发送输入文本,传递给算法,算法处理后,将数据返回到网页后端,网页后端接收服务端返回的数据:

def correct(request):
    a=request.GET
    inputsent=a.get('inputsent')
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = '127.0.0.1'
    port = 500
    client.connect((host, port))
    sendmsg = inputsent+'over'
    client.send(sendmsg.encode("utf-8"))
    msg = client.recv(1024)
    print(msg.decode("utf-8"))
    outputsent=msg.decode("utf-8")
    client.close()
    return HttpResponse(outputsent)

算法

算法接收到客户端的数据后,进行标点纠正,将获取的答案返回给客户端:

def run(self):
    print("开启线程.....")
    try:
        msg = ''
        while True:
            rec = self._socket.recv(self._recvsize)
            msg += rec.decode(self._encoding)
            if msg.strip().endswith('over'):
                msg=msg[:-4]
                break
        print(msg)
        '''
        模型预测方法
        res为要返回前端的结果
        '''
        self._socket.send(res.encode(self._encoding))
        pass
    except Exception as identifier:
        self._socket.send("500".encode(self._encoding))
        print(identifier)
        pass
    finally:
        self._socket.close()
    print("任务结束.....")
    pass

参考资料:
https://www.cnblogs.com/maosonglin/p/9397257.html

;