在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. Android如何在http头信息里设置参数

    在使用http请求server时常常要传递一些参数给server,如IMEI号.平台号.渠道号.客户端的版本号等一些通用信息,像这些参数我们没有必要每次都拼在url后,我们可以统一添加到http头里. ...

  2. (转载)Android开发——Android中常见的4种线程池(保证你能看懂并理解)

    0.前言 转载请注明出处:http://blog.csdn.net/seu_calvin/article/details/52415337 使用线程池可以给我们带来很多好处,首先通过线程池中线程的重用 ...

  3. Pandas 合并merge

    pandas中的merge和concat类似,但主要是用于两组有key column的数据,统一索引的数据. 通常也被用在Database的处理当中. 1.依据一组key合并 >>> ...

  4. MySQL数据查询之单表查询

    单表查询 简单查询 - 创建表 DROP TABLE IF EXISTS `person`; CREATE TABLE `person` ( `id` ) NOT NULL AUTO_INCREMEN ...

  5. SSM三大框架整合

    三大框架整合的思路 1.Dao层: Mybatis的配置文件:SqlMapConfig.xml 不需要配置任何内容,需要有文件头.文件必须存在. applicationContext-dao.xml: ...

  6. Java之IO流总结

    IO流·Java流式输入/输出原理·Java流类的分类·输入/输出流类·常见的节点流和处理流·文件流·缓冲流·转换流·数据流·Print流·Object流 ①Java流式输入/输出原理         ...

  7. rapidjson 的练习

    // JsonCpp.cpp: 定义控制台应用程序的入口点. // #include "stdafx.h" #include <string> #include < ...

  8. HTML语言

    复习: 1.Web项目的部署结构  静态Web技术(客户端技术):提供的内容任何人在任何时间访问都是一样的 HTML/CSS/JS/Flash.... 动态Web技术(服务器端技术):提供的内容不同人 ...

  9. numpy版本查看以及升降

     如题,参考:https://zhuanlan.zhihu.com/p/29026597 pip show numpy 查看numpy版本; pip install -U numpy==1.12.0, ...

  10. vue全局后置钩子afterEach

    beforeEach是路由跳转前执行的,afterEach是路由跳转后执行的. afterEach只有两个参数  afterEach((to,from)=>{}) 例子: router.afte ...