Unable to access file as a database in django

280 views Asked by At

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.

2

There are 2 answers

0
thebwt On BEST ANSWER

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

0
Shawn Chin On

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.