我是Django的新手,因此,我想问几个问题。
我正在遵循基于此的教程。
http://hplgit.github.io/web4sciapps/doc/pub/._web4sa_django006.html
它们有一个计算类,并在views.py中调用它来执行计算。
计算类
from numpy import exp, cos, linspace
import matplotlib.pyplot as plt
import os, time, glob
def damped_vibrations(t, A, b, w):
return A*exp(-b*t)*cos(w*t)
def compute(A, b, w, T, resolution=500):
"""Return filename of plot of the damped_vibration function."""
print os.getcwd()
t = linspace(0, T, resolution+1)
y = damped_vibrations(t, A, b, w)
plt.figure() # needed to avoid adding curves in plot
plt.plot(t, y)
plt.title('A=%g, b=%g, w=%g' % (A, b, w))
if not os.path.isdir('static'):
os.mkdir('static')
else:
# Remove old plot files
for filename in glob.glob(os.path.join('static', '*.png')):
os.remove(filename)
# Use time since Jan 1, 1970 in filename in order make
# a unique filename that the browser has not chached
plotfile = os.path.join('static', str(time.time()) + '.png')
plt.savefig(plotfile)
return plotfile
if __name__ == '__main__':
print compute(1, 0.1, 1, 20)
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse
from models import InputForm
from compute import compute
import os
def index(request):
os.chdir(os.path.dirname(__file__))
result = None
if request.method == 'POST':
form = InputForm(request.POST)
if form.is_valid():
form2 = form.save(commit=False)
result = compute(form2.A, form2.b, form2.w, form2.T)
result = result.replace('static/', '')
else:
form = InputForm()
return render_to_response('vib1.html',
{'form': form,
'result': result,
}, context_instance=RequestContext(request))
坦率地说,我不太确定这是否是正确的方法。据我所知,视图在客户端计算机上呈现。但是,如果需要密集资源,则应在服务器端完成。我在这里弄错了吗?
或者整个事情应该如何?
答案 0 :(得分:2)
视图在客户端计算机上呈现。
这只是不正确,服务器上的处理视图,然后视图响应将被发送回客户端。
在正常的html响应中,客户端浏览器然后呈现html。
客户端机器必须做的唯一处理是在客户端进行的任何操作(angular,javascript等)。
答案 1 :(得分:2)
你没有做错任何事。 views.py函数不是前端代码,它们是后端代码。您仍然关注概念MVC
,但在django中它就像MVT
,其中django中的views
是controller
中的MVC
和django的html template
符合view
中MVC
的概念。所有python代码都在服务器上执行,只有模板中的html和javascript在客户端呈现。