【问题标题】:Python Flask unicode string encoding conversionPython Flask unicode 字符串编码转换
【发布时间】:2020-08-28 22:45:44
【问题描述】:

我是 Flask 和编码的新手。使用 Python3 我有一个应用程序:

from flask import Flask
from flask import request
from flask import jsonify
import requests

app = Flask(__name__)

QUERY_PARAM = 'q'


@app.route('/response', methods=['GET'])
def get_query():
    query = request.args.get(QUERY_PARAM)
    user_input = dict()
    user_input['text'] = query
    return jsonify(user_input), requests.codes.ok

我输入 /response?q=什么是 ab\u0026c

现在返回:{"text":"what is ab\u0026c"}

我希望它返回:{"text":"what is ab&c"}

在代码中尝试了几种编码,但没有一个对我有用。 有人可以告诉我如何实现这一目标并帮助我理解它吗?

【问题讨论】:

  • 你可以试试user_input['text'] = str(query)

标签: python python-3.x flask unicode encoding


【解决方案1】:

您的实现似乎工作正常,但您以错误的方式传递查询参数。

您要发送文本:"what is ab&c"。 此文本需要编码为 url 编码。

例如,您可以为此使用 python,方法是在 shell 中运行以下行:

>>> from urllib.parse import urlencode
>>> payload = dict(q="what is ab&c")
>>> urlencode(payload)
'q=what+is+ab%26c'

根据该结果,我们知道请求将是:

http://localhost:5000/response?q=what+is+ab%26c

结果:

{
  "text": "what is ab&c"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    • 2010-09-27
    相关资源
    最近更新 更多