首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >unicode_literals和StringIO与正确的做事方式

unicode_literals和StringIO与正确的做事方式
EN

Stack Overflow用户
提问于 2016-01-29 09:29:31
回答 1查看 1.5K关注 0票数 0

是的,另一个杂乱无章的unicode问题。

我有一个代码片段:

代码语言:javascript
复制
from __future__ import unicode_literals
import requests
from lxml import etree

class Review(object):
    def __init__(self, site_name):
        self.parser = etree.HTMLParser()
        # other things

     def get_root(self, url):
        # snip snip
        resp = requests.get(url)
        html = resp.text
        root = etree.parse(StringIO(html), self.parser)
        return root

这是可行的。

在Python 3中,这可能类似于:

代码语言:javascript
复制
from urllib import request
# stuff to detect encoding of page
response = request.urlopen(req)
html = response.read().decode(detected_encoding)
root = etree.parse(StringIO(self.html_doc), self.parser)

当页面声明的编码不是它的实际编码时,需要处理大量丑陋的代码。

我的问题是,unicode_literals对我来说本质上是巫毒,我对自己的无知感到尴尬。为什么root = etree.parse(StringIO(html), self.parser)在大部分时间使用导入的unicode_literals神奇地工作,在python2.7中实际应该做什么?

例如,我现在正在修复的Django代码中有这个构造:

代码语言:javascript
复制
stuff = StringIO(unicode(request.body))

这是坏的和错误的。但是我无法解释为什么它是坏的和错误的,只是说它破坏了许多不是utf-8的编码。

我知道字符串是,在python 3中编码的字符串,python 2.7中的ascii字符串。我知道StringIO让我把字符串当作缓冲区对待。我知道stuff = StringIO(unicode(request.body))会使用导入的unicode_literals,但我不知道为什么我不知道该怎么做才能避免编写大量丑陋的代码来检测Django的request.body编码,这也是我发布这篇文章的原因。

tl;dr

unicode_literals在python2.7中是什么,它会修复stuff = StringIO(unicode(request.body))中的Django错误吗?副作用是什么?

非常感谢

EN

回答 1

Stack Overflow用户

发布于 2016-01-29 09:52:49

unicode文本不会影响像StringIO(unicode(request.body))这样的代码。它所做的就是在Python 2中不使用前缀时更改文字字符串的类型。

没有unicode文本

代码语言:javascript
复制
u'y'  # unicode string
b'z'  # byte string
'x'  # byte string

使用unicode文字

代码语言:javascript
复制
from __future__ import unicode_literals
u'y'  # unicode string
b'z'  # byte string
'x'  # *unicode* string

当您使用unicode文本时,您的行为与Python相同(不能在Python3.0到3.2中使用3.3+ )。

request.body从字节字符串转换为unicode字符串的正确方法是在将字节字符串转换为unicode时指定编码。

代码语言:javascript
复制
stuff = StringIO(body.decode('utf-8'))

如果编码不是utf-8,则更改编码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35080995

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档