Python常见第三方库


纸上得来终觉浅,绝知此事要躬行。

Python常见第三方库


实事求是,Python的强大之处在于它有非常丰富且强大的标准库和第三方库,几乎你想要实现的任何功能都有相应的Python库来提供支持,就类似于JAVAjar包或前端中的 JS 库。常见的第三方库提供了很多功能和用法,帮助我们简化代码和提高代码质量,需要我们多多学习。

1. request

Requests是用Python语言编写,基于urllib开源协议的HTTP库。它比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求,更重要的一点是它支持Python3哦!

  • 使用内建的标准库实现
import urllib2

def access_github(url):
    password_manager = urllib2.HTTPPasswordMgrWithDefaultReadlm()
    password_manager.add_password(None, url, 'user', 'password')
    auth_manager = urllib2.HTTPBaseicAuthHandler(password_manager)
    opener = urllib2.build_opener(auth_manager)
    urllib2.install_opener(opener)

    request = urllib2.Request(url)
    handler = urllib2.urlopen(request)
    return handler

if __name__ == '__main__':
    gh_url = 'https://api.github.com'
    handler = access_github(gh_url)
    print(handler.getcode())
    print(handler.headers.getheader('content-type'))
  • 替代的第三方模块实现
import requests

request = requests.get('https://api.github.com', auth=('user', 'password'))
print(request.status_code)
print(request.headers['content-type'])

2. httpie

作为开发者,往往需要在终端以一些非交互式模式访问一些网站和文件,或访问restful的通达性,通常会使用curl命令。但其语法参数繁多且输出内容不能高亮显示,所以可以使用Python版本的httpie模块来完成。

  • 模块优点

    • 友好的语法高亮输出
    • 支持持久性会话特性
    • 默认输出为json格式,易于可读且容易二次开发
  • 安装方式

# macOS
$ brew install httpie

# Linux
$ yum install httpie

# Windows
$ pip install --upgrade httpie
  • 使用方式
# 语法格式
http [flags] [METHOD] URL [ITEM [ITEM]]
# Custom HTTP method, HTTP headers and JSON data
http PUT example.org X-API-Token:123 name=John

# Submitting forms
http -f POST example.org hello=World

# Upload a file using redirected input
http example.org < file.json

# Download a file and save it via redirected output
http example.org/file > file

# Download a file wget style
http --download example.org/file
# Use Github API to post a comment on an issue with authentication
http -a USERNAME POST https://api.github.com/repos/jkbrzt/httpie/issues/83/comments body='HTTPie is awesome! :heart:'

# Use named sessions to make certain aspects or the communication persistent between requests to the same host
http --session=logged-in -a username:password httpbin.org/get API-Key:123
http --session=logged-in httpbin.org/headers

# Set a custom Host header to work around missing DNS records
http localhost:8000 Host:example.com

3. attrs

第三方模块是Python核心开发Hynek Schlawack设计并实现的一个项目,它就是解决上述痛点而生的,可以大量简化面向对象编程中需要写的代码。可用于字段类型验证自动类型转化属性值不可变类型注解等等。

  • 安装方式
# attrs is a Python-only package hosted on PyPI
$ pip install attrs
  • 使用方式
# 字段类型验证
# 业务代码中经验会对对象属性的类型和内容验证,attrs也提供了2种验证支持

# 1.装饰器
>>> @attr.s
... class C(object):
...     x = attr.ib()
...     @x.validator
...     def check(self, attribute, value):
...         if value > 42:
...             raise ValueError("x must be smaller or equal to 42")
>>> C(42)
C(x=42)
>>> C(43)
Traceback (most recent call last):
   ...
ValueError: x must be smaller or equal to 42

# 2.属性参数
>>> def x_smaller_than_y(instance, attribute, value):
...     if value >= instance.y:
...         raise ValueError("'x' has to be smaller than 'y'!")
>>> @attr.s
... class C(object):
...     x = attr.ib(validator=[attr.validators.instance_of(int),
...                            x_smaller_than_y])
...     y = attr.ib()
>>> C(x=3, y=4)
C(x=3, y=4)
>>> C(x=4, y=3)
Traceback (most recent call last):
   ...
ValueError: 'x' has to be smaller than 'y'!
# 属性类型转化
# Python不会检查传入的值的类型,类型错误很容易发生,attrs支持自动的类型转化

>>> @attr.s
... class C(object):
...     x = attr.ib(converter=int)
>>> o = C("1")
>>> o.x
1

4. click

