2016-06-29 7 views
1

私はダウンロード可能なテキストファイルを作成しようとしていますが、これを達成したと思いますが、コードを実行すると、Django - オンザフライで作成されたテキストファイルの許可が拒否されました

このテキストファイルを開くと、ファイルシステムのどこにでも作成されますか?私はちょうどそれらを作成し、それらをユーザーのマシンにダウンロードしている、これらのファイルを保存したいいけないよう

IOError at /networks/configs/STR-RTR-01/7 
[Errno 13] Permission denied: u'STR-CARD-RTR-01.txt' 

設定:

目標は、ユーザーがファイルをダウンロードできるリンクを提供するものである場合
def configs(request, device, site_id): 
    site = get_object_or_404(ShowroomConfigData, pk=site_id) 
    config_template = get_object_or_404(ConfigTemplates, device_name=device) 

    file_name = device[:4] + site.location.upper()[:4] + "-" + device[4:] + ".txt" 

    device_config = None 
    with open(file_name, 'w') as config_file: 
     device_config = env.from_string(config_template.config) 

     device_config.stream(
      STR   = site.location.upper()[:4], 
      IP   = site.subnet, 
      BGPASNO  = site.bgp_as, 
      LOIP  = site.r1_loopback_ip,   
      Location = site.location, 
      Date  = site.opening_date, 
     ).dump(config_file) 

    return render(request, file_name, { 
    }) 
+0

何OSを使用していて、どのようなウェブサーバ? – Aya

+0

あなたのDjangoプロセスは、そのフォルダへの適切なアクセス権を持っていません。 –

+0

CentosとApacheを使用していますが、どのフォルダに入っているのかわかりません。テキストファイルはフォルダに入れなければなりませんか?とにかくファイルを閉じた後に保存されませんか? – AlexW

答えて

0

自動的に生成されるため、ディスクに何も書き込む必要はありません。

あなただけのPython文字列で目的のコンテンツを構築し、ユーザーのブラウザが保存するようにユーザーのためのデフォルトのファイル名を指定するには、ファイルをダウンロードするのではなく、それを表示し、そのfilenameパラメータなければならないことを示唆しContent-Dispositionヘッダーを使用することができますファイルとして。

Aこれを行いビュー機能のややシンプルな例...あなたは

from django.http import HttpResponse 

def get_config_file(request): 

    filename = 'config.txt' 
    content = 'This is the content of my config file' 
    content_type = 'text/plain' 
    content_disposition = 'attachment; filename=%r' % filename 

    response = HttpResponse(content, content_type=content_type) 
    response['Content-Disposition'] = content_disposition 

    return response 
+0

完璧!ありがとうございました! – AlexW

+0

@AlexW FWIW 'HttpResponse'オブジェクトをファイルとして扱うこともできるので、' response = HttpResponse(content_type = content_type) 'と' device_config.stream(...)。dump (応答) ' – Aya

関連する問題