With respect to least runtime on web app, what is the ideal place to keep my imports in views.py
Say I want to validate and process some form entries with external modules. My current code:
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)
But what good is it doing by importing module re, module1, module 2 before hand if condition if form.is_valid():
failed? Or condition if request.method == 'POST':
fails? That is when the form was never submitted.
Would importing these modules after these conditions are passed (because thats when they are actually needed) cause any less runtime overhead on program or webapp when these conditions fail? avoiding unnecessary imports when they are not needed?
Psuedo code of my idea:
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
Which one of these is recommended and would have best performance on the website?