获取django应用程序的绝对路径 [英] Get absolute path of django app
问题描述
我正在写一个单元测试,需要访问我的django应用程序目录下的fixtures目录中的图像文件。我想使用相对路径在我的测试中打开这个图像文件,这将需要我获取django应用程序的绝对路径。有没有办法获得django应用程序的绝对路径?
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 test using relative path, which would require me to get the absolute path of the django app. Is there a way to get the absolute path of the django app?
推荐答案
Python模块(包括Django应用)有一个 __ file __
属性,告诉您文件系统上的 __ init __。py
文件的位置,因此
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__)
应该做你想要的。
在通常情况下, os.path.absname appname .__ path __ [0])
,但应用程序可能会改变,如果他们想以奇怪的方式导入文件。
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.
我在 settings.py $ c $中始终执行
PROJECT_ROOT = os.path.dirname(os.path.abspath(__ file __))
c>,尽管 - 使各种设置变得容易,需要是绝对路径。)
(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.)
这篇关于获取django应用程序的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!