Read local file in django

I'm stuck on this! I am writing a Django view that reads data from an external database. For this, I use the standard MySQLdb library. Now, to load the data, I have to fulfill a very long and complex query. I can hard code this query in my opinion and it works fine. But I think this is impractical; I want to be able to change the request in the future, so I am trying to load an instruction from a text file. My problem is that I do not know where to store and how to open this file. Wherever I am, I get the error "There is no such file or directory." Even saving it in the same directory as the view code does not work.

Please note that this is not a downloaded file; it is just an external file that completes my code. Any ideas? Thanks in advance!

+7
source share
2 answers

Save the file in the root of the django project and add the following to the settings.py file.

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) 

Then in the view do it.

 import os from django.conf.settings import PROJECT_ROOT file_ = open(os.path.join(PROJECT_ROOT, 'filename')) 
+18
source

To do this, I placed it in the settings module. In settings.py add, for example, MY_LONG_QUERY = 'from FOO select BAR...' . Then, in your opinion, just download it from these settings:

 from django.conf import settings settings.MY_LONG_QUERY 

But this does not really answer your question. Assuming that the permissions and everything is correct, save the link to your project root in your settings as follows:

 ROOT_PATH = os.path.split(os.path.abspath(__file__))[0] 

And again in your view, open the file as follows:

 from django.conf import settings def read_from_database(request): f = open(os.path.join(settings.ROOT_PATH, 'myfile.db')) # Do something with f 
+3
source

All Articles