from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
import os
def generate_api_document(url, api_name, method, request_data, response_data):
# 定义PDF文档路径和名称
file_path = f"{api_name}.pdf"
# 创建PDF文档
doc = SimpleDocTemplate(file_path, pagesize=letter)
elements = []
# 标题样式
styles = getSampleStyleSheet()
title = Paragraph(f"API Documentation: {api_name}", styles['Title'])
elements.append(title)
# 添加URL信息
url_paragraph = Paragraph(f"URL: {url}", styles['Normal'])
elements.append(url_paragraph)
# 添加请求方式信息
url_paragraph = Paragraph(f"Method: {method}", styles['Normal'])
elements.append(url_paragraph)
# 方法用于生成表格
def create_table(data, title):
table_data = [list(data[0].keys())] # 表头为字段字典的键
for item in data:
table_data.append(list(item.values()))
# 创建和设置表格样式
table = Table(table_data)
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('GRID', (0, 0), (-1, -1), 1, colors.black),
('BACKGROUND', (0, 1), (-1, -1), colors.beige),
]))
elements.append(Paragraph(title, styles['Heading2']))
elements.append(table)
# 生成请求参数和响应参数的表格
create_table(request_data, "Request Parameters")
create_table(response_data, "Response Parameters")
# 构建PDF
doc.build(elements)
# 返回生成的文档路径和文件名
return os.path.abspath(file_path)
# 示例调用功能
request_data_example = [
{"field": "user_id", "type": "int", "length": 11, "null": "false", "field_desc": "User Identifier"},
{"field": "email", "type": "string", "length": 256, "null": "false", "field_desc": "Email Address"}
]
response_data_example = [
{"field": "status", "type": "string", "length": 10, "null": "false", "field_desc": "Response Status"},
{"field": "message", "type": "string", "length": 256, "null": "true", "field_desc": "Additional Message"}
]
result = generate_api_document(
url="/api/v1/user/",
api_name="UserAPI",
method="POST",
request_data=request_data_example,
response_data=response_data_example
)
print("Document generated at:", result)
标签:elements,api,python,field,API,url,table,pdf,data
From: https://www.cnblogs.com/lanjianhua/p/18555314