Home  >  Article  >  Backend Development  >  When learning Python, how can you not master these 22 commonly used libraries?

When learning Python, how can you not master these 22 commonly used libraries?

王林
王林forward
2023-04-12 10:25:021832browse

When learning Python, how can you not master these 22 commonly used libraries?

What is the current usage status of Python in various industries around the world?

This question is the original intention of writing this article. I found the 22 most commonly used Python packages, hoping to give you some inspiration.

First I listed the most downloaded Python packages on PyPI in the past year. Let’s take a look at what these packages do, how they relate to each other, and why they’re so popular.

1. Urllib3

893 million downloads

Urllib3 is an HTTP client for Python. It provides many functions that are not available in the Python standard library.

  • Thread safety
  • Connection pool
  • Client SSL/TLS verification
  • Use multipart encoding for file upload
  • Use Auxiliary functions for retransmitting requests and handling HTTP redirects
  • Supports gzip and deflate encoding
  • Supports HTTP and SOCKS proxies

Although the name is Urllib3, it It is not a successor to urllib2 that comes with Python. If you want to use the core functionality of Python as much as possible (for example, if it cannot be installed due to some restrictions), then take a look at urllib.request.

For end users, I highly recommend the requests package (refer to the sixth item in the list). Urllib3 ranks first because almost 1200 packages depend on it, and many of these packages are also high on the list.

2, Six

732 million downloads

Six is ​​a Python 2 and Python 3 compatibility tool. The purpose of this project is to enable code to run on both Python 2 and Python 3.

It provides many functions that mask the syntax differences between Python 2 and Python 3. The easiest example to understand is six.print_(). In Python 3, you need to use the print() function when outputting, while in Python 2, print without parentheses is used. Therefore, using six.print_() supports both languages.

Key points:

  • The name of the package six comes from 2 x 3 = 6
  • Similar libraries also have future
  • If you want to add the code To convert to Python 3 (while Python 2 is no longer supported), take a look at 2to3

Although I understand that the package is so popular, I hope people will abandon Python 2 as soon as possible, especially from January 2020 Starting from the 1st, Python 2 is officially no longer supported.

3. botocore, boto3, s3transfer, awscli

Put these projects together:

  • botocore: No. 3, 660 million downloads
  • s3transfer: No. 7, 584 million downloads
  • awscli: No. 17, 394 million downloads
  • boto3: No. 22, 329 million downloads

