在 Django 的 views.py 中应该在哪里导入?

Where should imports be in Django's views.py?

关于 Web 应用程序的最少运行时间,将我的导入保存在 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、模块 1、模块 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

推荐使用其中哪一项并且在网站上的性能最好?

不要这样做。

没有理由像这样在代码中间导入。进口只做一次;由于几乎可以肯定,在某些时候您的代码将遵循 is_valid 路径,因此您将需要该导入,因此在此之前推迟导入没有任何好处。

事实上,这可能会使其 性能降低 ;而不是在流程启动时完成所有导入,而是在某人请求的过程中进行。

但无论哪种方式,差异都可以忽略不计。为了可读性,将你的导入放在它们所属的位置,在顶部。

在文件顶部导入模块完全没问题,recommended way 这样做。

它不会增加任何运行时开销,因为导入只执行一次,而不是在每个请求时执行(如 PHP)。