开发者

Unable to access file as a database in django

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 i开发者_开发问答mport 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.


The application starts from the root directory of your project. So you you need to fix your path, ('app-name/usage.rrd') .


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:

FILE_DIR = os.path.realpath(os.path.dirname(__file__))
rel_to_abs = lambda *x: os.path.join(FILE_DIR, *x)

In your case:

# in view.py
import os
import rrdtools
FILE_DIR = os.path.realpath(os.path.dirname(__file__))
rel_to_abs = lambda *x: os.path.join(FILE_DIR, *x)

def hello(request):
    info = rrdtool.info(rel_to_abs('usage.rrd'))
    return HttpResponse(info)

p.s. you might have seen this method being used in settings.py to specify paths to sqlite3 DATABASE_NAME, MEDIA_ROOT, etc. such that the absolute path is obtained at runtime rather than being hardcoded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