1

我正在从一些模型数据创建一个列表,但我没有正确执行它,它可以工作,但是当我刷新浏览器中的页面时,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})   
4

2 回答 2

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内联属性集。descriptionaddReportResultwaypointsindex.description = description

于 2013-01-19T10:29:39.513 回答
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})
于 2013-01-19T10:45:45.707 回答