- Chapter: Tornado表单处理
在 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处理的原生参数,每个参数都是字典里面的一项,主要每个参数对应的项都是一个列表。