python和JavaScript通信
- 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和JavaScript通信的文章就介绍到这了,更多相关js和python通信内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)