我正在从一些模型数据创建一个列表,但我没有正确地做它,它可以正常工作,但是当我刷新broswer reportResults中的页面时,只是添加了。我希望它会在请求之间收集垃圾,但显然我做错了什么,有什么想法吗?
谢谢, 伊万
reportResults = [] #the list that doesn't get collected
def addReportResult(fix,description):
fix.description = description
reportResults.append(fix)
def unitHistory(request,unitid, syear, smonth, sday, shour, fyear, fmonth, fday, fhour, type=None):
waypoints = Fixes.objects.filter(name=(unitid))
waypoints = waypoints.filter(gpstime__range=(awareStartTime, awareEndTime)).order_by('gpstime')[:1000]
if waypoints:
for index in range(len(waypoints)):
...do stuff here selecting some waypoints and generating "description" text
addReportResult(waypointsindex,description) ##append the list with this, adding a text description
return render_to_response('unitHistory.html', {'fixes': reportResults})
答案 0 :(得分:1)
每次重复使用相同的列表,要修复它,您需要重新构建代码以在每个请求上创建新列表。这可以通过多种方式完成,这是一种方式:
def addReportResult(reportResults, fix,description):
fix.description = description
reportResults.append(fix)
def unitHistory(request,unitid, syear, smonth, sday, shour, fyear, fmonth, fday, fhour, type=None):
reportResults = [] # Here we create our local list that is recreated each request.
waypoints = Fixes.objects.filter(name=(unitid))
waypoints = waypoints.filter(gpstime__range=(awareStartTime, awareEndTime)).order_by('gpstime')[:1000]
if waypoints:
for index in range(len(waypoints)):
# Do processing
addReportResult(reportResults, waypointsindex, description)
# We pass the list to the function so it can use it.
return render_to_response('unitHistory.html', {'fixes': reportResults})
如果addReportResult
保持较小,您还可以通过完全取消对description
的调用并在同一位置执行addReportResult
来内联waypointsindex.description = description
属性集。
答案 1 :(得分:0)
为了让您了解请求的生命周期,mod_wsgi将保持一个进程为多个请求提供服务。该过程每隔一段时间就会被回收,但它绝对不会像您所假设的那样受到单个请求的约束。
这意味着您需要一个本地列表。我建议直接在线移动addReportResult
函数内容,但如果它需要可重用或函数太长,那不是一个好主意。相反,我会让该功能返回该项目,您可以在本地收集结果。
def create_report(fix, description): # I've changed the name to snake_casing
fix.description = description
return fix
def unit_history(request,unitid, syear, smonth, sday, shour, fyear, fmonth, fday, fhour, type=None):
reports = []
waypoints = Fixes.objects.filter(name=(unitid))
waypoints = waypoints.filter(gpstime__range=(awareStartTime, awareEndTime)).order_by('gpstime')[:1000]
if waypoints:
for index in range(len(waypoints)):
report = create_report(waypointsindex, description)
reports.append(report)
return render_to_response('unitHistory.html', {'fixes': reportResults})