|
在 Python 中將 request.form 及 request.args轉換ImmutableMultiDict為字串表示形式,在 Flask 中實例,可以根據所需的字串格式採取幾種方法。
標準字典轉換為字串:
有ImmutableMultiDict一個to_dict()方法可以將其轉換為常規的 Python dict。然後,接著使用 str()或json.dumps() 轉成JSON 字串。
- from werkzeug.datastructures import ImmutableMultiDict
- import json
- # Example ImmutableMultiDict
- data = ImmutableMultiDict([('key1', 'value1'), ('key2', 'value2'), ('key1', 'value3')])
- # Convert to a regular dictionary
- regular_dict = data.to_dict()
- print(f"Regular dictionary: {regular_dict}")
- flat_dict = data.to_dict(flat=False)
- print(f"flat dictionary: {flat_dict}")
- # Convert dictionary to a simple string representation
- dict_string = str(regular_dict)
- print(f"String from dict: {dict_string}")
- # Convert dictionary to a JSON string
- json_string = json.dumps(regular_dict)
- print(f"JSON string from dict: {json_string}")
複製代碼
輸出
- Regular dictionary: {'key1': 'value1', 'key2': 'value2'}
- flat dictionary: {'key1': ['value1', 'value3'], 'key2': ['value2']}
- String from dict: {'key1': 'value1', 'key2': 'value2'}
- JSON string from dict: {"key1": "value1", "key2": "value2"}
複製代碼
|
|