django:Content-Disposition filename:日本語 pdf csv output

2022-08-20 21:37:24 浏览数 (1)

要件:

output CSV,PDF file

文件名:包含英语以外文字

対策:

英語以外のファイル名:url encode 必要

python :urllib.parse

环境,语言

Django4.1

python3.9

output csv sample

代码语言:python代码运行次数:0复制
from django.http import JsonResponse, HttpResponse
import json, csv

def data_output_csv(request):
    if request.method == 'POST':
        bts = Data.objects.all()

        # レスポンスの設定
        response = HttpResponse(content_type='text/csv;')
        filename = 'data.csv'  # ダウンロードするcsvファイル名
        response['Content-Disposition'] = 'attachment; filename={}'.format(filename)

        writer = csv.writer(response)
        for row in bts:
            writer.writerow([
                row.code, 
                row.name,
            ])

        return response

file name: en

代码语言:python代码运行次数:0复制
filename = 'data.csv'  # ダウンロードするcsvファイル名
response['Content-Disposition'] = 'attachment; filename={}'.format(filename)
print(response['Content-Disposition'])

#print 結果
attachment; filename=data.csv

file name: ja / zh

代码语言:python代码运行次数:0复制
# url encode对应
import urllib.parse

filename = 'data_日本語.csv'  # ダウンロードするcsvファイル名
response['Content-Disposition'] = 'attachment; filename={}'.format(filename)
print(response['Content-Disposition'])

quoted_filename = urllib.parse.quote(filename)
response['Content-Disposition'] = 'attachment; filename={}'.format(quoted_filename)
print(response['Content-Disposition'])

#print 結果
---------------------
=?utf-8?b?YXR0YWNobWVudDsgZmlsZW5hbWU9ZGF0YV/ml6XmnKzoqp4uY3N2?=
---------------------
attachment; filename=data_日本語.csv
---------------------


# 多浏览器对应
response['Content-Disposition'] = 'attachment; filename={}; filename*=UTF-8''{}'.format(quoted_filename, quoted_filename)

出力PDF実例

代码语言:python代码运行次数:0复制
# pdf output 
def output_order_pdf(request):

    po = Order.objects.filter(pk=1).first()

    num_3 = str(po.version).zfill(3)
    yymm = datetime.now().strftime("%y%m")
    filename = yymm   "【発注書】"   po.supplier_name   "_"   po.appl_purchase.purchase_id   "_"   num_3   ".pdf"
    quoted_filename = urllib.parse.quote(filename)

    # 自定義pdf 出力methodより、バイナリデータを取得
    pdf:io.StringIO = template_to_pdf('templete/order_output.html',{'order':po}) 
    response = HttpResponse(content_type='application/pdf;')
    response['Content-Disposition'] = 'attachment; filename={}; filename*=UTF-8''{}'.format(quoted_filename, quoted_filename)
    #response['Content-Disposition'] = 'attachment; filename={}'.format(quoted_filename)
    
    print(response['Content-Disposition'])
    
    response.write(pdf.getvalue())

    return response


# print ファイル名
attachment; filename=2208【発注書】ダミー仕入先_Padmin220811225340_035.pdf; 
filename*=UTF-82208【発注書】ダミー仕入先_Padmin220811225340_035.pdf
image.pngimage.png

0 人点赞