在写命令行工具的时候,都会用到参数解析模块。虽然标准库中有个类似argparse模块,且功能基本可以覆盖整个开发过程了。但是click模块和其实现思路是完全不一样的,提供了更多的特性和优点。

  • 模块优点

    • 支持任意命令的嵌套
    • 提供有用的功能函数,如在终端输出可以带颜色
    • 支持子命令的懒加载,就是都有哪些命令是动态算出来的,而不需要预先定义好
  • 使用内建的标准库实现

import argparse

parser = argparse.ArgumentParser(description='This print hello...')
parser.add_argument('name', help='Name to saying hello.', type=str)
parser.add_argument('--times', default=1, help='Number of 1-5', type=int, choices=range(1, 6))
args = parser.parse_args()

for _ in range(args.times):
    print('Hello, {}'.format(args.name))
$ python argparse.py -h
usage: argparse.py [-h] [--times {1,2,3,4,5}] name

This print hello...

positional arguments:
  name                 Name to saying hello.

optional arguments:
  -h, --help           show this help message and exit
  --times {1,2,3,4,5}  Number of 1-5
  • 替代的第三方模块实现
import click

@click.command()
@click.argument('name')
@click.option('--times', default=1, type=click.IntRange(1, 5)), help='Number of 1-5')
def hello(name, times):
    for _ in range(times):
        click.echo('Hello, {}!'.format(name))
$ python click.py -h
Usage: click.py [OPTIONS] NAME

Options:
  --times INTEGER RANGE Number of 1-5
  --help                Show this message and exit.

5. docopt

该模块是作者在pycon上面推荐的文档用法写法,是一个命令行接口描述语言。与argparseclick的思路也是完全不同的,直接写注释就可以完成其命令行帮助功能了,即所见即所得。

"""Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py (-h | --help)
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.
"""
from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Naval Fate 2.0')
    print(arguments)docoptdocopt
$ python docopt.py
Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py (-h | --help)
  naval_fate.py --version

$ python docopt.py shoip escape move 100 150 --speed=15

6. six

Python2Python3有很大的不同,six这个库为此提供了一个兼容的方案。使用six写的代码可以不用修改就运行在Python2Python3上。注意这个six并不是让Python2写的代码兼容Python3,如果你需要迁移工具,那么你要找的是2to3。如果你的代码需要同时需要运行在Python2Python3上,那么你就需要six

原理其实很简单,sixPython2Python3的名字等做了统一,比如Python2的字符串叫strPython3unicode,那么就可以使用six.text_type。如果运行在Python2上,six.text_type就是unicode,如果运行在Python3上,six.text_type就是str

  • 安装方式
# 使用pip安装
$ pip install six
  • 使用方式
# 统一了Python2和Python3的类型

# Python2
>>> import six
>>> s = u"hello"
>>> type(s)
<type 'unicode'>
>>> isinstance(s, six.string_types)
True

# Python3
Python 3.6.1 (default, Apr  4 2017, 09:40:21)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import six

In [2]: s = "hello"

In [3]: type(s)
Out[3]: str

In [4]: isinstance(s, six.string_types)
Out[4]: True
# 移动模块的位置
# Python3重新组织了很多模块的位置,例如Python2的HTMLParser,在Python3中是html.parser
from six.moves import html_parser

7. pelican

该模块使用Python语言实现的一个静态网站生成器,可以很方便、快捷的生成一个技术博客。

  • 安装方式
# 使用pip安装
$ pip install pelican markdown
  • 使用方式
# Create a project
$ mkdir -p ~/projects/yoursite
$ cd ~/projects/yoursite
$ pelican-quickstart

# Generate your site
$ pelican content

# Preview your site
$ cd ~/projects/yoursite/output
$ python -m pelican.server

8. mkdocs

MkDocs是一个用于创建项目文档的快速、简单、完美华丽的静态站点生成器。文档源码使用 Markdown 来撰写,用一个 YAML 文件作为配置文档,而且还支持多种主题可供选择。

  • 安装方式
# 使用pip安装
$ pip install mkdocs

# 检查是否正确安装
$ mkdocs help
mkdocs [help|new|build|serve|gh-deploy] {options}
  • 使用方式
# 输入以下命令以开始一个新项目
$ mkdocs new my-project
$ cd my-project

# 启动内建服务器
$ mkdocs serve
Running at: http://127.0.0.1:8000/

# 站点生成
$ mkdocs build

# 发布
MkDocs生成的文档只包含静态文件,因此你可以将文档部署到任意地方。GitHub和Amazon是不错的选择,只需上传site目录到你需要发布的位置即可。

文章作者: Escape
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Escape !
  目录