django

首页django
26
Nov
0

CSRF Failed: CSRF token missing or incorrect

开启CSRF及
SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = True
后,遇到错误:CSRF Failed: CSRF token missing or incorrect

解决方法一:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.TokenAuthentication',)
}

解决方法二:

MIDDLEWARE_CLASSES = (
'store.disable.DisableCSRF',
)

disable.py

class DisableCSRF(object):

def process_request(self, request):
    setattr(request, '_dont_enforce_csrf_checks', True)
22
Jun
0

django文件下载,文件名为中文产生浏览器不识别文件名的问题

原因:
各浏览器对文件名的编码引起的

解决方法有如下两种:

  1. 按照http标准组织的方式修改(然而这种方式,并没有成功!)
  2. django.utils.encoding import escape_uri_path

response = HttpResponse(content, content_type='application/octet-stream')
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(file_name))

2.直接按照各浏览器接受的编码进行编码(成功 已测试谷歌浏览器)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename=' + down_name.encode('utf-8').decode('ISO-8859-1')

ps.各浏览器接受的编码列表

IE浏览器,采用URLEncoder编码
Opera浏览器,采用filename*方式
Safari浏览器,采用ISO编码的中文输出
Chrome浏览器,采用Base64编码或ISO编码的中文输出
FireFox浏览器,采用Base64或filename*或ISO编码的中文输出

15
Jun
0

django下载文件

def file_download(file_name,chunk_size=512):

def file_iterator(file_name):
    with open(file_name,'rb') as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break
from django.http import StreamingHttpResponse
response = StreamingHttpResponse(file_iterator(file_name))
response['Content-Type'] = 'application/octet-stream'
if os_is_linux():
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(file_name[file_name.rfind('/') + 1:])
else:
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(file_name[file_name.rfind('\\') + 1:])
return response