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

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
云风的 BLOG
云风的 BLOG
Google DeepMind News
Google DeepMind News
美团技术团队
J
Java Code Geeks
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
宝玉的分享
宝玉的分享
博客园 - Franky
Y
Y Combinator Blog
爱范儿
爱范儿
H
Help Net Security
腾讯CDC
G
Google Developers Blog
B
Blog RSS Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
V
Visual Studio Blog
The GitHub Blog
The GitHub Blog
博客园_首页
C
Check Point Blog
博客园 - 三生石上(FineUI控件)

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: