Python 中有哪些常用的 API?

开发 前端
Python 中有哪些常用的 API有知道的?今天我们一起来聊一下。


1.Web 开发

Flask:轻量级 Web 框架,易于上手,适合构建小型到中型的应用程序。

Django:功能齐全的全栈 Web 框架,内置 ORM、认证系统等,适用于快速开发复杂网站。

FastAPI:现代、快速(高性能)的 Web 框架,基于 Python 类型提示,支持异步编程。

示例(Flask):

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello, World!'
if __name__ == '__main__':
    app.run()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

2. 网络请求与 HTTP 客户端

Requests:人类友好的 HTTP 库,简化了发送 HTTP 请求的过程。

HTTPX:一个基于 async/await 的 HTTP 客户端,兼容 Requests 接口,支持同步和异步操作。

示例(Requests):

import requests
response = requests.get('https://api.github.com')
print(response.status_code)
print(response.json())
  • 1.
  • 2.
  • 3.
  • 4.

3. 数据库交互

SQLAlchemy:强大的 SQL 工具包和对象关系映射器(ORM),支持多种数据库后端。

Peewee:轻量级 ORM,简单易用,适合小型项目。

Django ORM:如果使用 Django 框架,其内置的 ORM 提供了非常方便的数据库访问方式。

示例(SQLAlchemy):

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
new_user = User(name='Alice')
session.add(new_user)
session.commit()
users = session.query(User).all()
for user in users:
    print(user.name)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

4. 数据处理与分析

Pandas:提供高性能的数据结构和数据分析工具,广泛应用于金融、统计等领域。

NumPy:用于科学计算的基础库,特别擅长处理大型多维数组和矩阵运算。

SciPy:基于 NumPy 构建,提供了更多的数学函数和算法。

示例(Pandas):

import pandas as pd
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': ['a', 'b', 'c']
})
print(df)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

5. 机器学习与深度学习

Scikit-learn:专注于传统机器学习算法的库,提供了数据预处理、模型选择等功能。

TensorFlow 和 PyTorch:两个最流行的深度学习框架,支持 GPU 加速训练。

示例(Scikit-learn):

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2)
clf = KNeighborsClassifier()
clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

6. 图像处理

Pillow (PIL Fork):Python Imaging Library 的一个分支,提供了广泛的图像处理功能。

OpenCV:开源计算机视觉库,包含了大量的图像处理和机器视觉算法。

示例(Pillow):

from PIL import Image
img = Image.open('example.jpg')
gray_img = img.convert('L')  # 转换为灰度图像
gray_img.show()
  • 1.
  • 2.
  • 3.
  • 4.

7. 自然语言处理

NLTK:经典的 NLP 库,涵盖了分词、词性标注、句法解析等多个方面。

spaCy:更现代化的 NLP 库,注重速度和效率,特别适合生产环境中的应用。

示例(spaCy):

import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Apple is looking at buying U.K. startup for $1 billion")
for ent in doc.ents:
    print(ent.text, ent.label_)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

8. 命令行接口

Click:用于创建漂亮且易于使用的命令行界面(CLI)的应用程序。

Argparse:Python 标准库中的模块,用于解析命令行参数。

示例(Click):

import click
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.argument('name')
def hello(count, name):
    for _ in range(count):
        click.echo(f"Hello {name}!")
if __name__ == '__main__':
    hello()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

9. 并发与并行

Threading 和 Multiprocessing:分别用于实现多线程和多进程编程。

Asyncio:用于编写异步 I/O 程序,特别是网络服务端应用程序。

示例(Asyncio):

import asyncio
async def main():
    print('Hello')
    await asyncio.sleep(1)
    print('World')
asyncio.run(main())
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

10. 测试

unittest:Python 内置的单元测试框架。

pytest:一个扩展性强的测试框架,简化了测试编写和执行过程。

示例(pytest):

# test_example.py
def add(a, b):
    return a + b
def test_add():
    assert add(1, 2) == 3
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

11. 日志记录

logging:Python 内置的日志记录模块,提供了灵活的日志配置选项。

示例(logging):

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info('This is an info message')
  • 1.
  • 2.
  • 3.
  • 4.
责任编辑:华轩 来源: 测试开发学习交流
相关推荐

2024-10-25 08:30:55

NumPyPandasMatplotlib

2019-02-28 20:46:35

Python高级技巧编程语言

2009-07-03 10:31:57

什么是ServletServlet API

2022-09-30 10:44:47

Netty组件数据

2022-11-28 08:02:17

DNSIP计算机

2020-03-13 09:29:27

物联网通信互联网

2022-03-09 09:39:22

Python函数模块

2022-03-21 21:55:43

Python编程语言

2023-05-08 15:59:17

Redis数据删除

2023-08-13 16:32:12

JavaScript

2010-07-16 09:24:59

Perl模式

2025-02-11 09:49:12

2018-08-13 14:50:02

2020-07-29 10:00:38

PythonEllipsis索引

2021-03-15 08:15:42

ES2021语言开发

2020-11-23 08:16:22

物联网

2022-06-07 14:15:44

Vue开发工具

2022-03-08 15:32:49

Python数据集合代码

2021-12-10 08:13:02

MatplotlibpythonAPI

2024-01-23 09:08:47

软件架构REST
点赞
收藏

51CTO技术栈公众号