本培训方案将详细描述如何使用Python实现一个自动生成生日贺卡并上传或发送的脚本。内容分为三个部分:
- 贺卡生成:涵盖相关库的基础知识、数据读取、贺卡生成的流程和实现代码。
- 文件上传:介绍网络基础知识、贺卡上传的流程和实现代码。
- API调用:简要介绍通过企业微信API实现可投入生产环境的脚本。
第一部分:贺卡生成
1. 概述
在本部分中,主要涉及:
- 使用Python读取Excel文件中的数据。
- 使用Pillow库生成个性化的生日贺卡。
2. 必要的Python库
pandas:用于数据读取和处理。
pip install pandas
Pillow(PIL):用于图像处理和编辑。
pip install Pillow
3. 数据读取
步骤:
导入pandas库:
import pandas as pd
读取Excel文件:
data = pd.read_excel('birth.xlsx')
确保生日列为日期类型:
data['生日'] = pd.to_datetime(data['生日'])
4. 贺卡生成流程
流程:
获取当前日期:
import datetime today = datetime.datetime.now() month = today.month day = today.day
筛选当天生日人员:
birthday_people = data[(data['生日'].dt.month == month) & (data['生日'].dt.day == day)]
遍历生日人员,生成贺卡:
from PIL import Image, ImageDraw, ImageFont for index, person in birthday_people.iterrows(): name = person['姓名'] # 后续步骤
打开贺卡模板:
image = Image.open('template.png') draw = ImageDraw.Draw(image)
定义字体和颜色:
font = ImageFont.truetype('Arial.ttf', 40) text_color = (0, 0, 0) # 黑色
在贺卡上添加祝福语:
text_position = (100, 100) # 根据需要调整 message = f'祝{name}生日快乐!' draw.text(text_position, message, fill=text_color, font=font)
保存生成的贺卡:
output_path = f'card_{name}.png' image.save(output_path)
5. 实现代码
import pandas as pd
from PIL import Image, ImageDraw, ImageFont
import datetime
# 读取Excel文件
data = pd.read_excel('birth.xlsx')
data['生日'] = pd.to_datetime(data['生日'])
# 获取今天的日期
today = datetime.datetime.now()
month = today.month
day = today.day
# 筛选当天生日人员
birthday_people = data[(data['生日'].dt.month == month) & (data['生日'].dt.day == day)]
# 如果有生日人员,生成贺卡
if not birthday_people.empty:
for index, person in birthday_people.iterrows():
name = person['姓名']
# 打开贺卡模板
image = Image.open('template.png')
draw = ImageDraw.Draw(image)
# 定义字体和颜色
font = ImageFont.truetype('Arial.ttf', 40)
text_color = (0, 0, 0)
# 添加祝福语
text_position = (100, 100)
message = f'祝{name}生日快乐!'
draw.text(text_position, message, fill=text_color, font=font)
# 保存贺卡
output_path = f'card_{name}.png'
image.save(output_path)
else:
print('今天没有人过生日。')
第二部分:贺卡上传
1. 概述
本部分主要包括如何将生成的贺卡上传到指定的Web服务器。这需要了解一些基本的网络知识和使用requests
库进行HTTP请求。
2. 必要的Python库
requests:用于发送HTTP请求。
pip install requests
3. 网络基础知识
- HTTP协议:用于客户端和服务器之间的通信。常用的请求方法包括GET和POST。
- 文件上传:通常使用POST请求,将文件作为表单数据上传。
4. 贺卡上传流程
流程:
准备上传URL:获取服务器提供的上传接口,例如:
upload_url = 'http://example.com/upload'
构建上传请求:
import requests files = {'file': open(output_path, 'rb')} response = requests.post(upload_url, files=files)
处理服务器响应:
if response.status_code == 200: print(f'{name}的贺卡上传成功!') else: print(f'{name}的贺卡上传失败,状态码:{response.status_code}')
5. 实现代码
将上传部分添加到之前的贺卡生成代码中:
import requests
# 省略前面的代码
# 上传URL
upload_url = 'http://example.com/upload' # 请替换为实际的上传地址
# 在生成贺卡后,上传贺卡
# 保存生成的贺卡
output_path = f'card_{name}.png'
image.save(output_path)
# 上传贺卡
files = {'file': open(output_path, 'rb')}
response = requests.post(upload_url, files=files)
if response.status_code == 200:
print(f'{name}的贺卡上传成功!')
else:
print(f'{name}的贺卡上传失败,状态码:{response.status_code}')
# 关闭文件
files['file'].close()
第三部分:扩展—通过企业微信API发送贺卡
1. 概述
为了提高应用实用性,可以直接通过企业微信将贺卡发送给指定的用户。企业微信提供了丰富的API接口,可以满足这一需求。
2. 企业微信API简介
- 应用注册:在企业微信管理后台创建应用,获取
CorpID
、CorpSecret
和AgentID
。 - 用户管理:确保企业微信通讯录中的用户
UserID
与学号对应。
3. 发送贺卡流程
流程:
获取
access_token
:使用CorpID
和CorpSecret
调用企业微信API获取访问令牌。def get_access_token(corp_id, corp_secret): url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}' response = requests.get(url) return response.json().get('access_token')
上传媒体文件:将贺卡图片上传到企业微信,获取
media_id
。def upload_media(access_token, file_path): url = f'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=image' files = {'media': open(file_path, 'rb')} response = requests.post(url, files=files) return response.json().get('media_id')
发送图片消息:使用
media_id
通过API发送消息给指定用户。def send_image_message(access_token, user_id, media_id, agent_id): url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}' data = { "touser": user_id, "msgtype": "image", "agentid": agent_id, "image": { "media_id": media_id }, "safe": 0 } response = requests.post(url, json=data) return response.json()
4. 实现代码
完整的Python代码:
import pandas as pd
from PIL import Image, ImageDraw, ImageFont
import datetime
import requests
import os
# 企业微信配置
CORP_ID = '企业ID'
CORP_SECRET = '应用Secret'
AGENT_ID = '应用ID'
# 获取access_token
def get_access_token(corp_id, corp_secret):
url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}'
response = requests.get(url)
response_data = response.json()
if response_data.get('errcode') == 0:
return response_data.get('access_token')
else:
print(f"获取access_token失败,错误信息:{response_data}")
return None
# 上传媒体文件
def upload_media(access_token, file_path):
url = f'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=image'
with open(file_path, 'rb') as file:
files = {'media': file}
response = requests.post(url, files=files)
response_data = response.json()
if response_data.get('errcode') == 0:
return response_data.get('media_id')
else:
print(f"上传媒体文件失败,错误信息:{response_data}")
return None
# 发送图片消息
def send_image_message(access_token, user_id, media_id, agent_id):
url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}'
data = {
"touser": user_id,
"msgtype": "image",
"agentid": agent_id,
"image": {
"media_id": media_id
},
"safe": 0
}
response = requests.post(url, json=data)
return response.json()
# 主程序
def main():
# 读取Excel文件
data = pd.read_excel('birth.xlsx')
data['生日'] = pd.to_datetime(data['生日'])
# 获取今天的日期
today = datetime.datetime.now()
month = today.month
day = today.day
# 筛选当天生日人员
birthday_people = data[(data['生日'].dt.month == month) & (data['生日'].dt.day == day)]
# 获取access_token
access_token = get_access_token(CORP_ID, CORP_SECRET)
if not access_token:
print("无法获取access_token,程序退出。")
return
# 如果有生日人员,发送贺卡
if not birthday_people.empty:
for index, person in birthday_people.iterrows():
name = person['姓名']
student_id = person['学号']
user_id = str(student_id) # 假设UserID与学号一致
# 生成贺卡
image = Image.open('template.png')
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('Arial.ttf', 40)
text_color = (0, 0, 0)
text_position = (100, 100)
message = f'祝{name}生日快乐!'
draw.text(text_position, message, fill=text_color, font=font)
output_path = f'card_{name}.png'
image.save(output_path)
# 上传媒体文件
media_id = upload_media(access_token, output_path)
if not media_id:
print(f"无法上传媒体文件,跳过{name}。")
continue
# 发送消息
result = send_image_message(access_token, user_id, media_id, AGENT_ID)
if result.get('errcode') == 0:
print(f'已成功向{name}发送生日贺卡。')
else:
print(f'向{name}发送生日贺卡失败,错误信息:{result}')
# 删除本地贺卡文件
os.remove(output_path)
else:
print('今天没有人过生日。')
if __name__ == '__main__':
main()
5. 部署与运行
设置定时任务:
- Linux系统:使用
cron
定时任务,每天定时运行脚本。 - Windows系统:使用任务计划程序,设置每日触发。
保护敏感信息:
- 将
CORP_SECRET
等敏感信息保存在安全的地方。 - 避免将敏感信息上传到公共代码仓库。
6. 参考资料
总结:
本培训方案详细介绍了如何使用Python实现生日贺卡的自动生成和上传功能,以及通过企业微信API发送贺卡的扩展功能。通过学习本方案,我们可以更好地理解Python在实陃应用中的强大功能,提高工作效率和创造力。