Read a local file in django

前端 未结 2 1098
小蘑菇
小蘑菇 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 12:57

    Keep the file in django project root and add the following in the settings.py file.

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

    Then in the view do this.

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

    Update:

    In newer Django versions BASE_DIR is already defined in the settings.py file. So you can do the following.

    import os
    from django.conf import settings
    
    file_ = open(os.path.join(settings.BASE_DIR, 'filename'))
    

提交回复
热议问题