V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
72vc48
V2EX  ›  Python

从 flask 的 request.form 中取得值之后,怎样作 urldecode?

  •  
  •   72vc48 · 2016-11-19 16:01:01 +08:00 · 3892 次点击
    这是一个创建于 2716 天前的主题,其中的信息可能已经有所发展或是发生改变。
    一个表单需要提交一个中文字符,如 astr=%E6%88%91%E4%BB%AC%E5%A4%A7%E5%AE%B6 ,原字符是“我们大家”, UTF-8 编码,然后在视图函数中用 request.form['astr']取得的值也是这个%E6%88%91%E4%BB%AC%E5%A4%A7%E5%AE%B6 ,我想用 urllib.unquote(),结果返回的字符串类型竟然是 unicode ,并且已经是乱码了,求解怎样进行 urldecode 合适?
    8 条回复    2016-11-19 17:48:40 +08:00
    72vc48
        1
    72vc48  
    OP
       2016-11-19 16:03:02 +08:00
    s = urllib.unquote(request.form['astr'])
    assert type(s) == unicode
    sun1991
        2
    sun1991  
       2016-11-19 16:49:34 +08:00
    以下是我在 py2 上的测试结果, 你用的是 py3?

    Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32
    Type "copyright", "credits" or "license()" for more information.
    >>> ss = '%E6%88%91%E4%BB%AC%E5%A4%A7%E5%AE%B6'
    >>> import urllib
    >>> s = urllib.unquote(ss)
    >>> s
    '\xe6\x88\x91\xe4\xbb\xac\xe5\xa4\xa7\xe5\xae\xb6'
    >>> s.decode('utf8')
    u'\u6211\u4eec\u5927\u5bb6'
    >>> print(s.decode('utf8'))
    我们大家
    >>> type(s)
    <type 'str'>
    >>>
    72vc48
        3
    72vc48  
    OP
       2016-11-19 17:00:01 +08:00
    @sun1991
    我用的是 Python 2.7.11 。
    我在 shell 里边试验是和你的试验结果一样的,但是到了 flask 的视图函数中,情况就不同了。 urllib.unquote()的结果竟然已经是 unicode
    banxi1988
        4
    banxi1988  
       2016-11-19 17:15:40 +08:00
    Flask 默认已经使用 utf-8 编码对 请求参数(如 Query 参数) 进行了 utf-8 解码.
    并且已经进行了 url_unquote_plus 操作了.
    你要测试也是侧重在 Flask 环境下测试解决问题.
    在 Python 或 iPython 上直接对原始字符串进行操作.场景不一样.
    72vc48
        5
    72vc48  
    OP
       2016-11-19 17:17:32 +08:00
    搞定。分享一下。从 request.form 中取得的值,是 unicode 的,作为参数传给 urllib.unquote(), urllib.unquote 就会返回 unicode 类型的字符串。那么只要 request.form['astr'].encode('ascii')一下,再传进去,就能返回 str 类型了(在这里其实是 utf-8 编码)。
    72vc48
        6
    72vc48  
    OP
       2016-11-19 17:20:36 +08:00
    @banxi1988 一开始我也以为是环境不同,结果是传参类型的问题。花掉我一下午的时间。。。
    jimzhong
        7
    jimzhong  
       2016-11-19 17:41:42 +08:00
    py3 里面好像会自动解码
    72vc48
        8
    72vc48  
    OP
       2016-11-19 17:48:40 +08:00
    @jimzhong 有机会试试
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2481 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:03 · PVG 00:03 · LAX 09:03 · JFK 12:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.