您的位置:首页 > 其它

get_argument返回unicode数据类型的问题

2015-02-02 21:51 176 查看
Chapter: Tornado表单处理

1. 使用get_argument获取url
query参数

2. 为何get_argument不区分POST与GET?

3. get_argument返回unicode数据类型的问题

在 Tornado 里,self.get_argument返回的数据类型为unicode

1
chars
=
self
.get_argument(
'chars'
)
2
self
.write(
str
(
type
(chars))
)
3
#
输出
4
#
<type 'unicode'>
get_argument在获取数据的时候,会进行decode("utf-8")操作,因为get_argument最终调用了tornado.escape下面的to_unicode方法,也就是argument会通过decode("utf-8")来转成unicode:

01
def
to_unicode(value):
02
"""Converts
a string argument to a unicode string.
03
04
If
the argument is already a unicode string or None, it is returned
05
unchanged.
Otherwise it must be a byte string and is decoded as utf8.
06
"""
07
if
isinstance
(value,
_TO_UNICODE_TYPES):
08
return
value
09
assert
isinstance
(value,
bytes)
10
return
value.decode(
"utf-8"
)
11
12
#
to_unicodewas previously named _unicodenot because it was private,
13
#
but to avoid conflicts with the built-in unicode() function/type
14
_unicode
=
to_unicode
get_argument获取数据之后一般需要先使用u.encode('utf-8')转换成string类型后才能使用。

如果用get_argument无法获取数据,可以用更加原始的方法通过self.request.arguments获取GET或者POST的所有参数字典,这个字典是未经过decode处理的原生参数,每个参数都是字典里面的一项,主要每个参数对应的项都是一个列表。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