django smart_str和smart_unicode

2015/04/21 22:55
阅读数 324

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
分享
返回顶部
顶部