目次

目次

Bottleで受け取ったリクエストパラメータが文字化けした時にしたこと

アバター画像
福山
アバター画像
福山
最終更新日2017/04/25 投稿日2017/04/25

日本語をリクエストパラメータで渡した際に文字化けしたのでそれへの対応を書きます。 今回は例として、q=アイウエオと投げます。

文字化けしました

元々下のように書いていました。

    @route('/artists')
    def artists():
        req_param = {}
        req_param['q'] = request.params['q'] # アイウエオが代入される
        print('q: ', req_param['q'])

    ...後続処理

出力結果

q: アイウã

文字化けしました。

調べてみる

ここのWTForms supportのところに書いてありました。

Note
In Python 2 all keys and values are byte-strings. If you need unicode, 
you can call FormsDict.getunicode() or fetch values via attribute access. 
Both methods try to decode the string (default: utf8) and return an empty string if that fails.
 No need to catch UnicodeError:

>>> request.query['city']
'G\xc3\xb6ttingen'  # A utf8 byte string
>>> request.query.city
u'Göttingen'        # The same string as unicode

In Python 3 all strings are unicode, but HTTP is a byte-based wire protocol. 
The server has to decode the byte strings somehow before they are passed to the application. 
To be on the safe side, WSGI suggests ISO-8859-1 (aka latin1), a reversible single-byte codec that 
can be re-encoded with a different encoding later. 
Bottle does that for FormsDict.getunicode() and attribute access, but not for the dict-access methods. 
These return the unchanged values as provided by the server implementation, which is probably not what you want.

>>> request.query['city']
'Göttingen' # An utf8 string provisionally decoded as ISO-8859-1 by the server
>>> request.query.city
'Göttingen'  # The same string correctly re-encoded as utf8 by bottle
If you need the whole dictionary with correctly decoded values (e.g. for WTForms), you can call FormsDict.decode() to get a re-encoded copy.

ちなみに試したPythonのバージョンは、3.5.1です。

変更

    @route('/artists')
    def artists():
        req_param = {}
        req_param['q'] = request.params.q # アイウエオが代入される
        print('q: ', req_param['q'])

    ...後続処理

出力結果

q: アイウエオ
アバター画像

福山

最近技術触れてないかも

目次