12.Python常用的第三方模块


Python作为一门强大的编程语言,凭借其简洁易学的语法和丰富的生态系统,成为了众多开发者的首选。除了Python内置的标准库外,还有大量的第三方模块可以扩展Python的功能。在本篇博客中,我们将介绍一些工作中经常用到的一些偏工具类的第三方模块,它们能够帮助我们更高效地进行开发和解决各种问题。

一、jsonpath模块

jsonpath模块为我们提供了这样一种功能:通过表达式来提取一个json中某些节点的值

关于jsonpath的表达式,可以参考官网:https://goessner.net/articles/JsonPath/%20

下面列举一些常见的表达式

import json, jsonpath

content = '''
{ "store": {
  "book": [
   { "category": "reference",
    "author": "Nigel Rees",
    "title": "Sayings of the Century",
    "price": 8.95
   },
   { "category": "fiction",
    "author": "Evelyn Waugh",
    "title": "Sword of Honour",
    "price": 12.99
   },
   { "category": "fiction",
    "author": "Herman Melville",
    "title": "Moby Dick",
    "isbn": "0-553-21311-3",
    "price": 8.99
   },
   { "category": "fiction",
    "author": "J. R. R. Tolkien",
    "title": "The Lord of the Rings",
    "isbn": "0-395-19395-8",
    "price": 22.99
   }
  ],
  "bicycle": {
   "color": "red",
   "price": 19.95
  }
 }
}
'''

obj = json.loads(content)

# 取所有书的作者
authors = jsonpath.jsonpath(obj, "$.store.book[*].author")
print(authors)

# 取所有的作者
authors = jsonpath.jsonpath(obj, "$..author")
print(authors)

# 取store下所有的子节点
staff = jsonpath.jsonpath(obj, "$.store.*")
print(staff)

# 取store下所有的价格,包括书、自行车的价格
prices = jsonpath.jsonpath(obj, "$.store..price")
print(prices)

# 取第一本书的价格
first_book = jsonpath.jsonpath(obj, "$..book[0]")
print(first_book)

# 最后一本书
last_book = jsonpath.jsonpath(obj, "$..book[(@.length-1)]")
print(last_book)

# 前两本书
first_two_books = jsonpath.jsonpath(obj, "$..book[0,1]")
print(first_two_books)

# 前两本书的另一种取值方法
first_two_books = jsonpath.jsonpath(obj, "$..book[:2]")
print(first_two_books)

# 所有书中有isbn属性的节点
books_contains_isbn = jsonpath.jsonpath(obj, "$..book[?(@.isbn)]")
print(books_contains_isbn)

# 价格小于10的书
books_low_price = jsonpath.jsonpath(obj, "$..book[?(@.price<10)]")
print(books_low_price)

# 作者是Nigel Rees的书
books_nigel_rees = jsonpath.jsonpath(obj, "$..book[?(@.author=='Nigel Rees')]")
print(books_nigel_rees)

二、requests模块

requests模块为我们提供了一种简单而优雅的方式来发送HTTP请求并处理响应。使用它可以发送GET和POST请求、处理响应内容,从而使我们的HTTP请求变得高效和可靠。

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}

wd = {"wd": "谦谦君子,温润如玉"}
url = "https://www.baidu.com/s?"

# 支持get/post等http方法,可以设置参数、headers、cookies
response = requests.get(url, params=wd, headers=headers)
print(type(response))

# http响应码
print(response.status_code)

# 取出响应的unicode编码的字符串
data = response.text
print(data)

# 取出响应的二进制流,可以自己编码
binary_data = response.content

# 将响应内容解析为JSON格式
json_response = response.json()

三、tqdm模块

如果需要执行一个比较久的循环,那么我们希望可以看到执行进度,tqdm为我们提供了进度条的功能,下面是两种常见的使用方式。

from tqdm.autonotebook import tqdm
import time

