【问题标题】:returned array referencing the same memory spot but returning different values返回的数组引用相同的内存点但返回不同的值
【发布时间】:2019-07-16 17:24:36
【问题描述】:

我正在设置一个基本的动态网页来显示 EC2 实例数据,我需要检查并传递包含内部数据的数组以使用 D3 显示。我使用多进程在后台运行集合。

运行 python3.7 和最新版本的 Flask。

app.py 代码

    @app.route('/experiment')
    def experiment():
        type = request.args.get('type')
        resource = request.args.get('resource')
        action = request.args.get('action')
        if 'test' not in session:
            thread = multiprocessing.Process(target=exp.transmitTest)
            session['test'] = 'started'
            thread.start()
        print(f"Looking for Data at {hex(id(exp.getData()))} found {exp.getData()}")
        return render_template('experiment.html',  data=exp.getData(), type=request.args.get('type'), resource=request.args.get('resource'), action=request.args.get('action'))

后端代码

    def transmitTest(self):
        for i in range(5):
            self.data.append(random.randint(0,100))
            time.sleep(4)
            print(f"Data: {self.data} at {hex(id(self.data))}")

    def getData(self):
        return self.data

我的 JS 调度程序每 5 秒运行一次“/experiment”。打印语句显示,即时写入和从 getter 获取的数组位于相同的内存空间,但一个是空的,另一个有数据。谁能帮我理解这个?

【问题讨论】:

    标签: flask jinja2 python-3.7


    【解决方案1】:

    所以我想通了。在烧瓶中的进程中调用对象方法时,python会创建对象的副本,然后区分两个副本,即使它们确实占用了相同的内存空间。我需要通过 redisqueue (https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xxii-background-jobs) 添加一个后端队列,这样我就可以在不中断烧瓶路由的情况下对后端进行异步调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      相关资源
      最近更新 更多