我正在尝试快速制作可下载的文本文件,我想我已经实现了这一点,但是当我运行代码时,我得到了权限被拒绝的错误。
另外,当我打开此文本文件时,是否会在文件系统中的任何位置创建它?因为我不想存储这些文件,只需创建它们并将它们下载到用户计算机
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, {
})
如果目标是提供一个链接,使用户可以下载自动生成的文件,则无需在磁盘上写入任何内容。
您可以只使用Python字符串构建所需的内容,并使用Content-Disposition
标头建议用户的浏览器应下载文件而不是显示文件,并使用其filename
参数为用户指定将文件另存为的默认文件名。
一个稍微简单一些的视图函数示例,它执行此操作...
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句