Удаление персонализированного класса внутри view.py - Django
here is my view.py. Despite the code is a little bit long, I'd like to remove the class Ibm()
from inside the else
element to a new file called Ibm_class.py
. I tried to do that but I couldn't find any way!
-> wb: file is loaded from a upload
-> wb2, wb3, wb4: files are stored inside the media folder
I tried to copy/paste this class and then import it to the view.py
file but the excel_file
variable must be inside the view
and is still needed inside the Ibm_class.py
. Any suggestion, pls?
Thank you!
Используйте инъекцию зависимости в своем классе вместо того, чтобы полагаться на переменные локальной/глобальной области видимости. Здесь вместо прямого использования переменных inputsCombo
, inputsDNCombo
, outputCombo
, faixas
и sigma
внутри вашего класса, просто передайте их конструктору Ibm
в качестве атрибутов класса.
views.py
...
from my_app.ibm import Ibm # Or wherever you would put that class
...
def index(request):
...
else:
excel_file = request.FILES["excel_file"]
wb = openpyxl.load_workbook(excel_file, data_only=True)
inputsCombo = wb['Inputs COMBO']
inputsDNCombo = wb['Inputs DN COMBO']
outputCombo = wb['OutPut COMBO']
faixas = wb['Faixas']
wb2 = openpyxl.load_workbook('media/sigma.xlsx', data_only=True)
sigma = wb2['Planilha1']
...
for i in range(8, 8 + numeroIbms):
# Pass the dependencies to the constructor of Ibm class
ibm = Ibm(i, inputsCombo, inputsDNCombo, outputCombo, faixas, sigma)
...
...
ibm.py
class Ibm(object):
# Accept the injected parameters to Ibm class
def __init__(self, i, inputsCombo, inputsDNCombo, outputCombo, faixas, sigma):
self.numeroIbm = inputsCombo[get_column_letter(i) + str(10)].value
self.anosAlternativa = inputsDNCombo[get_column_letter(i) + str(14)].value
self.unitariaIBM = arredonda(outputCombo[get_column_letter(i - 1) + str(42)].value)
# For the arguments that will be used by your other functions e.g. check_faixa, define them as class attributes here
self.faixas = faixas
self.sigma = sigma
def get_volume(self):
if self.tipoInvestimento != 'Loja':
for j in range(2, self.sigma.max_row + 1): # Append "self." to the usage of "sigma" to refer to the class attribute that was set in __init__
if self.numeroIbm == self.sigma['A' + str(j)].value:
self.margem12m = self.sigma['D' + str(j)].value
self.volume12m = self.sigma['E' + str(j)].value
def check_faixa(self):
if self.tipoInvestimento != 'Loja':
if self.faixaMargem[0] == 'R':
pass
else:
for row in range(5, self.faixas.max_row + 1): # Append "self." to the usage of "faixas" to refer to the class attribute that was set in __init__
cidade = self.faixas['C' + str(row)].value
if cidade == unidecode.unidecode(self.cidade.upper() + '/' + self.uf.upper()):
self.faixaReal = self.faixas['D' + str(row)].value
if self.faixaReal == '':
self.faixaReal = 'n/a'