zoukankan      html  css  js  c++  java
  • 借助 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)

    就这么简单便捷!

  • 相关阅读:
    洛谷P3003 [USACO10DEC]苹果交货Apple Delivery
    洛谷P1576 最小花费
    洛谷P1821 [USACO07FEB]银牛派对Silver Cow Party
    洛谷P1948 [USACO08JAN]电话线Telephone Lines
    洛谷P3371【模板】单源最短路径
    洛谷P2384最短路
    FirstOfAll
    Proxy模式:管理第三方API
    Abstract Server模式,Adapter模式和Bridge模式
    Observer模式
  • 原文地址:https://www.cnblogs.com/ajianbeyourself/p/4883487.html
Copyright © 2011-2022 走看看