2016-04-09 9 views
0

良い一日、私は、次のエラーを受信して​​います:djangoのローカルテキストファイルの内容を正しく読み込むには?ファイルから読み取るしようとしているときに

Exception Type: KeyError 
Exception Value:  
'opened' 

エラーがreadFileので怒鳴るラインから来ている:

if fileHandler['opened']: 

と、これはどのようにあります以下のように私の見解はなりますproject.settingsから がdjango.core.filesから TEXT_FILEインポートdjango.shortcutsからファイルをインポート

def home_view(request): 
    context = {'error': ''} 
    readFile(context) 
    render(request, 'index.html', context) 


def readFile(context): 
    fileHandler = open_file(context, 'r') 

    if fileHandler['opened']: 
     file = File(fileHandler['handler']) 
     read_content(file, context) 

     file.close() 


def open_file(context, mode): 
    try: 
     fileHandler = open(text_file, mode) 
     return {'open': True, 'handler': fileHandler} 

    except IOError: 
     context['error'] += 'Unable to open file.\n' 
    except: 
     context['error'] += 'Unexpected exception in openFile method.\n' 
     return {'opened':False, 'handler': None} 


def read_content(file, context): 
    context['fileContent'] = '' 
    for sentence in file.chunks(10): 
     context['fileContent'] += sentence 
0123をレンダリングインポートの

と私の設定:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
text_file = os.path.join(BASE_DIR, 'my_file.txt') 

ウィル本当にappreaciateanyヘルプ。

+0

open_file関数の内部にあるように、キーを 'open'に設定していて、存在しない 'opened'キーにアクセスしています。 – Abhinav

+0

@Abhinavありがとうございましたありがとうございました –

答えて

0

ビューの3行目にreadFile関数の宣言がありません!

def home_view(request): 
    context = {'error': ''} 
    readFile(context) # HERE! 
    render(request, 'index.html', context) 

多分あなたの問題はここにありますか?

+0

ご迷惑をおかけして申し訳ありません、私はそれを置き換えました –

関連する問題