无法在 django 中将文件作为数据库访问
在我的 django 应用程序中,结构如下:
__init__.py
__init__.pyc
models.py
tests.py
usage.rrd
views.py
views.pyc
我试图访问 views.py
中的 usage.rrd
文件,如下所示:
from django.http import HttpResponse
import rrdtool
def hello(request):
info = rrdtool.info('usage.rrd')
return HttpResponse(info)
但我得到:
打开“/usage.rrd”:没有这样的文件或 目录
尽管位于当前目录中。
In my django application structure is as follows:
__init__.py
__init__.pyc
models.py
tests.py
usage.rrd
views.py
views.pyc
I am trying to access the usage.rrd
file in views.py
as follows:
from django.http import HttpResponse
import rrdtool
def hello(request):
info = rrdtool.info('usage.rrd')
return HttpResponse(info)
but I am getting:
opening '/usage.rrd': No such file or
directory
despite being in the current directory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 bwt 的答案中提到的路径问题。您的 django 环境的工作目录将不是您应用程序的工作目录,因此无法找到您的文件。
您必须指定 rrd 文件的完整路径(不理想)或相对于工作目录的路径。
或者,处理此类问题的常见技巧是提取特定 python 模块所在的目录(使用 __file__ ),并使用它将路径(相对于当前文件)转换为绝对路径。例如:
在您的情况下:
ps 您可能已经在
settings.py
中看到此方法用于指定 sqlite3DATABASE_NAME
、MEDIA_ROOT
的路径,等等,这样绝对路径是在运行时获得的,而不是硬编码的。As mentioned in thebwt's answer it's a path issue. The working directory for your django environment will not be that of you app, hence the failure to locate your file.
You will have to specify either a full path to your rrd file (not ideal) or a path relative to the working directory.
Alternatively, a common trick to deal with issues like this is to extract the directory a particular python module is in (using
__file__
), and using that to translate a paths (relative to the current file) to an absolute path. For example:In your case:
p.s. you might have seen this method being used in
settings.py
to specify paths to sqlite3DATABASE_NAME
,MEDIA_ROOT
, etc. such that the absolute path is obtained at runtime rather than being hardcoded.该应用程序从项目的根目录启动。所以你需要修复你的路径 ('app-name/usage.rrd') 。
The application starts from the root directory of your project. So you you need to fix your path, ('app-name/usage.rrd') .