Django - 从视图

时间:2015-05-23 21:20:44

标签: django pythonanywhere

我正在使用Django构建一个托管在PythonAnywhere上的网站。 其中一个网站页面是一个私人页面,我用它来构建内容,然后将其显示在公共页面中。 我不想将私有页面内生成的内容保存到数据库中,然后从数据库中检索它,而是将其保存到我的静态目录中的静态文件中(这是一小部分JSON文件,将一遍又一遍地提供再次,所以我认为将它们作为静态文件提供是有意义的。)

在定义我的私人页面的视图中,我有以下用于保存文件的代码:

json=request.POST.get('json')
name=request.POST.get('name')
file=open(settings.STATIC_ROOT+'/'+name+'.json','w')
file.write(json)
file.close()

请注意,我之前导入了设置:

from django.conf import settings
奇怪的是,这工作了一段时间,但后来它停止了工作。 我得到的错误是:

Exception Value: 'function' object has no attribute 'STATIC_ROOT'

我做错了吗? 我与PythonAnywhere相关的事实是什么?应用程序是否可能由无法写入我的静态目录的工作人员提供服务? 我该怎么做才能解决问题?

1 个答案:

答案 0 :(得分:1)

As pointed out by PythonAnywhere staff, the procedure was legitimate and supposed to work because the app is served by a worker running as my own user ID which has permissions to write to the static directory. The problem was generated by a naming conflict due to the fact that also one of the views had been named settings. To solve the problem I substituted the import statement with

from django.conf import settings as djangoSettings

and the open statement with

file=open(djangoSettings.STATIC_ROOT+'/game'+name+'.json','w')

After doing these substitutions, everything seemed to work.