是否可以访问views.py中的静态文件? [英] Is it possible to access static files within views.py?
问题描述
我可以通过直接url( localhost:8000 / static / maps / foo.txt
)访问有问题的静态文件,所以我想我拥有这一切工作得很好但是我不能这样做:我想在view.py中打开这个文本文件。这是因为我正在开发一个简单的网络浏览器冒险游戏,我想在静态/地图中存储地图,并使用 f = open('/ static / maps /'+ mapname +')加载这些地图。 txt','r')
。我得到 IOError:没有这样的文件或目录
。我真的不明白,因为当我在地址中搜索这样的目录
I am able to access the static file in question via direct url (localhost:8000/static/maps/foo.txt
), so I guess I have it all working well. But I can't do the following: I want to open that text file in views.py. It's because I'm working on a simple web browser adventure game and I wanted to store maps in static/maps and load those maps using f=open('/static/maps/' + mapname + '.txt', 'r')
. I get the IOError: no such file or directory
. I really don't understand it, because there is such directory when I search for it in address.
可以以某种方式完成吗? / p>
Can it be done somehow?
推荐答案
您需要使用存储在磁盘上的位置,这可能位于 settings.STATIC_ROOT
或 settings.STATICFILES_DIRS
,而不是由网络应用程序提供的地方。
You need to use the place they are stored on disk, which is probably in settings.STATIC_ROOT
or settings.STATICFILES_DIRS
, not the place they are being served by the web app.
请注意,如果您以编程方式修改这些文件,则它们(根据定义)不是静态文件。您最好使用 MEDIA_ROOT
位置。还要注意,Django有帮助者做这样的事情 - 请参阅管理文件。
Note however that if you are modifying these files programmatically, they aren't (by definition) static files. You'd be better off using the MEDIA_ROOT
location. Also note that Django has helpers to do this sort of thing - see the documentation on Managing files.
这篇关于是否可以访问views.py中的静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!