Read a local file in django

前端 未结 2 1101
小蘑菇
小蘑菇 2021-01-01 12:46

I\'m quite stuck on this one! I am writing a Django view that reads data from an external database. To do this, I am using the standard MySQLdb library. Now, to load the da

2条回答
  •  悲&欢浪女
    2021-01-01 13:12

    For this use, I'd put it in the settings module. In settings.py, add e.g. MY_LONG_QUERY = 'from FOO select BAR...'. Then, in your view just load it from the settings like so:

    from django.conf import settings
    settings.MY_LONG_QUERY
    

    But, this doesn't really answer your question. Assuming permissions and all are correct, keep a reference to your project root in your settings like this:

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

    And then again in your view, open your file like so:

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

提交回复
热议问题