找回密碼
 註冊
搜索
查看: 113|回復: 0

[教學] immutablemultidict to string

[複製鏈接]
發表於 昨天 22:14 | 顯示全部樓層 |閱讀模式
Push to Facebook
在 Python 中將 request.form 及 request.args轉換ImmutableMultiDict為字串表示形式,在 Flask 中實例,可以根據所需的字串格式採取幾種方法。

標準字典轉換為字串:
有ImmutableMultiDict一個to_dict()方法可以將其轉換為常規的 Python dict。然後,接著使用
str()json.dumps() 轉成JSON 字串。

  1. from werkzeug.datastructures import ImmutableMultiDict
  2. import json

  3. # Example ImmutableMultiDict
  4. data = ImmutableMultiDict([('key1', 'value1'), ('key2', 'value2'), ('key1', 'value3')])

  5. # Convert to a regular dictionary
  6. regular_dict = data.to_dict()
  7. print(f"Regular dictionary: {regular_dict}")

  8. flat_dict = data.to_dict(flat=False)
  9. print(f"flat dictionary: {flat_dict}")

  10. # Convert dictionary to a simple string representation
  11. dict_string = str(regular_dict)
  12. print(f"String from dict: {dict_string}")

  13. # Convert dictionary to a JSON string
  14. json_string = json.dumps(regular_dict)
  15. print(f"JSON string from dict: {json_string}")
複製代碼

輸出
  1. Regular dictionary: {'key1': 'value1', 'key2': 'value2'}
  2. flat dictionary: {'key1': ['value1', 'value3'], 'key2': ['value2']}
  3. String from dict: {'key1': 'value1', 'key2': 'value2'}
  4. JSON string from dict: {"key1": "value1", "key2": "value2"}
複製代碼


您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

Archiver|手機版|小黑屋|TShopping

GMT+8, 2025-10-17 08:31 , Processed in 0.021958 second(s), 19 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回復 返回頂部 返回列表