惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
博客园 - 【当耐特】
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
D
Docker
T
The Blog of Author Tim Ferriss
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
M
MIT News - Artificial intelligence
H
Hackread – Cybersecurity News, Data Breaches, AI and More
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
云风的 BLOG
云风的 BLOG
F
Fortinet All Blogs
罗磊的独立博客
小众软件
小众软件
A
About on SuperTechFans
MyScale Blog
MyScale Blog
D
DataBreaches.Net
The GitHub Blog
The GitHub Blog
C
Check Point Blog
L
LangChain Blog

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
Post Nested Data Structure to the Server Using Requests
2021-04-08 · via jdhao's digital space

In this post, I will share how to post complex data and decode it in the server side in Python.

The problem#

To post a simple Python dict with no nested structure to the server, we may use the below code:

payload = {'name': 'john smith', 'age': 20}

r = requests.post("https://httpbin.org/post", data=payload)

By default, when we use requests.post(url, data=payload) to post payload to the server. We can check the header of the HTTP request via the following command:

The Content-Type of this HTTP request will be application/x-www-form-urlencoded by default. To decode the posted dict, if we use Flask, we can use the following code:

from flask import Flask, request


user_request = request.form.to_dict()

When the data structure is simple, it is fine to use the default options. Once there are nested structure in your Python dictionary, the server can not decode the message properly if the client is using this Content-Type, for example, when we have nested dictionary (a 2-D list):

payload = {'matrix': [[1, 2, 3], [4, 5, 6]], 'msg': 'hello'}

In this case, you will lost the data structure since application/x-www-form-urlencoded can note keep the data structure.

Solution#

There are two solutions here.

Serialize data as json string#

First, we can encode the complex dictionary into string using json:

# Note that payload must be json-serializable, or you will meet an error.
payload = json.dumps(payload)

r = requests.post(url, data=payload)

On the server side (suppose that we are using Flask), we can decode the string to get the original dict:

import json

from flask import request

# decodes the string into original dictionary
user_request = json.loads(request.data)

Use application/json as Content-Type#

Second, we can directly tell the server that we are sending data in json format using requests:

payload = {'matrix': [[1, 2, 3], [4, 5, 6]], 'msg': 'hello'}

r = requests.post(url, json=payload)

In this case, the request header will be something like the following:

{'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate',
'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '2705',
'Content-Type': 'application/json'}

The Content-Type field will be application/json, in which we tell the server that we are sending JSON data.

On the server side (suppose you are using flask), we can retrieve that data using the following script:

from flask import request


# directly decodes the request body as JSON.
user_request = request.get_json()

Ref#