【发布时间】:2017-06-13 14:28:07
【问题描述】:
我正在用 Django 编写一个 Web 应用程序,它以特定的方式使用。它不使用存储在数据库中的模型,而是使用 REST API 从另一个应用程序和平台收集的 JSON 数据动态构建表单。
网页呈现一个表单,其中显示数学参数及其值的列表。然后用户可以更改(或不更改)这些值并按下“运行”按钮以显示一些计算结果。
这些表单是根据通过 URL 查询 JSON 数据获得的数据构建的(它为我提供了参数列表及其初始值)。按照规范,我必须使用 Django 并且不使用数据库来存储任何参数值数据(唯一存储的数据是 JSON 数据的 URL 地址)。
我最终找到了一些可行的解决方案,使用 CBV。我有该结构的详细视图:
class SimulationView(DetailView):
template_name='template.html'
model=SimModel # provides URLs for REST API (URLs for querying parameter list and simulation function)
# this is used to display the page with GET
def get_context_data(self, **kwargs):
# conn.request function that returns param_JSON in JSON/REST
# for a SUBSET of parameters in param_JSON build a list of entries named init_entries. Note not all parameters from the JSON request are used for the user interface.
# form = paramForm(initial=init_entries) and store in context['form']
return context
def post(self, request, *args, **kwargs):
# because the user may have changed parameter values, need to rebuild the JSON dataset to return to the URL with a simulation request
# conn.request function that returns param_list in JSON/REST
# for each param in JSON param_list build a list of entries
# form = paramForm(request.POST, request.FILES, initial=init_entries) and store in context['form']
# use form data to build REST request for the simulation function
# conn.request simulation function and get result in JSON
# store result in context['result']
return render(request, 'template.html', context)
template.html 负责在执行 GET 时显示初始表单,并在执行 POST 时显示结果。
如您所见,存在性能问题。当你做 GET 来构建页面时,你必须做 REST 连接来获取数据并构建表单和界面(这是正常的)。但是当你 POST 请求模拟时,你需要再次运行 URL 连接以获取 JSON 格式的参数列表,更改值,然后请求模拟结果。请注意,REST 请求返回的参数比显示给用户的参数多得多,因此不可能仅使用表单数据来构建正确的 JSON 请求。这有效,但效率低下。我尝试将 param_JSON 存储在类的字段中,但这不起作用:在执行 POST 时再次实例化该类,并且 param_JSON 值丢失。
我需要一个 get 函数吗?还是我做错了?一般来说,有没有更好的方法?非常感谢您的建议。
【问题讨论】: