我有一个测量程序将测量推送到web服务器,该服务器用django和postgres编写。目前我正在通过django表单进行此更新。但我发现,表单界面非常慢。如果我设置了一个脚本,那么通过表单上传100条记录需要7或8秒,并在我的VM中固定一个cpu。我可能最终会将20或30个测量系统更新到服务器中,每个测量系统以每秒15个测量值运行,因此更新速度不会起作用。
我最初使用django ORM编写它,然后我重写了自己构建SQL字符串。两者同样缓慢。然后我完全注释掉了数据库更新,它仍然很慢。所以我猜表单界面是瓶颈。
问题:
这是相关表单的模型:
class MeasurementForm(forms.Form):
RunKey = forms.CharField()
MeasureTime = forms.CharField()
CaliperValue = forms.CharField()
CaliperToleranceStatus = forms.CharField()
IOFieldName = forms.CharField(required=False)
IOFieldValue = forms.CharField(required=False)
ToleranceStatus = forms.CharField()
Count = forms.CharField(required=False)
这是实际进行更新的代码。但实际更新已被注释掉。
def entermeasurement(request):
if request.method == 'POST': # If the form has been submitted...
form = MeasurementForm(request.POST) # A form bound to the POST data
response = HttpResponse(mimetype='text/plain')
if form.is_valid(): # All validation rules pass
raws = form.cleaned_data['CaliperValue'].split(",")
vals = []
for v in raws:
if "null" in unicode.lower(v):
vals.append(None)
else:
vals.append(v)
# insert a measurement record.
cursor = connection.cursor()
# print ("presql")
# get number of records removed given the date.
sqlstring = """insert into bwmeasures_measurements
("RunKey_id",
"MeasureTime",
"CaliperValue",
"CaliperToleranceStatus",
"IOFieldName",
"IOFieldValue",
"ToleranceStatus")
values
( """
"""
sqlstring = sqlstring + \
str(form.cleaned_data['RunKey']) + \
", timestamp'" + \
str(dateutil.parser.parse(form.cleaned_data['MeasureTime'])) + \
"', '" + \
postgresarray(vals) + \
"', '" + \
postgresarray(form.cleaned_data['CaliperToleranceStatus'].split(",")) + \
"', '" + \
postgresarray(quodstrings(form.cleaned_data['IOFieldName'])) + \
"', '" + \
postgresarray(quodstrings(form.cleaned_data['IOFieldValue'])) + \
"', '" + \
str(form.cleaned_data['ToleranceStatus']) + \
"')"
"""
# print(sqlstring)
#print("would update here!")
#cursor.execute(sqlstring)
#transaction.commit_unless_managed()
'''
# Django ORM way of doing the insert.
measurement = Measurements()
measurement.RunKey = ProductionRuns.objects.get(id=int(form.cleaned_data['RunKey']))
measurement.MeasureTime = dateutil.parser.parse(form.cleaned_data['MeasureTime'])
measurement.CaliperValue = vals
measurement.CaliperToleranceStatus = form.cleaned_data['CaliperToleranceStatus'].split(",")
measurement.IOFieldName = quodstrings(form.cleaned_data['IOFieldName'])
measurement.IOFieldValue = quodstrings(form.cleaned_data['IOFieldValue'])
measurement.ToleranceStatus = int(form.cleaned_data['ToleranceStatus'])
measurement.save()
'''
# indicate success
response.write("saved\n")
response.write(measurement.id)
# Process the data in form.cleaned_data
return response
else:
response.write("failed")
response.write(str(form.errors))
return response
else:
form = MeasurementForm() # An unbound form
return render(request, 'entermeasurement.html', {
'form': form,
})