Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法在Python异步函数中复制对象_Javascript_Python_Html_Asynchronous_Websocket - Fatal编程技术网

Javascript 无法在Python异步函数中复制对象

Javascript 无法在Python异步函数中复制对象,javascript,python,html,asynchronous,websocket,Javascript,Python,Html,Asynchronous,Websocket,我正在制作一个带有消息同步系统的Python WebSocket服务器和HTML客户端。UpdateData函数似乎无法正确复制对象 我的PythonWebSocket服务器代码如下 import asyncio import json import logging import websockets import copy logging.basicConfig() m_sysObj =\ { "Valve":[ { "ActualTemp

我正在制作一个带有消息同步系统的Python WebSocket服务器和HTML客户端。UpdateData函数似乎无法正确复制对象

我的PythonWebSocket服务器代码如下

import asyncio
import json
import logging
import websockets
import copy

logging.basicConfig()

m_sysObj =\
{
    "Valve":[ 
        {
            "ActualTemp": 190,
        }
    ],
    "Test": 0
}

USERS = set()

def state_event():
    return json.dumps({"type": "state", **m_sysObj})

def users_event():
    return json.dumps({"type": "users", "count": len(USERS)})

def copyData(data):
    m_sysObj = [x[:] for x in data]

async def notify_state():
    if USERS:  # asyncio.wait doesn't accept an empty list
        message = state_event()
        await asyncio.wait([user.send(message) for user in USERS])


async def notify_users():
    if USERS:  # asyncio.wait doesn't accept an empty list
        message = users_event()
        await asyncio.wait([user.send(message) for user in USERS])


async def register(websocket):
    USERS.add(websocket)
    await notify_users()

async def unregister(websocket):
    USERS.remove(websocket)
    await notify_users()

async def updateData(websocket, path):
    # register(websocket) sends user_event() to websocket
    await register(websocket)
    try:
        await websocket.send(state_event())
        async for message in websocket:
            data = json.loads(message)
            #m_sysObj = data                                    # not working
            #m_sysObj = copy.deepcopy(data)                     # not working
            #m_sysObj = [inner_list[:] for inner_list in data]  # not working
            m_sysObj["Valve"] = data["Valve"]                   # works, but I need to copy "test" as well
            await notify_state()
    finally:
        await unregister(websocket)

start_server = websockets.serve(updateData, "localhost", 6789)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
我的HTML WebSocket客户端代码失败了

<html>
    <head>
        <title>WebSocket demo</title>
    </head>
    <body>
        <div class="buttons">
            <div class="update button">update Button</div>
            <div class="container">
                <form></form>
                  temp: <input id="temp" class="value" type="text"><br>
                </form>
            </div>
        </div>
        <div class="state">
            <span class="users">?</span> online
        </div>
        <script>
            var m_sysObj;
            var update = document.querySelector('.update'),
                users = document.querySelector('.users'),
                websocket = new WebSocket("ws://127.0.0.1:6789/");
            update.onclick = function (event) {
                m_sysObj.Valve[0].ActualTemp = +document.getElementById('temp').value;
                websocket.send(JSON.stringify(m_sysObj));
            }

            websocket.onmessage = function (event) {
                data = JSON.parse(event.data);
                switch (data.type) {
                    case 'state':
                        m_sysObj = data;
                        document.getElementById('temp').value = data.Valve[0].ActualTemp;
                        break;
                    case 'users':
                        users.textContent = (
                            data.count.toString() + " user" +
                            (data.count == 1 ? "" : "s"));
                        break;
                    default:
                        console.error(
                            "unsupported event", data);
                }
            };
        </script>
    </body>
</html>

WebSocket演示
更新按钮
温度:
? 在线 的 var m_sysObj; var update=document.querySelector('.update'), users=document.querySelector('.users'), websocket=新的websocket(“ws://127.0.0.1:6789/”; update.onclick=函数(事件){ m_sysObj.Valve[0]。ActualTemp=+document.getElementById('temp').value; send(JSON.stringify(m_sysObj)); } websocket.onmessage=函数(事件){ data=JSON.parse(event.data); 开关(数据类型){ “国家”一案: m_sysObj=数据; document.getElementById('temp')。value=data.Valve[0]。ActualTemp; 打破 案例“用户”: users.textContent=( data.count.toString()+“用户”+ (data.count==1?“:“s”); 打破 违约: 控制台错误( “不支持的事件”,数据); } };

deepcopy似乎不起作用,客户端的值正在重置。复制对象的唯一方法是复制单个标记。

我发现问题在于带有全局变量的python函数。我必须用global关键字设置全局变量

   async for message in websocket:
            data = json.loads(message)
            global m_sysObj
            m_sysObj = data
            await notify_state()

您是否尝试确定异步是否与此deepcopy故障相关?或者说,如果您从代码中删除了所有异步,那么deepcopy成功了吗?