学堂 学堂 学堂公众号手机端

python和JS如何进行通信,用什么方法

lewis 6年前 (2019-06-27) 阅读数 6 #技术
今天这篇给大家分享的知识是“python和JS如何进行通信,用什么方法”,小编觉得挺不错的,对大家学习或是工作可能会有所帮助,对此分享发大家做个参考,希望这篇“python和JS如何进行通信,用什么方法”文章能帮助大家解决问题。


js和python是两种语言,js处理网页数据,python可作为服务端开发,两者通过websocket进行通信。 websocket是socket的封装,省去了通信上的HTTP协议转换上的麻烦. 大中型项目推荐使用torando/Djiango平台,两个平台集成度较高,方便开发使用.

实验以发送html页面上的图片到服务器后端为例子.

服务端接收图片后,开启本地端口为10086的服务,等待前端的连接.服务把前端发的图像url存在本地文件car.bmp.

import asyncio
import websockets
import urllib.request

async def recv_user_msg(websocket):
  while True:
    url = await websocket.recv()
    urllib.request.urlretrieve(url,'car.bmp')
    await websocket.send('ok')


async def run(websocket, path):
  while True:
    try:
      await recv_user_msg(websocket)
    except websockets.ConnectionClosed:
      print("ConnectionClosed...", path)    
      break
   
if __name__ == '__main__':
  print("127.0.0.1:10086 websocket...")
  asyncio.get_event_loop().run_until_complete(websockets.serve(run, "127.0.0.1", 10086))
  asyncio.get_event_loop().run_forever()

缺少module直接pip install安装解决.

pip install websockets
pip install urllib

在页面上嵌入img标签,连接服务端,点击发送图片,图片发送至服务端,并且显示返回结果.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>测试Socket——ws://127.0.0.1:10086</title>
 
</head>
<body>
  <img id = 'img' src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1598273151875&di=2823d5f7c3aa5e075bd785572e3e1561&imgtype=0&src=http%3A%2F%2Fimage.9game.cn%2F2019%2F8%2F8%2F90082743.jpg"/>
 <button onclick = "send_img()">发送图片</>
<script type="text/javascript">
    var socket;   
    var ws = new WebSocket("ws://127.0.0.1:10086/test");
    socket = ws;
    ws.onopen = function() {
      console.log('连接成功');

    };

    ws.onmessage = function(evt) {
      var received_msg = evt.data;
      alert('recv:' + received_msg + ' 发送完成');
    };

    ws.onclose = function() {
      s = '断开了连接'
      alert(s);
    };
   
    function send_img() {
      image = document.getElementById('img');
      socket.send(image.src);
  }
  </script>
</body>
</html>

现在大家对于python和JS如何进行通信,用什么方法的内容应该都有一定的认识了吧,希望这篇能对大家有所帮助。最后,想要了解更多,欢迎关注博信,博信将为大家推送更多相关的文章。
版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门