FileNotFoundError 与 matplotlib 和 apscheduler

问题描述

我的目标是从网站下载数据、绘制图形、保存并在网页上显示。我使用的是 Django 3.2、Python 3.9.5、pandas 和 matplotlib。

当我的视图中只有以下代码时,一切正常并且图表显示正确:

r = requests.get(url_lab)  #url_lab defined elsewhere,not relevant
z = zipfile.ZipFile(io.BytesIO(r.content))

if file_lab in z.namelist():   #file_lab defined elsewhere,not relevant
    df_lab = pd.read_csv(z.open(file_lab),dtype={'a': str,'b': str,'c': float},usecols=col_list,parse_dates=['Period'],\
        encoding = "ISO-8859-1",engine='python') 

df_lab.set_index('Period',inplace=True,drop=True)
df_lab = df_lab.sort_index().loc['2015-03-03':]

x = df_lab.index[df_lab.Series_reference == "HLFQ.S1A1S"]
y = df_lab.Data_value[df_lab.Series_reference == "HLFQ.S1A1S"]
fig = plt.plot(x,y)

plt.savefig('static/images/lab-empl-lev.png')

但是,我不希望每次运行服务器时都运行此代码,事实上,每天在特定时间更新数据很重要。所以我需要使用某种任务调度程序,并决定使用 apscheduler。因此,按照教程,我创建了一个文件夹,其中包含一个空的 __init__.pyfetch.py,其中包含以前的代码updater.py

fetch.py

def get_lab_data():
    r = requests.get(url_lab)
    z = zipfile.ZipFile(io.BytesIO(r.content))

    if file_lab in z.namelist():
        df_lab = pd.read_csv(z.open(file_lab),\
            encoding = "ISO-8859-1",engine='python') 

    df_lab.set_index('Period',drop=True)
    df_lab = df_lab.sort_index().loc['2015-03-03':]

    x = df_lab.index[df_lab.Series_reference == "HLFQ.S1A1S"]
    y = df_lab.Data_value[df_lab.Series_reference == "HLFQ.S1A1S"]
    fig = plt.plot(x,y)

    plt.savefig('static/images/lab-empl-lev.png')

updater.py

from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from . import fetch

def start():
    scheduler = BackgroundScheduler()
    scheduler.add_job(fetch.get_lab_data,'cron',day_of_week='mon-fri',hour=10,minute=47)
    scheduler.start()

然后,为了测试是否一切正常,我运行 fetch.py 文件并在末尾添加 get_lab_data() 以运行该函数。然后我收到以下错误

FileNotFoundError: [Errno 2] No such file or directory: 'static/images/lab-empl-lev.png'

这很奇怪,因为它以前有效。所以我想可能是因为这现在是一个不同的目录,所以试着像这样回到以前的目录:

import os.path as path
import os
two_up = path.abspath(path.join(os.getcwd(),"../.."))

但是错误仍然存​​在。我也尝试使用我的媒体文件夹:

plt.savefig('media/lab-empl-lev.png')

但我得到同样的错误FileNotFoundError: [Errno 2] No such file or directory: 'media/lab-empl-lev.png'

当我输入绝对文件路径时它会起作用,但它必须是相对路径,否则它在生产中不起作用。

我还通过添加 plt.show() 仔细检查了其他一切是否确实正常工作 - 正确的图表显示

我还尝试了以下方法

from django.templatetags.static import static
url = static(r'images/test3.png')
plt.savefig(url)

但仍然没有运气。

以下也给出了同样的错误

from django.conf import settings
url = os.path.join(settings.STATIC_URL,'test3.png')

我的文件结构如下:

---app
   __init__
   views.py
   apps.py
   ---migrations
   ---templates
   ---static
      ---images
   etc.
---mysite
---fetch-data
   __init__.py
   fetch.py
   updater.py
---media
---static
   ---css
   ---images
---templates
manage.py

我在 settings.py 中的静态设置(虽然这里应该没有问题,因为在我的项目其他地方一切正常):

STATICFILES_FINDERS = [
        'django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder',]

STATIC_URL = '/static/'
STATICFILES_Dirs = (os.path.join(BASE_DIR,"static"),)

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'

在我的项目的 urls.py 中:

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)

有人知道为什么会发生这种情况以及如何解决吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...