您现在的位置是:网站首页> 编程资料编程资料

python和JavaScript通信_python_

2023-05-26 373人已围观

简介 python和JavaScript通信_python_

  • 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标签,连接服务端,点击发送图片,图片发送至服务端,并且显示返回结果.

              测试Socket——ws://127.0.0.1:10086                

到此这篇关于python和JavaScript通信的文章就介绍到这了,更多相关js和python通信内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网