set_cookie raise exception when the value contains Unicode charset

52 views
Skip to first unread message

Xx Johnsua

unread,
Jan 29, 2017, 4:03:34 PM1/29/17
to Django users
Hello everyone,

Following is my code:

def post(self, request, *args, **kwargs):
   
self.object = self.get_object()
    form
= forms.CommentForm(request.POST or None)
   
if form.is_valid():
        response
= self.form_valid(form)
       
return self._set_cookies(response, form)
...

@transaction.atomic
def form_valid(self, form):
   
self.object = form.save(commit=False)
   
self.object.ip = get_remote_addr(self.request)
   
self.object.save()
   
return HttpResponseRedirect(self.get_success_url())

def _set_cookies(self, response, form):
    year
= 365 * 24 * 60 * 60
    response.set_cookie('nickname', form.cleaned_data['nickname'], max_age=year)
    response
.set_cookie('url', form.cleaned_data['url'], max_age=year)
    response
.set_cookie('email', form.cleaned_data['email'], max_age=year)
   
return response

But if the form.cleaned_data['nickname'] contains Chinese, an exception is raised:

Traceback (most recent call last):
 
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/handlers.py", line 138, in run
   
self.finish_response()
 
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/handlers.py", line 180, in finish_response
   
self.write(data)
 
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/handlers.py", line 274, in write
   
self.send_headers()
 
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/handlers.py", line 333, in send_headers
   
self._write(bytes(self.headers))
 
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/headers.py", line 142, in __bytes__
   
return str(self).encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 227-228: ordinal not in range(256)

So how to save the unicode data into cookie? I have to urlencode it manually?

Melvyn Sopacua

unread,
Jan 29, 2017, 8:48:47 PM1/29/17
to django...@googlegroups.com

On Sunday 29 January 2017 13:03:34 Xx Johnsua wrote:

 

 

> File

> "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versio

> ns/3.5/lib/python3.5/wsgiref/headers.py", line 142, in __bytes__

> return str(self).encode('iso-8859-1')

 

https://docs.djangoproject.com/en/1.10/ref/settings/#default-charset

 

I believe your default charset is set to 'iso-8859-1'.

--

Melvyn Sopacua

Xx Johnsua

unread,
Jan 30, 2017, 12:58:22 AM1/30/17
to Django users
But I never change the DEFAULT_CHARSET , this is my diffsettings:

$ ./manage.py diffsettings
AUTH_PASSWORD_VALIDATORS = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}]
AUTH_USER_MODEL = 'ucenter.User'
BASE_DIR = '/Users/shiyu/pro/python/talkbook'  ###
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'PORT': '', 'NAME': '/Users/shiyu/pro/python/talkbook/db.sqlite3', 'TEST': {'COLLATION': None, 'NAME': None, 'CHARSET': None, 'MIRROR': None}, 'PASSWORD': '', 'AUTOCOMMIT': True, 'TIME_ZONE': None, 'CONN_MAX_AGE': 0, 'USER': '', 'ATOMIC_REQUESTS': False, 'OPTIONS': {}, 'HOST': ''}}
DEBUG = True
DEFAULT_FROM_EMAIL = None
EMAIL_HOST = None
EMAIL_HOST_PASSWORD = None
EMAIL_HOST_USER = None
EMAIL_PORT = None
EMAIL_USE_SSL = None
EMAIL_USE_TLS = None
INSTALLED_APPS = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_select2', 'django_markup', 'bootstrap3', 'pure_pagination', 'django_gravatar', 'mptt', 'captcha', 'app.ucenter', 'app.front', 'app.manager']
IP_HEADER = None  ###
LANGUAGE_CODE = 'zh-hans'
LOGGING = {'version': 1, 'formatters': {'standard': {'format': '[%(asctime)s] - [%(levelname)s] - [%(name)s:%(lineno)d]  - %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S'}}, 'handlers': {'console': {'class': 'logging.StreamHandler', 'level': 'DEBUG'}, 'file': {'filename': '/Users/shiyu/pro/python/talkbook/error.log', 'class': 'logging.FileHandler', 'level': 'WARNING'}}, 'disable_existing_loggers': False, 'loggers': {'': {'handlers': ['console'], 'level': 'WARNING'}, 'talkbook': {'propagate': True, 'handlers': ['console'], 'level': 'DEBUG'}, 'django': {'handlers': ['file'], 'level': 'WARNING'}}}
LOGIN_REDIRECT_URL = 'manager:index'
LOGIN_URL = 'manager:login'
MARKUP_SETTINGS = {'markdown': {'safe_mode': 'escape', 'extension_configs': {'toc': {'anchorlink': True}}, 'extensions': ('extra', 'nl2br', 'codehilite', 'toc', 'linkify')}}  ###
MEDIA_ROOT = '/Users/shiyu/pro/python/talkbook/media'
MEDIA_URL = '/media/'
MIDDLEWARE = ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware']
OPTION_INI_PATH = '/Users/shiyu/pro/python/talkbook/conf/option.ini'  ###
PAGINATION_SETTINGS = {'SHOW_FIRST_PAGE_WHEN_INVALID': True, 'PAGE_RANGE_DISPLAYED': 5, 'MARGIN_PAGES_DISPLAYED': 2}  ###
ROOT_URLCONF = 'conf.urls'  ###
SECRET_KEY = '.............'
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SETTINGS_MODULE = 'conf.settings'  ###
STATIC_URL = '/static/'
TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/Users/shiyu/pro/python/talkbook/templates'], 'APP_DIRS': True, 'OPTIONS': {'context_processors': ['django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'talkbook.context.global_site_context']}}]
TIME_ZONE = 'Asia/Shanghai'
USE_L10N = True
USE_TZ = True
WSGI_APPLICATION = 'talkbook.wsgi.application'


在 2017年1月30日星期一 UTC+8上午9:48:47,Melvyn Sopacua写道:
Reply all
Reply to author
Forward
0 new messages