在Django中,向cookie写入中文字符后会报错;如向cookie中保存用户名,当用户名存在中文字符时:

Traceback (most recent call last):
  File , in run
    self.finish_response()
  File , in finish_response
    self.write(data)
  File , in write
    self.send_headers()
  File , in send_headers
    self._write(bytes(self.headers))
  File , in __bytes__
    return str(self).encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 145-146: ordinal not in range(256)
[/Apr/ ::]
----------------------------------------
Exception happened during processing of request )
Traceback (most recent call last):
  File , in run
    self.finish_response()
  File , in finish_response
    self.write(data)
  File , in write
    self.send_headers()
  File , in send_headers
    self._write(bytes(self.headers))
  File , in __bytes__
    return str(self).encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 145-146: ordinal not in range(256)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File , in run
    self.handle_error()
  File , in handle_error
    super(ServerHandler, self).handle_error()
  File , in handle_error
    self.finish_response()
  File , in finish_response
    self.write(data)
  File , in write
    self.send_headers()
  File , in send_headers
    if not self.origin_server or self.client_is_modern():
  File , in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File , in process_request_thread
    self.finish_request(request, client_address)
  File , in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File , in __init__
    super(WSGIRequestHandler, self).__init__(*args, **kwargs)
  File , in __init__
    self.handle()
  File , in handle
    handler.run(self.server.get_app())
  File , in run
    self.close()
  File , in close
    self.status.split()[], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'

  此时可以使用Json模块的dumps()和loads(),将其序列化,再进行反序列化;

  如记录用户名时,先将用户名进行序列化,再写入到cookie中。而在读取cookie之后,再将其反序列化即可

  

  dumps / loads 用法:

import json
username='用户1'
username=json.dumps(username)
username
'"\\u7528\\u62371"'
# 反序列化
username=json.loads(username)
username
'用户1'

  

  在Django中:

                if remember=='on':
                    # 记住用户名
                    # 如果username是中文,设置cookies时会报错
                    # cookie 中文编码处理
                    username=json.dumps(username)
                    response.set_cookie('username',username,max_age=7*24*3600)

                else:
                    # 取消记住用户名
                    response.delete_cookie('username')
        if 'username' in request.COOKIES:
            username=request.COOKIES.get('username')
            username=json.loads(username)

  

  

Django | Cookie 中文编码的问题的更多相关文章

  1. Django cookie相关操作

    Django cookie 的相关操作还是比较简单的 首先是存储cookie #定义设置cookie(储存) def save_cookie(request): #定义回应 response = Ht ...

  2. falsk 与 django cookie和session存、取、删的区别

    falsk cookie的存取删需导入from flask import Flask,make_response,request# 存COOKIE的方法@app.route('/setcookie') ...

  3. django cookie、session

    Cookie.Session简介: Cookie.Session是一种会话跟踪技术,因为http请求都是无协议的,无法记录上一次请求的状态,所以需要cookie来完成会话跟踪,Seesion的底层是由 ...

  4. Python之路-(Django(Cookie、分页))

    Cookie 分页 1.获取Cookie: request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, sal ...

  5. Django Cookie 和 Sessions 应用

    在Django里面,使用Cookie和Session看起来好像是一样的,使用的方式都是request.COOKIES[XXX]和request.session[XXX],其中XXX是您想要取得的东西的 ...

  6. Python Web框架篇:Django cookie和session

    part 1 概念 在Django里面,cookie和session都记录了客户端的某种状态,用来跟踪用户访问网站的整个回话. 两者最大的区别是cookie的信息是存放在浏览器客户端的,而sessio ...

  7. 28.Django cookie

    概述 1.获取cookie request.COOKIES['key'] request.COOKIES.get('key') request.get_signed_cookie(key, defau ...

  8. 5.Django cookie

    概述 1.获取cookie request.COOKIES['key'] request.COOKIES.get('key') request.get_signed_cookie(key, defau ...

  9. Django Cookie,Session

    Cookie Cookie的由来 HTTP协议是无状态的,每次请求都是独立的,对服务器来说,每次的请求都是全新的,上一次的访问是数 据是无法保留到下一次的 某些场景需要状态数据或者中间数据等相关对下一 ...

随机推荐

  1. struts2遇到的一个问题。

    2018-09-12 好几年没配过struts2了,今天想用最新版的配一下,一直不成功,后来才知道,一堆红色输出里面有这样一句 ERROR StatusLogger No log4j2 configu ...

  2. JavaSE 初学进度条JProgressBar

    预备知识 创建进度条类后将其直接加入JFrame看看效果 public class JProgressBarDemo2 { public static void main(String args[]) ...

  3. PowerDesigner 缺省值 引号 问题

    在使用PowerDesigner做为MySQL数据库建模的时候,总是有这样的问题,例如我需要一个字段 createTime 类型是 Timestamp,要求这个字段默认值为系统当前时间,于是我给这个字 ...

  4. mySQL配置文件、备份与恢复

    mysql配置文件 mysql的配置文件为/etc/my.cnf 配置文件查找次序:若在多个配置文件中均有设定,则最后找到的最终生效 /etc/my.cnf --> /etc/mysql/my. ...

  5. Chapter3_操作符_直接常量和指数计数法

    (1)直接常量 在程序中使用直接常量,相当于指导编译器,告诉它要生成什么样的类型,这样就不会产生模棱两可的情况.比如flaot a = 1f等,后缀表示告诉编译器想生成的类型.常用的后缀有l/L(lo ...

  6. jvm参数与GC

    一.JVM的新生代.老年代.与永久代 JVM中的堆,一般分为三大部分:新生代.老年代.永久代: 1.新生代:主要是用来存放新生的对象,一般占据堆的1/3空间.由于频繁创建对象,所以新生代会频繁触发Mi ...

  7. MFC头文件

    AFX.H struct CRuntimeClass; // object type information class CObject; // the root of all objects cla ...

  8. 一个自己实现的js表单验证框架。

    经常要做一些表单验证的操作,每次都是用现成的框架,比如jquery,bootstrap等的验证插件,虽然也很强大,也很好用,可就是用起来需要引入许多js库,还有里面功能太多,感觉不太符合自己的需求.最 ...

  9. 833. Find And Replace in String

    To some string S, we will perform some replacement operations that replace groups of letters with ne ...

  10. Ubuntu18.04安装网易云音乐

    一. 安装 去网易云官网下载对应于ubuntu系统的安装包 安装依赖 dpkg -s libcanberra-gtk-module #检查依赖是否安装 sudo apt install libcanb ...