【问题标题】:Repeated Action on pandas DataFrame in django rest frameworkdjango rest框架中对pandas DataFrame的重复操作
【发布时间】:2019-02-18 06:46:46
【问题描述】:

场景: 我正在处理djangodjango rest framework,处理pandas dataframe 中的数据。

在前端,有一些函数可以应用于相同的数据。用户可以应用第一个功能,然后数据集将根据应用的功能而变化,然后用户可以应用另一个功能,依此类推..

在后端。我保持所有功能井井有条。循环它并给出响应。 我的问题是,我每次都在执行从第一个函数到最后一个函数的整个过程,这让我的过程变慢了。

有没有一种保持状态和只处理最后一个函数的好方法。 ??

【问题讨论】:

    标签: python django pandas rest django-rest-framework


    【解决方案1】:

    实现这一目标的方法很少

    1。通过使用与服务器的持久连接。

    你可以使用django-channels 之类的东西来创建一个开放的连接。这样,您可以将数据框实例关联到连接并对其进行更改。

    示例代码

    class DataframeWebsocketHandler(WebsocketConsumer):
        def connect(self):
            self.accept()
            self.df = pandas.DataFrame(data=d) # your own implementation here.
    
            # send your initial data
            self.send(text_data=json.dumps({
                'data': self.df
            }))
    
        def disconnect(self, close_code):
            pass
    
        def receive(self, text_data):
            text_data_json = json.loads(text_data)
    
            # you will receive actions to perform here 
            # all actions you take on self.df will persist until websocket is closed
            operation = text_data_json['operation']
            perform_operation(self.df,operation)
    
            # send changed data to the client
            self.send(text_data=json.dumps({
                'data': self.df
            }))
    

    2。通过使用 pkl 和 django 缓存

    您可以将当前修改后的数据帧存储到 pickle 中,并将其存储在 cache 中。 当被要求修改相同的内容时,您可以稍后加载。

    示例代码

    from django.core.cache import cache
    # ... your code
    def new_dataframe_page(request):
        # ... your code
        df = pandas.DataFrame(data=d)
        cache.put(some_inst_specific_key,pickle.dumps(df),3000)
        request.session.put('dframe_cache',some_inst_specific_key)
    
    def update_dataframe(request):
        # ... your code
        cache_key == request.session.get("dframe_cache")
        df = None
        if cache_key && cache.get(cache_key) is not None:
            df = pickle.loads(cache.get(cache_key))
        else:
            # generate new cache normally and store it to session just like above 
            df = generate_dataframe(request)
    
        # perform your current action on dataframe
        cache.put(cache_key,pickle.dumps(df))
    
        # return your modified dataframe.
    

    3。 (最简单且不推荐)具有全局变量:

    维护一个存储各种状态的全局映射变量,当用户要求修改时,直接使用该全局映射中的变量。这种方法很简单,而且不太复杂。但不幸的是,这在生产环境中不起作用。要为 django 提供服务,您通常会运行多个 django 实例,每个实例都有自己的运行时。因此,例如,如果您正在运行 15 个 django 实例,那么所有 15 个实例都将具有单独的全局变量,并且其中一个的任何更改都不会反映在其他实例中。

    【讨论】:

    • 感谢您分享想法
    • 不客气。如果他们有帮助,请考虑接受此作为答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 2019-08-16
    • 2015-09-25
    • 2017-06-14
    • 1970-01-01
    • 2022-12-22
    相关资源
    最近更新 更多