# 第一种是将一个可迭代对象放入tqdm中
for i in tqdm(range(1, 5), colour="blue"):
    time.sleep(1)

# 第二种是设置一个总量,然后在循环中手动更新
progress = tqdm(total=5, colour="blue")
for i in range(1, 5):
    progress.update(1)
    time.sleep(1)

四、连接mysql

准备工作

在开始之前,确保您已经安装了Python以及mysql-connector库。可以使用以下命令来安装这个库:

pip install mysql-connector-python
连接到MySQL数据库

在Python中,我们可以使用mysql-connector库来连接MySQL数据库。以下是连接到数据库的基本步骤:

import mysql.connector

# 配置数据库连接参数
config = {
    'host': 'localhost',
    'user': 'your_username',
    'password': 'your_password',
    'database': 'your_database_name'
}

# 连接数据库
connection = mysql.connector.connect(**config)

# 创建一个游标对象
cursor = connection.cursor()

# 执行SQL查询和操作

# 关闭游标和连接
cursor.close()
connection.close()

在上面的代码中,我们首先通过配置一个字典来设置数据库连接参数,包括主机地址、用户名、密码和数据库名称。然后,使用mysql.connector.connect()方法来建立数据库连接,并创建一个游标对象用于执行SQL查询和操作。最后,在完成操作后,务必关闭游标和连接。

执行SQL查询

一旦连接到数据库,我们可以使用游标对象执行各种SQL查询和操作。以下是一些常见的操作示例:

  1. 执行查询:
# 查询语句
query = "SELECT * FROM users"

# 执行查询
cursor.execute(query)

# 获取查询结果
results = cursor.fetchall()

for row in results:
    print(row)
  1. 插入数据:
# 插入语句
insert_query = "INSERT INTO users (username, email) VALUES (%s, %s)"
data = ("john_doe", "john@example.com")

# 执行插入
cursor.execute(insert_query, data)

# 提交更改
connection.commit()
  1. 更新数据:
# 更新语句
update_query = "UPDATE users SET email = %s WHERE username = %s"
data = ("new_email@example.com", "john_doe")

# 执行更新
cursor.execute(update_query, data)

# 提交更改
connection.commit()
  1. 删除数据:
# 删除语句
delete_query = "DELETE FROM users WHERE username = %s"
data = ("john_doe",)

# 执行删除
cursor.execute(delete_query, data)

# 提交更改
connection.commit()
错误处理和资源释放

在进行数据库操作时,务必进行错误处理以及适时释放资源。使用tryexcept来捕获可能发生的异常,确保代码的健壮性。同时,不要忘记在操作完成后关闭游标和连接

try:
    # 执行数据库操作
except mysql.connector.Error as err:
    print("操作出现错误:", err)
finally:
    cursor.close()
    connection.close()

五、连接redis

Redis是一个高性能的键值存储系统,广泛用于缓存、消息队列等应用场景。在Python中,我们可以使用redis-py库来方便地操作Redis数据库。本文将介绍如何使用Python连接到Redis,执行基本的操作,并举例说明常见的用法。

安装redis-py

在开始之前,我们需要安装redis-py库。可以使用pip进行安装:

pip install redis

连接到Redis数据库

首先,我们需要导入redis模块,然后建立与Redis数据库的连接:

import redis

# 建立连接
redis_client = redis.Redis(host='localhost', port=6379, db=0)

基本操作示例

# 存储键值对
redis_client.set('name', 'Alice')

# 获取键值对
name = redis_client.get('name')
print(f'Name: {name.decode("utf-8")}')

# 列表操作
redis_client.rpush('fruits', 'apple', 'banana', 'orange')
fruits = redis_client.lrange('fruits', 0, -1)
print(f'Fruits: {fruits}')

# 集合操作
redis_client.sadd('colors', 'red', 'green', 'blue')
colors = redis_client.smembers('colors')
print(f'Colors: {colors}')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值