借助 Django 的 smart_str 和 smart_unicode 进行编码转换

转自:http://www.dirk.sh/diary/using-django-smart_str-smart_unicode/

Django 为字符编码的转换提供了非常简洁的方法:

1. django.utils.encoding.smart_unicode
2. django.utils.encoding.smart_str

我们在需要将用户提交的数据转换为 Unicode 的时候,可以使用 smart_unicode,而在需要将程序中字符输出到非 Unicode 环境(比如 HTTP 协议数据)时可以使用 smart_str 方法。拿 DDlog 来说,也有不少地方用到了这两个方法。

1、smart_unicode 在 DDlog 中的使用

Blog 的标签(Tag)一般多少会有中文,对于服务器环境来说,不会安装系统级的 UTF-8 环境,那么浏览器请求的 URL 中包含的中文会作为经过 urllib.quote 编码转换后的 UTF-8 字符串(注意,这种情况下,Django 不会自动转换为 Unicode),这里,我们在使用这个数据之前,需要进行一定的转换。

比较原始的方法类似如下:

1. def post_via_tag(request, tag):
2. from urllib import unquote
3. key = unquote(unicode(tag).encode('UTF-8'))
4. tag_as = Tag.objects.select_related().get(tag__iexact = key)

而如果使用 Django 的 smart_unicode,明显简洁得多(也更符合 DRY 原则):

1. def post_via_tag(request, tag):
2. from django.utils.encoding import smart_unicode
3. tag_as = Tag.objects.select_related().get(tag__iexact = smart_unicode(tag))
4. # ... other code

2、smart_str 在 DDlog 中的使用

DDlog 在接受评论的时候,会将评论者的姓名和邮件地址保存到 Cookie 中,以便该用户下次发表评论的时候自动显示相关信息。而评论者的姓名有可能是中文的,如果直接把中文字符串放到 Cookie 中,会引发 UnicodeEncodeError 异常。

这里需要进行去 Unicode 编码:

1. def post_comment(request, slug):
2. # ... other prepare code
3. response.set_cookie('COMMENT_AS_NAME', smart_str(comment_user.name), expired_at)

就这么简单便捷!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值