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

推荐订阅源

Stack Overflow Blog
Stack Overflow Blog
T
Tailwind CSS Blog
Recent Announcements
Recent Announcements
宝玉的分享
宝玉的分享
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Proofpoint News Feed
D
Docker
Google DeepMind News
Google DeepMind News
aimingoo的专栏
aimingoo的专栏
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
云风的 BLOG
云风的 BLOG
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
IT之家
IT之家
H
Help Net Security
Apple Machine Learning Research
Apple Machine Learning Research
Martin Fowler
Martin Fowler
S
SegmentFault 最新的问题
B
Blog
D
DataBreaches.Net

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
Build Web API with Flask --- Work with JSON-like Dict
2020-04-13 · via jdhao's digital space

This is a simple post about how to send JSON-like Dict data to a Flask server via requests package.

Post dict to Flask server#

To post Python dict using requests package, we can use the data parameter:

import requests

payload = {'foo': 1, 'bar': 2}
requests.post(url, data=payload)

In the above example, the Content-Type for posted data is application/x-www-form-urlencoded, you can get the posted data in the Flask server side via request.form:

from flask import request

data = request.form.to_dict()

Post and receive dict with value of list type#

One caveat when we use request.form.to_dict() is that we only get the first element for a dict value of list type. For example, if payload is the following dict:

payload = {'id': '123', 'type': 'jpg', 'box': [0, 0, 100, 100]}

On the Flask server side, after request.form.to_dict(), you only get the following:

{'id': '123', 'type': 'jpg', 'box': '0'}

which is completely non-obvious for Flask beginners. To get the full list instead, we have two ways:

  • Use requests.form.to_dict(flat=False) (see here on the description about to_dict()). One drawback is that values that are non-list originally are converted to list. So now you get:
    {'id': ['123'], 'type': ['jpg'], 'box': ['0', '0', '100', '100']}
  • Use request.form.getlist('key') to get the list corresponding to key, more about this here.

Directly posting JSON data#

Another way to post Python dict is to directly post and receive JSON data. When making requests, we can use the json parameter of requests.post() method:

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

In this way, requests package will serialize your dict into JSON format. The Content-Type in HTTP header will be set to application/json. In the Flask side, we need to use request.get_json() to get the posted JSON data.

Post or return base64 encoded image in dict#

When you post base64 encoded image in dict via requests package, you may see the following error:

TypeError: Object of type bytes is not JSON serializable

This is because the Python JSON library cannot serialize byte type. You can convert the base64 encoded image as string via decode() method:

import base64
import requests

with open('test.jpg', 'rb') as f:
    im_b64 = base64.b64encode(f.read())

payload = {'image': im_b64.decode()}
r = requests.post(url, json=payload)

Similarly, when you want to return base64 encoded image in the Flask server side via jsonify() method, you need also to convert bytes type to str before JSON library can serialize it.

References#