注意:抱歉,我没有发布两个以上链接所需的声誉分数。下面发布的片段引用了以下视图和支持类的__del__() 方法。
我在 Django 中有一个基于函数的视图,它将类的实例存储为 django 会话的值。
# First view Function
if request.method == 'POST':
logger.info('User %s Began Upload of File %s' % (request.user.username, request.FILES['file']))
form = uploadFileForm1(request.POST, request.FILES)
if form.is_valid():
# form.cleaned_data contains an in memory version of the uploaded file.
uploaded_shp = ShpUploader(form.cleaned_data['file'])
# Store ShpUploader instance in cookie to be referenced
request.session['uploaded_shp'] = uploaded_shp
return HttpResponseRedirect('./2')
else:
for uploadfile_error in form.errors['file']:
logger.warning(uploadfile_error)
会话在稍后的视图中被访问,我将这个对象的一些方法存储在会话中。
# Second view Function
if request.method == 'POST':
# Required to repass shpPath kwarg
form = uploadFileForm2(request.POST,shpPath=request.session['uploaded_shp'].upload_full_path)
if form.is_valid():
# Pass user-defined field mappings to import_shapefile method.
request.session['uploaded_shp'].import_shapefile(form.cleaned_data)
logger.info('Successful - User %s Uploaded File %s' % (request.user.username, request.session['uploaded_shp'].upload_full_path))
return HttpResponseRedirect('./success')
else:
print form.errors
我最初玩弄了__del__()
在我的类中覆盖该方法的想法,以自动删除该对象引用的文件夹。
# Inside my class definition
def __del__(self):
"""
Given a directory, remove it an its contents.
Intended to clean up temporary files after upload.
"""
shutil.rmtree(self.upload_dir)
logger.info('Delete Successful: %s' % self.upload_dir)
我的问题是为什么我的类的__del__()
方法在第一个视图和第二个视图之间执行,尽管将实际对象存储在会话中?
我尝试使用具有自定义__del__()
方法的类编写一个基本示例,该方法使用字典在函数之间保留对象。这个例子:
class tester(object):
def __init__(self, val):
self.val = val
print 'created in %s' % self.val
def __del__(self):
print 'deleted'
cache = {}
def f1():
print 'in f1'
t = tester('Test Object Value')
cache['tdict'] = t
print cache['tdict'].val
def f2():
print 'in f2'
print cache['tdict'].val
if __name__ == '__main__':
f1()
f2()
产生我所期望的输出,__del__()
仅在退出第二个函数后调用该方法f2()
。
in f1
created in Test Object Value
Test Object Value
in f2
Test Object Value
deleted
[Finished in 0.1s]
关于会话中间件的工作方式,我是否遗漏了一些东西?我的一个想法是关于弱引用,如果 django 会话中间件使用这些?有关弱引用的文章链接,请参见下文。
# Can't post over two links yet.
http://mindtrove.info/python-weak-references/
感谢您的洞察力。我已经解决了这个问题,但我仍然很好奇为什么会发生这种行为。