【问题标题】:After executing an api in django rest, the RAM remains high在 django rest 中执行一个 api 后,RAM 仍然很高
【发布时间】:2023-02-16 21:09:38
【问题描述】:

After executing an api in django rest in production mode, the following method is called and executed. After each execution of this method, the amount of RAM usage goes up and up and does not go down, and I don't understand where the problem is.

def download(self):
    try:
        if self.adjust:
            path = Path(UPLOAD_DIR / 'yf_history' / self.market / 'adjusted')
        else:
            path = Path(UPLOAD_DIR / 'yf_history' / self.market)
        path.mkdir(parents=True, exist_ok=True)
        data = yfinance.download(
            progress=False,
            tickers=self.ticker_list,
            period=self.period,
            interval=self.interval_period,
            group_by='ticker',
            auto_adjust=self.adjust,
            prepost=False,
            threads=True,
            proxy=None
        ).T
        for ticker in self.ticker_list:
            try:
                data.loc[(ticker,),].T.dropna().to_csv(path / f'{ticker}{self.suffix}.csv')
            except:
                pass
        del data
    except Exception as error:
        return False, error
    else:
        return True, 'Saved successfully'

I don't have this problem with any other function

Python==3.9 Django==3.2.9 djangorestframework==3.13.1 yfinance==0.2.10

Thank you for your advice on the problem and solution.

    标签: python django django-rest-framework yfinance


    【解决方案1】:

    听起来您的下载功能可能会导致内存泄漏。这是一个常见的问题,当您的代码重复分配内存而不释放内存时,会导致使用的内存量逐渐增加。

    下载函数中内存泄漏的一个可能原因是数据变量。这个变量被赋值为 yfinance.download() 方法的输出,它返回一个 Pandas DataFrame。此 DataFrame 可能非常大,尤其是在您下载大量数据时。当您在函数末尾调用 del data 时,这应该释放 DataFrame 使用的内存,但垃圾收集器可能无法立即清理它。

    要修复内存泄漏,您可以尝试以下几种方法:

    在创建 Path 对象并打开要写入的文件时使用 with 语句。这将在您完成后自动关闭文件,这应该有助于释放内存。

    使用 gc.collect() 方法强制垃圾收集器运行并释放任何未使用的内存。

    尝试以较小的块下载和处理数据,而不是一次全部下载和处理。这有助于减少任何给定时间所需的内存量。

    使用内存分析器来识别内存使用的来源并相应地优化代码。

    除了这些建议之外,监控生产中应用程序的内存使用情况并尝试识别可能导致泄漏的任何模式或趋势始终是一个好主意。

    【讨论】:

      猜你喜欢
      • 2014-05-07
      • 2023-03-28
      • 2013-07-03
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多