'模块'对象没有属性' main' - Django

时间:2014-07-18 16:25:30

标签: python django exception

在我的views.py我导入并调用外部Python脚本,因此:

import reval2
reval2.main(user)

这是reval2.py。对不起,代码很长:

# -*- coding: utf-8 -*-

import xlrd
import xlwt
import itertools
import os
import sqlite3
import numpy as np
import bond_cf
import bond_cf2
import datetime
import interest_calc
import csv
print "begin"
def obj_arr_xl(wb,i):
    sh=wb.sheet_by_index(i)
    nested_list=[sh.row_values(i) for i in range(sh.nrows)]
    return np.array(nested_list,dtype=object)

def get_wb(fname):
    if not fname.endswith('.xls'):
        fname = fname + '.xls'
    if not os.path.exists(fname):
        pass # Ath. commentað af Gumma --- print "file %s not found " % fname
    return xlrd.open_workbook(fname)     

def get_excel_data(infile):

    local_filename = infile    
    wb=get_wb(local_filename)

    paym=obj_arr_xl(wb,0)
    data_paym=paym[1:]
    data_paym = data_paym.tolist()
    for x in data_paym:
        x[0]=str(x[0])
        x[1]=float(x[1])
        x[1]=round(x[1],2)
        x[2]=float(x[2])
        x[2]=round(x[2],2)
#        year, month, day, hour, minute, second = xlrd.xldate_as_tuple(x[3],wb.datemode)
#        x[3]=datetime.date(year,month,day)
    return np.array(data_paym,dtype=object)    

def write_xls_table(file_name, wbook,data,sheet_name,headings):
    date_format = xlwt.XFStyle()
    date_format.num_format_str='YYYY-MM-DD'
    r0=0
    c0=0
    book = wbook
    sheet = book.add_sheet(sheet_name)
    rowx = 0
    for colx, value in enumerate(headings):
        sheet.write(rowx+r0, colx+c0, value)
    sheet.set_panes_frozen(True) # frozen headings instead of split panes
    sheet.set_horz_split_pos(rowx+1+r0) # in general, freeze after last heading row
    sheet.set_remove_splits(True) # if user does unfreeze, don't leave a split there
    for row in data:
        rowx += 1
        for colx, value in enumerate(row):
            if isinstance(value,datetime.date):
                sheet.write(rowx+r0, colx+c0, value,date_format)
            else:
                sheet.write(rowx+r0, colx+c0, value)                 
    book.save(file_name)             

def write_grf(grf,ofile,val_date):
    tot = []
    tot_agg = []
    sheets = []
    wb2 = xlwt.Workbook(encoding='utf-8')
    for bond in grf:
        tot = tot + bond[1]
        i=0
        while bond[1][i][0] <= val_date:
            i = i+1
        sheet_name = bond[0]
        j=1
        while sheet_name in sheets and j<10:
            j=j+1
            sheet_name = bond[0] + '(' + str(j) + ')'
        sheets.append(sheet_name)        
        write_xls_table(ofile,wb2,bond[1][i:],sheet_name,["Dagsetning","Höfuðstóll","Vextir"])
    tot.sort(key = lambda entry: entry[0])
    tot_agg.append(tot[0])
    j=0
    for i in xrange(1,len(tot)):
        if tot[i][0] == tot[i-1][0]:
            tot_agg[j][1] = tot_agg[j][1] + tot[i][1]
        else:
            j=j+1
            tot_agg.append(tot[i])
    i=0
    while tot_agg[i][0] <= val_date:
        i = i+1
    write_xls_table(ofile,wb2,tot_agg[i:],"Samtals",["Dagsetning","Höfuðstóll","Vextir"])

def add_inflation(sch,val_date,nom):  #BG 2014_07_01
#def add_inflation(sch,val_date):
    infl = np.zeros(150)
    infl_sch = []
    try:
        with open(nom,'r') as f:
            csvr=csv.reader(f,delimiter=";")
            for line in csvr:
                yr,inflation=int(line[0]),float(line[1][0:4].replace(',','.'))
                infl[yr-1] = inflation
    except IOError as err:
        pass # print 'File error: '+str(err) ATH. Commentað af Gumma    
    for row in sch:
        time_to_paym = row[0] - val_date
        row[1] = row[1]*infl[time_to_paym.days/365]**(time_to_paym.days/365.0)
        infl_sch.append(row)    
    return infl_sch

#def reval(infile,price_i,lsk_i, val_date = datetime.date.today(), arion = False,i=3.5,yc=False):
def reval(infile,price_i,lsk_i, val_date = datetime.date.today(), arion = False,i=3.5,yc=False,nom=False): #BG 2014_07_01
    bonds = get_excel_data(infile)
    rev_bonds = []
    grf = []
    conn = sqlite3.connect("/srv/www/tbg/database/bonds.db", detect_types=sqlite3.PARSE_DECLTYPES)
    c = conn.cursor()
    c.execute('SELECT * FROM types')
    for x in bonds:
        # Ath - commentað af Gumma print x[0]
        c.execute('SELECT * FROM bonds NATURAL JOIN types WHERE bond_id = ?',(x[0],))
        bond_id, end_d, intr, base_i, typ, start_d, first_id, first_pd, calc, ind, paypy, loan_type, adj_intr_date = c.fetchone()
        if calc == '1/1':
            calc = interest_calc.fixed_interest_calculator_11(intr)
        if calc == 'act/360':
            calc = interest_calc.fixed_interest_calculator_act360(intr)
        if calc == 'act/act':
            calc = interest_calc.fixed_interest_calculator_actact(intr)        
        if calc == '30/360':
            calc = interest_calc.fixed_interest_calculator_30360(intr)
        if calc == '30E/360':
            calc = interest_calc.fixed_interest_calculator_30E360(intr)
        if ind != 'ISK':
            index = True
        else:
            index = False
        bnd = bond_cf2.bond(bond_id,index,end_d,paypy,calc,val_date,start_d,first_id,first_pd,i,arion,yc)
        # Ath. commentað af Gumma --- print bnd.d_factor
        if ind == 'CPI':
            nominal = x[1]*price_i/base_i
        else:
            if ind == 'LSK':
                nominal = x[1]*lsk_i/base_i
            else:
                nominal = x[1]
        if adj_intr_date == False:
            bnd.set_dates()
        else:
            bnd.set_adj_dates()
        if loan_type == 'annuity':
            sch = bnd.annuity(nominal)
        if loan_type == 'standard':
            sch = bnd.standard(nominal)
        if loan_type == 'ibh':
            sch = bnd.ibh(nominal,intr)
        if loan_type == 'combo':
            c.execute('SELECT * FROM combos WHERE type = ?',(typ,))
            typ, f_prop, f_start, f_end, b_prop, b_start, b_end, a_prop, a_start, a_end = c.fetchone()
            sch = bnd.combo(f_prop,f_start,f_end,b_prop,b_start,b_end,a_prop,a_start,a_end,nominal)
        # Ath. commentað af Gumma ---- print bnd.d_factor,bnd.freq,sch
        pv, pv_sch = bnd.present_value(sch)
        # Ath. commentað af Gumma ---- print pv_sch
        if ind != 'ISK' and ind != 'CPI' and ind != 'LSK':
            c.execute('SELECT * FROM fx_rates WHERE type = ?',(ind,))
            typ, rate = c.fetchone()
            pv = pv*rate
            for row in pv_sch:
                row[1] = row[1]*rate
                row[2] = row[2]*rate
        reval = pv - x[2]
        y = [x[0],x[1],x[2],reval]
        rev_bonds.append(y)

        if nom: #BG 2014_07_01
            if ind == 'CPI' or ind == 'LSK':
#                sch = add_inflation(sch,val_date,nom)
                sch = add_inflation(sch,val_date,nom)  #BG 2014_07_01
        grf.append([x[0],sch])
    print "reval"
    return rev_bonds, grf

# BG 2014_07_01    
def main(user):

    os.chdir('/srv/www/tbg/file/' + user + '/')
    f = open('reval2_log.txt', 'r')
    input_dict = {}
    read = f.readlines()[0].split(";")

    for line in read:
        if len(line.split(" ")) > 2:
            list = line.split(" ")
            input_dict[line.split(" ")[0]] = datetime.date(int(list[1]), int(list[2]), int(list[3]))
        else:
            input_dict[line.split(" ")[0]] = line.split(" ")[1]

    if input_dict.has_key('yield_curve'):
            yield_curve = True
    else:
        yield_curve = False

    ASSETS_filn = input_dict['ASSETS_filn']
    DATE_val = input_dict['DATE_val']
    CPI_value = float(input_dict['CPI_value'])
    LSK_value = float(input_dict['LSK_value'])

    if input_dict['INFL_filn'] == 'Verdbolga':
        INFL_filn = False
    else:
        INFL_filn = input_dict['INFL_filn']

    if yield_curve:
        YIELDC_filn = input_dict['YIELDC_filn']
    else:
        YIELDC_filn = False

    REVAL_filn = '/srv/www/tbg/file/' + input_dict['user'] + '/' + input_dict['REVAL_filn']
    #if '.xls' not in REVAL_filn[-4:-1]:
    #   REVAL_filn += '.xls'
    CASHF_filn = '/srv/www/tbg/file/' + input_dict['user'] + '/' + input_dict['CASHF_filn']
    #if '.xls' not in CASHF_filn[-4:-1]: 
    #   CASHF_filn += '.xls'

    if input_dict.has_key('arion'):
        arion = True
    else:
        arion = False

    wbook = xlwt.Workbook()
    revbnd, grf = reval(ASSETS_filn, CPI_value, LSK_value, DATE_val,arion,3.5,YIELDC_filn,INFL_filn)
    write_xls_table(REVAL_filn,wbook,revbnd,"endurmat",["Skuldabref","Nafnverd","Bokfaert verd","Endurmat"])
    write_grf(grf,CASHF_filn,DATE_val)



print "end"
if __name__ == '__main__' :
    main()

完整追踪:

Environment:


Request Method: POST
Request URL: http://tbg/reval2/reikna/

Django Version: 1.6.5
Python Version: 2.6.5
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'reval2',
 'bjorncsv',
 'south',
 'index',
 'funds',
 'verkefni')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


    Traceback:
    File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
      112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "/usr/local/lib/python2.6/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
      22.                 return view_func(request, *args, **kwargs)
    File "/srv/www/tbg/reval2/views.py" in reikna_reval2
      63.       reval2.main(user)

    Exception Type: AttributeError at /reval2/reikna/
    Exception Value: 'module' object has no attribute 'main'

dir(reval2)的输出:

__builtins__
__doc__
__file__
__name__
__pakcage__
__path__
admin
forms
models
urls
views

1 个答案:

答案 0 :(得分:2)

你的名字有冲突。

包含Django代码的目录也称为reval2。由于该目录位于Python路径上,并且包含__init__.py,因此它是一个有效的Python包,因此在您import reval2时导入。

您必须重命名目录或脚本。