Get absolute path of django app

后端 未结 6 2024
一整个雨季
一整个雨季 2021-02-03 20:09

I am writing a unit test that needs to access an image file that I put in \"fixtures\" directory right under my django app directory. I want to open up this image file in my tes

6条回答
  •  离开以前
    2021-02-03 21:08

    Python modules (including Django apps) have a __file__ attribute that tells you the location of their __init__.py file on the filesystem, so

    import appname
    pth = os.path.dirname(appname.__file__)
    

    should do what you want.

    In usual circumstances, os.path.absname(appname.__path__[0]), but it's possible for apps to change that if they want to import files in a weird way.

    (I do always do PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) in my settings.py, though -- makes it easy for the various settings that need to be absolute paths.)

提交回复
热议问题