python - Flask/Werkzeug 请求对象表单参数

标签 python flask python-requests werkzeug

我有一个 Flask 应用程序,它为 Django 消费者提供 API。我用 requests library在我的消费者中点击 API。

我的问题是这样的:当我测试我的 API 时,我在 request.form 中获取 POST 数据,当我从我的消费者(使用请求库)中获取它时,我在 中获取 POST 数据请求.data.

例如,

Flask 应用中的 API 端点:

@mod.route('/customers/', methods=['POST'])
def create_prospect():
    customer = Customer()
    prospect = customer.create_prospect(request.form)
    return jsonify(prospect.serialize()), 201

在 Flask 应用程序中测试 API 端点:

def test_creating_prospect(self):
    with self.app.app_context():
        data = {'name': 'Test company and co'}
        response = self.client.post(self.url, data=data)
        ...

这会在我的端点中填充 request.form,效果很好。

使用请求从我的 Django 应用中使用 API:

...
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
data = {'name': 'Test company and co'}
response = requests.post(url, data=data, headers=headers)

这会在我的端点中填充 request.data,但由于我正在检查 request.form 中的信息而失败。

我在写这个问题时有一个想法;也许 json header 正在填充 request.data 而不是 request.form

感谢任何意见。

编辑 - 我尝试将 header 添加到我的测试中,效果很好:

    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    response = self.client.post(self.url, data=data, headers=headers)

最佳答案

啊,我发送的内容类型不正确。将其更改为“application/x-www-form-urlencoded”可使 request.form 获得正确的内容。

request.data 填充了 Flask/Werkzeug 不知道如何处理的东西 according to the docs .

关于python - Flask/Werkzeug 请求对象表单参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17139844/

相关文章:

python - VTK 通过按钮集成到 PyQt 中

Python CSV对字段中的数据求平方根

python - Flask-Restful 忽略蓝图的 url_prefix

python-3.x - Python 请求与curl

Python 请求 - 如何为创建的 session 设置默认重试对象?

python - 使用多线程下载文件时内存不断增长

python - 客户端机器上的 MySQLdb 可以连接到服务器机器上的数据库吗?

python - 在 Python 中的 API 网关请求中使用 AWS Cognito 访问 token

javascript - 动态改变 Google map 上绘制的圆圈的颜色

python - static 子文件夹中的视频不起作用