LoginSignup
7

More than 3 years have passed since last update.

posted at

updated at

bottleで文字列を取得しようとすると日本語が文字化けする -> 解消

0.はじめに

bottleの詳しい使い方等は他に良い記事を書いている方が大勢いらっしゃいますので、導入方法や解説はそちらにおまかせします。

New!! getunicode を使う方法 (2019/03/19 追記)

私の環境(一応)

macOS Sierra 10.12.2
Python 3.5.2
bottle 0.13-dev

1.現象

こんな感じの入力フォームを作って、

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Artist Search</title>
</head>
<body>
<b>検索語句を入れてください。</b>
<form action="/" method="post" accept-charset="UTF-8">
    アーティスト名 :<input type="text" name="artist_name" />
    ジャンル :<input type="text" name="genre" />
    <input type="submit" value="送信" /> <input type="reset" value="取り消し" />
</form>
</body>
</html>

適当にページ配置して、

routing_to_"/"
from bottle import route, template

@route('/')
def html_index():
    return template('index')

こんな感じになりますね。
入力フォーム

普通にPOSTからforms.getすると
from bottle import route, template, request

@route('/', method='POST')
def search():
    artistname = request.forms.get('artist_name')
    genre = request.forms.get('genre')
    return template('{{name}}, {{genre}}', name=artistname, genre=genre)

日本語を入れて送信すると、
日本語入れてみる

こうなっちゃいますね。
文字化け乙

2.じゃあどうするか

結論から言うと、

こうする
from bottle import route, template, request

@route('/', method='POST')
def search():

    # get使わずにそのまま取ってくる
    artistname = request.forms.artist_name
    genre = request.forms.genre

    return template('{{name}}, {{genre}}', name=artistname, genre=genre)

ちゃんと取得できました。
うまくいった

getunicode

2019/03/19追記

request.forms.getunicode() なるメソッドを使えば、getと同じような書き方で文字化けを解消できるようです。

getunicode使う
from bottle import route, template, request

@route('/', method='POST')
def search():

    # forms.get => forms.getunicode
    artistname = request.forms.getunicode('artist_name')
    genre = request.forms.getunicode('genre')

    return template('{{name}}, {{genre}}', name=artistname, genre=genre)

ちなみに、request.query にも使えます。 request.query.getunicode('queryname')

詳しくは…

詳しい話はここに書いてありますのでさらに深く知りたい方はどうぞ

ソース(英語)
stack_over_flow: How to get utf-8 from forms in Bottle?

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
7