Botocore is the underlying interface of AWS. botocore is the basis for the boto3 (#22) library, which gives you access to Amazon's S3, EC2 and other services.

Botocore is also the basis for AWS-CLI, the command line interface for AWS.

s3transfer (7th) is a Python library for managing S3 transfers. The library is still under development, and its home page still recommends not using it, or at least fixing the version when using it, since its API may change even between minor version numbers. boto3, AWS-CLI, and many other projects rely on s3transfer.

The fact that AWS-related libraries rank so high illustrates how popular AWS services are.

4. Pip

627 million downloads

I guess many people know and love pip (Python package installation tool). Using pip to install packages from the Python Package Index and other repositories such as local mirrors or custom repositories containing private software is effortless.

Interesting facts about pip:

  • The name of Pip is a recursive definition: Pip Installs Packages
  • Pip is very easy to use. To install a package just execute pip install . To delete, just execute pip uninstall .
  • The biggest benefit of Pip is that it can install a series of packages, usually placed in the requirements.txt file. This file can also specify the detailed version number of each package. Most Python projects will include this file.
  • Use pip in conjunction with virtualenv (#57) to create predictable, independent environments that do not interact with the system's own environment.

5. python-dateutil

617 million downloads

The Python-dateutil module provides powerful function extensions for the standard datetime module. Everything that ordinary Python datetime cannot do can be done with python-dateutil.

You can accomplish many very cool functions with this library. I'll just give you a very useful example: Fuzzy parsing of date strings from log files:

from dateutil.parser import parse
logline = 'INFO 2020-01-01T00:00:01 Happy new year, human.'
timestamp = parse(log_line, fuzzy=True)
print(timestamp)
# 2020-01-01 00:00:01

6, requests

611 million downloads

Requests based on download volume A library called urllib3. With it, sending requests is extremely easy. Many people prefer requests over urllib3, so there are probably more end users of requests than urllib3. The latter is lower level and usually appears as a dependency of other projects.

The following example demonstrates how easy to use requests:

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# 200
r.headers['content-type']
# 'application/json; charset=utf8'
r.encoding
# 'utf-8'
r.text
# u'{"type":"User"...'
r.json()
# {u'disk_usage': 368627, u'private_gists': 484, ...}

7、s3transfer

第3、7、17和22名互相关联,所以请参见第3名的介绍。

8、Certifi

5.52亿次下载

近年来,几乎所有网站都开始使用SSL,这一点可以从地址栏中的锁图标看出来,该图标的意思是网站是安全的、加密的,可以避免窃听。

When learning Python, how can you not master these 22 commonly used libraries?

加密基于SSL证书,SSL证书由可信的公司或非营利组织负责签发,如 LetsEncrypt。这些组织会对利用它们的证书对签发的证书进行数字签名。

利用这些证书的公开部分,浏览器就可以验证网站的签名,从而证明你访问的是真正的网站,而且别人没有在窃听数据。

Python 也可以做到同样的功能,这就需要用到 certifi。它和 Chrome、Firefox 和 Edge 等Web浏览器中包含的根证书集合没有什么区别。

Certifi 是一个根证书集合,这样 Python 代码就可以验证SSL证书的可信度。

许多项目都信赖并依赖 certifi,可以在这里看到这些项目。这也是为何该项目排名如此高的原因。

9、Idna

5.27亿次下载

根据 PyPI 的页面,idna提供“对于RFC5891中定义的IDNA协议(Internationalised Domain Names in Applications)的支持”。

我们来看看 idna 是什么意思:

IDNA 是处理包含非 ASCII 字符的域名的规则。但原始的域名不是已经支持非 ASCII 字符了吗?那么问题何在?

When learning Python, how can you not master these 22 commonly used libraries?

问题是许多应用程序(如Email客户端和Web浏览器等)并不支持非 ASCII 字符。或者更具体地说,Email 和 HTTP 协议并不支持这些字符。

在许多国家这并不是问题,但像中国、俄罗斯、德国、印尼等国家就很不方便。因此,这些国家的一些聪明人联合起来提出了 IDNA,也并非完全偶然。

IDNA 的核心是两个函数:ToASCII 和 ToUnicode。ToASCCI 会将国际化的 Unicode 域名转换成 ASCII 字符串,而 ToUnicode 会做相反的处理。在 IDNA 包中,这两个函数叫做 idna.encode() 和 idna.decode(),参见下面的例子:

import idna
idna.encode('ドメイン.テスト')
# b'xn--eckwd4c7c.xn--zckzah'
print(idna.decode('xn--eckwd4c7c.xn--zckzah'))
# ドメイン.テスト

该编码的详细内容可以参见 RFC3490。

10、PyYAML

5.25亿次下载

YAML 是一种数据序列化格式。它的设计目标是同时方便人类和机器阅读——人类很容易读懂,计算机解析也不难。

When learning Python, how can you not master these 22 commonly used libraries?

PyYAML 是 Python 的 YAM 解析器和编码器,也就是说它可以读写 YAML 格式。它可以将任何 Python 对象编码为 YAML:列表,字典,甚至类实例都可以。

Python 提供了自己的配置管理器,但 YAML 提供的功能远胜于 Python 自带的 ConfigParser(只能使用最基本的.ini文件)。

例如,YAML 能存储任何数据类型:boolean,list,float等。ConfigParse 的内部一切都保存为字符串。如果你要用 ConfigParser 来加载证书,就需要指明你需要的是整数:

config.getint(“section”, “my_int”)

而 pyyaml 能够自动识别类型,因此只需这样就能获得 int:

config[“section”][“my_int”]

YAML 还允许任意深度的嵌套,尽管并非每个项目都需要,但非常方便。

你可以自行决定使用哪一个,但许多项目都使用 YAML 作为配置文件,因此该项目的流行度非常高。

11、pyasn1

5.12亿次下载

像 IDNA 一样,这个项目的描述的信息量也非常大:

ASN.1 类型和 DER/BER/CER 编码(X.208)的纯 Python 实现。

幸运的是,我们依然能找到这个几十年之久的标准的许多资料。ASN.1 是 Abstract Syntax Notation One(抽象语法记法一)的缩写,是数据序列化的鼻祖。它来自于通讯行业。也许你知道 protocol buffer 或者 Apache Thrift 吧?ASN.1正是它们的1984年版本。

ASN.1 描述了一种不同系统之间的跨平台的接口,可以通过该接口发送数据结构。

还记得第8名的 certifi 吗?ASN.1 用于定义 HTTPS 协议以及许多其他加密系统中使用的证书的格式。ASN.1 还广泛用于 SNMP、LDAP、Kerberos、UMTS、LTE 和 VOIP 等协议中。

它是个非常复杂的标准,人们已经发现某些实现充满了脆弱性。你可以看看 Reddit 上的这个关于 ASN.1 的讨论(https://www.reddit.com/r/programming/comments/1hf7ds/useful_old_technologies_asn1/)。

除非真正必要,否则我建议不要使用它。但由于许多地方都在使用该协议,因此许多包都依赖于它。

12、docutils

5.08亿次下载

Docutils 是一个模块化系统,用于将纯文本文档转换成其他格式,如 HTML、XML 和 LaTeX等。docutils 可以读取 reStructuredText 格式(一种类似于 MarkDown 的容易阅读的格式)的纯文本文档。

我猜你一定听说过 PEP 文档,甚至可能阅读过。PEP 文档是什么?

PEP 的意思是 Python Enhanced Proposal(Python增强提案)。PEP 是一篇设计文档,用于给 Pytho n社区提供信息,或者为 Python(或其处理器、环境)描述一个新特性。PEP 应该提供特性的精确的技术标准,并给出该特性的理由。

PEP 文档就是使用固定的 reStructuredText 模板,然后通过 docutils 转换成漂亮的文档。

Sphinx 的核心也使用了 docutils。Sphinx 用于创建文档项目。如果说 docutils 是一台机器,那么 Sphinx 就是一个工厂。它的最初设计目的是构建P ython 本身的文档,但许多其他项目也利用 Sphinx 来创建文档。

你一定度过 readthedocs.org 上的文档吧?那里的文档都是使用 Sphinx 和 docutils 创建的。

13、Chardet

5.01亿下载

你可以使用 chardet 模块来检查文件或数据流的字符集。在分析大量随机的文本时这个功能非常有用。但也可以用来判断远程下载的数据的字符串。

在安装 chardet 后,就可以使用命令行工具 chardetect,使用方法如下:

chardetect somefile.txt
somefile.txt: ascii with confidence 1.0

也可以在程序中使用该库,参见文档(https://chardet.readthedocs.io/en/latest/usage.html)。

Requests 和许多其他包都依赖于 chardet。我估计不会有太多人直接使用 chardet,所以它的流行度肯定是来自于这些依赖。

14、RSA

4.92亿次下载

Rsa是 RSA 的纯 Python 实现。它支持如下功能:

  • 加密和解密
  • 签名和签名验证
  • 根据 PKCS#1 version 1.5生成秘钥

它可以作为 Python 库使用,也可以在命令行上使用。

  • RSA 名称中的三个字母来自于三个人的姓:Ron Rivest,Adi Shamir,和Leonard Adleman。他们于1977年发明了该算法。
  • RSA 是最早出现的一批公钥加密系统,广泛用于安全数据传输。这种加密系统包括两个秘钥:一个是公钥,一个是私钥。使用公钥加密数据,然后该数据只能用私钥进行解密。
  • RSA 算法很慢。通常并不使用 RSA 算法直接加密用户数据,而是用它来加密对称加密系统中使用的共享秘钥,因为对称加密系统速度很快,适合用来加密大量数据。

下面代码演示了 RSA 的使用方法:

import rsa
# Bob creates a key pair:
(bob_pub, bob_priv) = rsa.newkeys(512)
# Alice ecnrypts a message for Bob
# with his public key
crypto = rsa.encrypt('hello Bob!', bob_pub)
# When Bob gets the message, he
# decrypts it with his private key:
message = rsa.decrypt(crypto, bob_priv)
print(message.decode('utf8'))
# hello Bob!

假设 Bob 拥有私钥 private,Alice 就能确信只有 Bob 才能阅读该信息。

但 Bob 并不能确信 Alice 是信息的发送者,因为任何人都可以获得 Bob 的公钥。为了证明发送者的确是 Alice,她可以使用自己的私钥对信息进行签名。Bob 可以使用 Alice 的公钥对签名进行验证,来确保发送者的确是 Alice。

许多其他包都依赖于 rsa,如 google-auth(第37名),oauthlib(第54名),awscli(第17名)。这个包并不会经常被直接使用,因为有许多更快、更原生的方法。

15、Jmespath

4.73亿次下载

在 Python 中使用 JSON 很容易,因为 JSON 可以完美地映射到 Python 的字典上。我认为这是最好的特性之一。

说实话我从来没听说过 jmepath 这个包,尽管我使用过很多 JSON。我会使用 json.loads() 然后手动从字典中读取数据,或许还得写几个循环。

JMESPath,读作“James path”,能更容易地在 Python 中使用 JSON。你可以用声明的方式定义怎样从 JSON 文档中读取数据。

下面是一些最基本的例子:

import jmespath
# Get a specific element
d = {"foo": {"bar": "baz"}}
print(jmespath.search('foo.bar', d))
# baz
# Using a wildcard to get all names
d = {"foo": {"bar": [{"name": "one"}, {"name": "two"}]}}
print(jmespath.search('foo.bar[*].name', d))
# [“one”, “two”]

这仅仅是它的冰山一角。更多用法参见它的文档和 PyPI 主页。

16、Setuptools

4.01亿次下载

Setuptools 是用来创建 Python 包的工具。

这个项目的文档很糟糕。文档并没有描述它的功能,还包含死链接。真正的好文档在这里:https://packaging.python.org/,以及这篇文章中关于怎样创建 Python 包的教程:https://packaging.python.org/tutorials/packaging-projects/。

17、awscli

第3、7、17和22名互相关联,所以请参见第3名的介绍。

18、pytz

3.94亿次下载

类似于第5名的 dateutils,该库可以帮助你操作日期和时间。处理时区很麻烦。幸运的是,这个包可以让时区处理变得很容易。

关于时间,我的经验是:在内部永远使用UTC,只有在需要产生供人阅读的输出时才转换成本地时间。

下面是 pytz 的例子:

from datetime import datetime
from pytz import timezone
amsterdam = timezone('Europe/Amsterdam')
ams_time = amsterdam.localize(datetime(2002, 10, 27, 6, 0, 0))
print(ams_time)
# 2002-10-27 06:00:00+01:00
# It will also know when it's Summer Time
# in Amsterdam (similar to Daylight Savings Time):
ams_time = amsterdam.localize(datetime(2002, 6, 27, 6, 0, 0))
print(ams_time)
# 2002-06-27 06:00:00+02:00

更多文档和例子可以参见 PyPI 页面。

19、Futures

3.89亿次下载

从 Python 3.2 开始,python 开始提供 concurrent.futures 模块,可以帮你执行异步操作。futures 包是该库的反向移植,所以它是用于 Python 2 的。当前的 Python 3 版本不需要该包,因为 Python 3 本身就提供了该功能。

前面我说过,从2020年1月1日起官方已经停止支持 Python 2。我希望明年再做这个列表的时候,不再看到这个包排进前22名。

下面是 futures 包的基本用法:

from concurrent.futures import ThreadPoolExecutor
from time import sleep
def return_after_5_secs(message):
sleep(5)
return message
pool = ThreadPoolExecutor(3)
future = pool.submit(return_after_5_secs,
 ("Hello world"))
print(future.done())
# False
sleep(5)
print(future.done())
# True
print(future.result())
# Hello World

可见,我们可以创建一个线程池,然后提交一个函数,让某个线程执行。同时,你的程序会继续在主线程上运行。这是实现并行执行的一种很容易的方式。

20、Colorama

3.70亿次下载

你可以使用 Colorama 在终端上添加颜色:

When learning Python, how can you not master these 22 commonly used libraries?

下面的示例演示了实现这个功能有多么容易:

from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')

21、Simplejson

3.41亿次下载

Python 自带的 json 模块有什么问题导致了这个包有如此高的排名?没有任何问题!实际上, Python 的 json 就是 simplejson。但 simplejson 有一些优点:

能在更多 Python 版本上运行

更新频率高于 Python

一部分代码是用C编写的,运行得非常快

有时候你会看到脚本中这样写:

try:
import simplejson as json
except ImportError:
import json

不过,除非确实需要一些标准库中没有的功能,我依然会使用 json。SImplejson 可能比 json快很多,因为它的一部分是用C实现的。但是除非你要处理几千个 JSON 文件,否则这点速度提升并不明显。此外还可以看看 UltraJSON,这是个几乎完全用C编写的包,应该速度更快。

22、boto3

第3、7、17和22名互相关联,所以请参见第3名的介绍。

结束语

只写22个包很难,因为后面的许多包都是终端用户更倾向使用的包。

写这篇文章给了我一些启示:

许多排名靠前的包提供一些核心的功能,如处理时间、配置文件、加密和标准化等。它们通常是其他项目的依赖。

最常见的使用场景就是连接。许多包提供的功能就是连接到服务器,或者支持其他包连接服务器。

其他包是对 Python 的扩展,比如用于创建 Python 包的工具,创建文档的工具,创建版本兼容性的工具,等等。

The above is the detailed content of When learning Python, how can you not master these 22 commonly used libraries?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete