HTTPX|The next generation HTTP client for Python 3

Introduction

HTTPX is a relatively popular project recently seen by GitHub. According to the description on the official website, it has the following characteristics:

  • It is as convenient as using requests, and some of them have
  • Added support for HTTP/1.1 and HTTP/2.
  • Ability to make requests directly to WSGI applications or ASGI applications.
  • There are strict timeout settings everywhere
  • Full type annotation
  • 100% test coverage

    Simple application in FastAPI

Examples of basic use of HTTPX are given in the reference below, so I won’t repeat them here. I have at least two conclusions:
(1) Simplify the traditional synchronous HTTP operation
(2) Simplify the asynchronous HTTP operation (also the biggest highlight)

Now let's look at a basic example of testing API in FastAPI development:

Create the main module program main.py

code show as below:

HTTPX|The next generation HTTP client for Python 3

Write test file test_main.py

code show as below:
HTTPX|The next generation HTTP client for Python 3

[Note] If we want to call an asynchronous function in the test, our test function must also be asynchronous! Pytest provides a neat library for this, called Pytest-asyncio, which allows us to specify to call certain test functions asynchronously. The installation command is as follows:

HTTPX|The next generation HTTP client for Python 3

After installing Pytest-asyncio, pytest will automatically determine and call it. If you do not install this pytest-asyncio library, then there will be a syntax error when importing AsyncClient from httpx in the above code, and there is no support for this type of support! ! !

summary

httpx is a young Python3 library that is growing, but judging from the attention of github users and the current status of Python application needs, this library is very promising! Both in terms of server-side development, or crawler development.

reference

https://github.com/encode/httpx
https://www.python-httpx.org/advanced/
https://fastapi.tiangolo.com/advanced/async-tests/

Guess you like

Origin blog.51cto.com/zhuxianzhong/2583109