
Python生态系统提供了丰富的API接口,覆盖了从Web开发到机器学习的各个领域。以下是15个常用API对象的详细介绍,包含使用说明和原创代码示例。
使用说明:轻量级Web框架,适合快速构建RESTful API
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/users', methods=['GET'])
def get_users():
users = [{'id': 1, 'name': '张三'}, {'id': 2, 'name': '李四'}]
return jsonify(users)
if __name__ == '__main__':
app.run(debug=True)使用说明:简化HTTP请求发送过程,支持各种HTTP方法
import requests
# GET请求示例
response = requests.get(' http://httpbin.org/json')
print(f"状态码: {response.status_code}")
print(f"响应内容: {response.text}")
# POST请求示例
data = {'title': '测试文章', 'content': '这是内容'}
post_resp = requests.post(' http://httpbin.org/post', json=data)使用说明:数据库对象关系映射工具,支持多种数据库
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker, declarative_base
Base = declarative_base()
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True)
name = Column(String(50))
price = Column(Integer)
# 创建数据库连接
engine = create_engine('sqlite:///products.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# 添加新记录
new_product = Product(name='笔记本电脑', price=5999)
session.add(new_product)
session.commit()使用说明:提供高性能数据结构和数据分析工具
import pandas as pd
import numpy as np
# 创建DataFrame
data = {
'城市': ['北京', '上海', '广州', '深圳'],
'人口(万)': [2154, 2428, 1530, 1303],
'GDP(亿元)': [36103, 38701, 25019, 27670]
}
df = pd.DataFrame(data)
# 数据操作
print(df.head())
print(f"平均GDP: {df['GDP(亿元)'].mean()}亿元")使用说明:传统机器学习算法库
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# 生成示例数据
X, y = make_classification(n_samples=1000, n_features=4, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
# 训练模型
clf = RandomForestClassifier(n_estimators=100)
clf.fit(X_train, y_train)
# 预测并评估
accuracy = clf.score(X_test, y_test)
print(f"模型准确率: {accuracy:.2f}")使用说明:Python图像处理库
from PIL import Image, ImageFilter
# 创建新图像
img = Image.new('RGB', (300, 200), color='lightblue')
# 图像操作
img = img.filter(ImageFilter.BLUR)
img = img.rotate(45)
img.save('processed_image.png')使用说明:现代化NLP库,适合生产环境
import spacy
nlp = spacy.load("zh_core_web_sm")
text = "清华大学位于北京市海淀区,成立于1911年。"
doc = nlp(text)
for token in doc:
print(f"词: {token.text}, 词性: {token.pos_}")使用说明:创建命令行界面应用程序
import click
@click.group()
def cli():
pass
@cli.command()
@click.option('--verbose', is_flag=True, help='详细输出')
def status(verbose):
if verbose:
click.echo("系统状态: 运行正常")
else:
click.echo("正常")
if __name__ == '__main__':
cli()使用说明:异步I/O编程支持
import asyncio
async def fetch_data(task_id, delay):
print(f"任务{task_id}开始执行")
await asyncio.sleep(delay)
print(f"任务{task_id}完成")
return f"任务{task_id}结果"
async def main():
tasks = [
fetch_data(1, 2),
fetch_data(2, 1),
fetch_data(3, 3)
]
results = await asyncio.gather(*tasks)
print(f"所有任务完成: {results}")
asyncio.run(main())使用说明:简化测试编写和执行
# calculator.py
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
# test_calculator.py
def test_add():
calc = Calculator()
assert calc.add(2, 3) == 5
def test_multiply():
calc = Calculator()
assert calc.multiply(4, 5) == 20使用说明:灵活的日志记录配置
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('app.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger('my_app')
logger.info('应用程序启动')
logger.debug('调试信息')使用说明:基于类型提示的高性能API框架
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
async def create_item(item: Item):
return {"message": f"商品 {item.name} 创建成功", "price": item.price}使用说明:支持同步和异步的HTTP客户端
import asyncio
import httpx
async def fetch_urls():
async with httpx.AsyncClient() as client:
responses = await asyncio.gather(
client.get(' https://httpbin.org/get'),
client.get(' https://httpbin.org/ip')
)
for response in responses:
print(f"状态码: {response.status_code}")
print(f"内容: {response.json()}")
asyncio.run(fetch_urls())使用说明:简单易用的对象关系映射器
from peewee import SqliteDatabase, Model, CharField, IntegerField
db = SqliteDatabase('students.db')
class Student(Model):
name = CharField()
age = IntegerField()
class Meta:
database = db
db.connect()
db.create_tables([Student])
# 创建记录
student = Student.create(name='王五', age=20)
print(f"创建学生: {student.name}")使用说明:图像处理和计算机视觉库
import cv2
import numpy as np
# 创建示例图像
image = np.zeros((300, 400, 3), dtype=np.uint8)
cv2.rectangle(image, (50, 50), (200, 150), (0, 255, 0), 2)
cv2.putText(image, 'OpenCV Demo', (60, 100),
cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
cv2.imwrite('demo_image.jpg', image)这些API对象覆盖了Python开发的主要领域,熟练掌握能极大提升开发效率。每个库都有详细的官方文档,建议在实际项目中根据具体需求深入学习和使用。
“无他,惟手熟尔”!有需要的用起来!
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!