get_argument返回unicode数据类型的问题

本文详细解析了在Tornado框架中使用get_argument处理表单数据时,如何获取并理解URL查询参数,以及为什么get_argument方法不区分POST与GET请求。同时解释了get_argument返回的unicode数据类型是如何通过decode('utf-8')操作转换成字符串类型的,以供后续使用。

在 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_unicode was previously named _unicode not 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处理的原生参数,每个参数都是字典里面的一项,主要每个参数对应的项都是一个列表。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值