Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

I’m sure you’re like me, and the Requests library is widely used in your daily work. Today I’m going to introduce you to what is billed as the next full-featured HTTP client: HTTPX.

What is a HTTPX

HTTPX is a full-featured Python3 client that supports synchronous & asynchronous apis and supports both HTTP/1.1 and HTTP/2.

HTTPX has a much easier interface and more power than other HTTP libraries, making it the perfect choice for future Python developers.

Installation and use

The installation

pip install httpx
Copy the code

get

import httpx

# get obj
res = httpx.get('https://www.baidu.com')
print(res,res.status_code)

# response content,text
print(res.content,res.text)
Copy the code

As for the difference between content and text, it can be seen from the figure that the type of content is bytes and that of text is STR.

post

# post obj

res = httpx.post('http://127.0.0.1:4523/mock/351132/pet',data={'name':'Python Testing and Development '.'status':'Python_Lab'})

print(res.text,type(res.content),res.status_code,res.encoding)
Copy the code

Because we used the Mock Server, the data returned by the interface might not be the same as what we requested.

put

# put pbj

res = httpx.put('http://127.0.0.1:4523/mock/351132/pet',params={'apifoxResponseId':'321249'})
print(res.status_code,res.encoding,res.text)
Copy the code

delete

# delete obj

res = httpx.delete('http://127.0.0.1:4523/mock/351132/pet/1')
print(res.status_code,res.encoding,res.text)
Copy the code

Advanced usage

Processing json

Normally, if the content returns bytes or STR, we would need to use the JSON module alone to convert the data, but now we can use json methods provided by HTTPX to retrieve the dictionary object directly to facilitate data processing.

import httpx

# json
res = httpx.get('https://getman.cn/mock/post')
print(type(res.text),type(res.content),type(res.json()),res.json())
Copy the code

Processing binary

When we need to download an image, we usually read the content in chunks and then write it to a file. But HTTPX recommends that we use pillow and IO to handle the binary content of the image.

import httpx
from PIL import Image
from io import BytesIO

# bytes
res = httpx.get('http://localhost:8765/um/imgs/')
print(res.status_code)
ff = Image.open(BytesIO(res.content))
ff.save('xx.png')
Copy the code

HTTPX supports all methods such as raise_for_status() for all requests, and has added some new features such as httpx.codes.ok instead of 200 response code phrases. All in all, HTTPX is an excellent piece of software to learn.

The official documentation

www.python-httpx.org/

That’s all for today, thank you for reading, and we’ll see you next time.