如何在Flask中将FORM响应数据转换为Python字典? [英] How to convert FORM response data to Python dictionary in Flask?

查看:203
本文介绍了如何在Flask中将FORM响应数据转换为Python字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下POST格式的数据

I have the following data in POST format

标题:内容类型:'application/x-www-form-urlencoded':

数据:'field1 = true& field2 = false& field3 = 123'

在烧瓶服务器中,使用 response.form 产生以下结果:

In the flask server, using the response.form, yields the following result:

ImmutableMultiDict([[''field1','true'),('field2','false'),('field3','123')])

完成之后: request.form.to_dict()

结果是: {'field1':'true','field2':'false','field3':'123'}

是否可以将JSON布尔值 true/false 转换为Python布尔值 True/False ?to_dict函数不应该将它们转换为python布尔类型吗?

Is there a way to convert the JSON boolean true/false to Python Boolean True/False? Shouldn't the to_dict function convert these to python boolean types?

字典已转换,但是true/false仍然是字符串.

The dictionary is converted, but the true/false remains a string.

除了使用字符串比较之外,实现此目标的最佳方法是什么?

What is the optimal way to achieve this, besides using string comparison?

推荐答案

您将不得不封送数据,即参考-

You will have to marshal the data i.e refer - https://flask-restful.readthedocs.io/en/latest/api.html.

In [11]: from flask_restful import fields, marshal

In [12]: data = {'field1': 'true', 'field2': 'false', 'field3': '123'}

In [13]: mfields = { 'field1':fields.Boolean, 'field2':fields.Boolean, 'field3':fields.Raw}

In [14]: marshal(data, mfields)
Out[14]: OrderedDict([('field1', True), ('field2', True), ('field3', '123')])

In [17]: dict(marshal(data, mfields))
Out[17]: {'field1': True, 'field2': True, 'field3': '123'}

使用诸如棉花糖之类的序列化库来处理表单数据.

Use a serialization library such as Marshmallow to handle form data.

如果您事先不知道表单结构,则必须手动将其转换,因为 true 是此处的字符串.如果不是,则可以使用 json.loads .

In case you don't know the form structure before hand, you will have to convert it manually because true is a string here. If it wasn't then json.loads could be used.

In [18]: data
Out[18]: {'field1': 'true', 'field2': 'false', 'field3': '123'}

In [19]: {k: True if v == "true" else False if v == "false" else v for k,v in data.items()}
Out[19]: {'field1': True, 'field2': False, 'field3': '123'}

这篇关于如何在Flask中将FORM响应数据转换为Python字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