CodeDrift
V2EX  ›  问与答

请教个关于 python\Dajngo 设置 cookie 时编码的问题。

  •  
  •   CodeDrift · Jul 21, 2015 · 2454 views
    This topic created in 3974 days ago, the information mentioned may be changed or developed.

    具体代码如上
    这里获取一个ubid 然后通过模型获取了一个对象,其中的两个属性 学校名称和班级名称,该字符串现在是unicode类型的,学校名称和班级名称都为汉语。大概如下。xx县第一实验小学|102班

    现在将他们拼接成字符串,然后跟这个ubid设置成一个key value的cookie。
    设置cookie时如果不进行encode('utf-8'),则报'ascii' codec can't encode characters in position 0-8: ordinal not in range(128)错,加上后正常。

    在前台页面获取到这个cookie.值为
    \351\203\221\345\267\236\345\270\202\346\203\240\346\265\216\345\214\272\344\270\234\351\243\216\350\267\257\345\260\217\345\255\246|105\347\217\255

    请问要怎么进行处理,还原为中文。。查了好久没找到才来请教的 。先谢谢了!

    6 replies    2015-07-22 11:55:09 +08:00
    CodeDrift
        1
    CodeDrift  
    OP
       Jul 21, 2015
    稍微顶一下。。 打扰啦~
    yahoo21cn
        2
    yahoo21cn  
       Jul 21, 2015 via Android
    2还是3,文件本身是什么编码的,文件头是否声名了编码
    CodeDrift
        3
    CodeDrift  
    OP
       Jul 22, 2015
    @yahoo21cn python2 py文件声明了# coding=utf-8
    CodeDrift
        4
    CodeDrift  
    OP
       Jul 22, 2015
    好难解决。。
    yahoo21cn
        5
    yahoo21cn  
       Jul 22, 2015
    print str('\351\203\221\345\267\236\345\270\202\346\203\240\346\265\216\345\214\272\344\270\234\351\243\216\350\267\257\345\260\217\345\255\246|105\347\217\255').decode('string_escape')
    yahoo21cn
        6
    yahoo21cn  
       Jul 22, 2015
    好像直接pring就可以了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   895 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 19:27 · PVG 03:27 · LAX 12:27 · JFK 15:27
    ♥ Do have faith in what you're doing.