0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flask-RESTX でレスポンス返却する JSON データで日本語を文字化けさせない

Posted at

概要

デフォルトで Flask-RESTXjson.dumps を ASCII モードでレスポンスを返却してしまう。このため、JSON データにひらがなや漢字が含まれる場合は、内容が文字化けしてしまうという事象が発生する。

解決方法

Flask-RESTX の RESTX_JSON 環境変数を使って、json.dumps 時の引数を上書きする。

app.config["RESTX_JSON"] = {"ensure_ascii": False}
  • 実装例
app.py
from flask import Flask
from flask_restx import Api, Resource

app = Flask(__name__)
api = Api(app)

app.config["RESTX_JSON"] = {"ensure_ascii": False}

@api.route("/hello")
class Hello(Resource):
    def get(self):
        return {"message": "こんにちは、世界。"}, 200

if __name__ == '__main__':
    app.run(debug=True)
  • 出力例
$ curl http://localhost:5000/hello
{
    "message": "こんにちは、世界。"
}
0
0
0

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
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?