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

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
Google DeepMind News
Google DeepMind News
美团技术团队
大猫的无限游戏
大猫的无限游戏
H
Help Net Security
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
M
MIT News - Artificial intelligence
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Security Blog
Microsoft Security Blog
F
Fortinet All Blogs
A
About on SuperTechFans
Recent Announcements
Recent Announcements
D
Docker
Vercel News
Vercel News
Engineering at Meta
Engineering at Meta
腾讯CDC
Martin Fowler
Martin Fowler
阮一峰的网络日志
阮一峰的网络日志

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
Note on Using requests package
2020-07-09 · via jdhao's digital space

How to check request header and body?#

When making requests, we may want to see exactly what are being requested. With requests, it is easy do access the request header and request body:

import requests

url = "http://httpbin.org/post"
payload = {"apple": 10, "pear": [20, 30], "img": "http://example.com/demo.jpg"}
r = requests.post(url, json=payload)

print(f"request headers: {r.request.headers}")
print(f"request body: {r.request.body}")

A sample output is:

request headers: {'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding':
'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length':
'69', 'Content-Type': 'application/json'}
request body: b'{"apple": 10, "pear": [20, 30], "img": "http://example.com/demo.jpg"}'

Ref:

How to encode JSON when using application/x-www-form-urlencoded?#

When making requests using json data in requests.post(url, data=json_dict), the Content-Type is application/x-www-form-urlencoded. How is JSON encoded by requests?

In requests, this is handled by class RequestEncodingMixin, it provides _encode_params() method to convert provided into url-encoded string (JSON is converted to query string and some characters are escaped). Under the hood, it is using urllib.parse.urlencode() to encode the json data.

url = "http://httpbin.org/post"
payload = {"apple": 10, "pear": [20, 30], "img": "http://example.com/demo.jpg"}
r = requests.post(url, data=payload)

print(f"request body: {r.request.body}")

The request body is:

apple=10&pear=20&pear=30&img=http%3A%2F%2Fexample.com%2Fdemo.jpg

We can also encode JSON directly using urllib:

import urllib

payload = {"apple": 10, "pear": [20, 30], "img": "http://example.com/demo.jpg"}
print(urllib.parse.urlencode(payload, doseq=True))

The encoded string is the same.

Ref:

Set up max retries#

When we use requests to request a URL, we may sometimes get “max retried exceed” errors due to various causes such as unstable network or frequent request.

We can add retry features using requests to increase the chance of successful request:

from requests.adapters HTTPAdapter

from requests.packages.urllib3.util.retry import Retry

session = requests.Session()

retry_strategy = Retry(total=2)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)

r = session.get(url)

In the above code, we first set the parameter max_retries for HTTPAdapter, which can be a simple number or a Retry object from the urllib3 package.

Then we change the original adapter used by session by using the mount() method. The first parameter is the URL prefix for a certain adapter: when the URL matches the prefix, the corresponding adapter will be used by requests session.

Ref: