【发布时间】:2016-09-22 22:10:19
【问题描述】:
关于网络应用程序的最少运行时间,将我的导入保存在 views.py 中的理想位置是什么
假设我想使用外部模块验证和处理一些表单条目。我当前的代码:
from django.shortcuts import render
from .forms import *
import re
import module1
import module2
def index(request):
form = MyForm()
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
#
#Process my stuff here using re, module1, module2
#
return render(request, 'index.html', context)
但是,如果条件if form.is_valid(): 失败,提前导入模块 re、module1、module 2 有什么好处?或者条件if request.method == 'POST': 失败?那是表单从未提交的时候。
在满足这些条件后导入这些模块(因为那是实际需要它们的时候)在这些条件失败时会导致程序或 webapp 的运行时开销减少吗?在不需要时避免不必要的导入?
我的想法的伪代码:
if form.is_valid():
import re
#Perform some regex matches and stuff
if (above re matches succeed):
import module1
#Process my stuff here using module1 here
#and so on importing modules only when they are required
其中哪一项是推荐的,并且在网站上表现最好?
【问题讨论】:
标签: python django import python-import