在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. 安装Ubuntu 18.04后的一些操作

    安装Ubuntu 18.04后的一些操作 1.设置root密码 sudo passwd 2.登陆root(输入密码后看到井号就是切换成为root账户) su 3.删除预装 apt-get remove ...

  2. MySQL开发——【字段类型、约束】

    创建数据表 基本语法: create table 数据表名称( 字段名称 字段类型 字段约束, ... )[表选项]; 字段类型 整数型 ,有符号型,可以表示 ,有符号型,可以表示 mediumint ...

  3. Difference Among Mercedes Star Diagnostic Tool MB Star C3 C4 C5 C6

    Mercedes Star Diagnostic Tool newly update to MB Star C6.There are many star diangostic tool in the ...

  4. Linux学习小记(1)

    学习Linux,进行阶段性总结,权当笔记方便日后翻阅和查看. 在此特别推荐peida的博客,他的有关Linux的理解个人感觉深入浅出,很适合入门的小白来理解和学习. 说一说针对IP的修改,ifconf ...

  5. shell启动执行cypher语句

    1.跳转到目录:cd /data/soft/neo4j-community-not/ 2.修改配置文件:nano ./conf/neo4j.conf: 3. 登录:bin/cypher-shell - ...

  6. poj 3279(暴力)

    题意:有一个n*m的格子,每个格子都有黑白两面(0表示白色,1表示黑色).我们需要把所有的格子都反转成黑色,每反转一个格子,它上下左右的格子都会跟着反转.请求出用最小步数完成反转时每个格子反转的次数. ...

  7. 使用Linux自带日志滚动工具logrotate滚动redis日志示例

    截至到redis-5.0版本,redis仍然不会自动滚动日志文件,如果不处理则日志文件日积月累越来越大,最终将导致磁盘满告警: # ls -lh total 12G -rw-r--r-- 1 redi ...

  8. 【repost】H5总结

    1.新增的语义化标签: <nav>: 导航 <header>: 页眉 <footer>: 页脚 <section>:区块 <article> ...

  9. HTCVive使用

    1.设备的安装与配置 https://wenku.baidu.com/view/fa172fd7482fb4daa48d4b44.html?from=search 2.接入SDK.实现简单示例场景.更 ...

  10. Service启动过程分析

    Service是一种计算型组件,用于在后台执行一系列的计算任务.由于工作在后台,因此用户是无法直接感知到它的存在.Service组件和Activity组件略有不同,Activity组件只有一种运行模式 ...