代码注释、API文档生成(使用千问)
代码注释是“给未来的自己和同事看”,核心是“说明‘为什么这么写’+‘怎么用’”。API文档是“给调用者看”,核心是“说明‘接口怎么调’+‘参数/响应是什么’”。
代码注释与API文档是代码可维护性与可复用性的核心。传统模式下,开发人员常因时间紧张导致注释缺失、文档不规范,影响后续维护与协作。千问可自动生成代码注释(单行注释、函数注释、类注释)与标准化API文档(如Swagger风格),确保代码可读性与文档规范性。
示例:生成代码注释和API文档
某公司后端团队正在开发一个基于Flask的用户登录接口。开发人员小张完成了核心逻辑,但尚未添加注释和文档。该接口接收POST请求,参数为username(必填)、password(必填)、captcha(可选),成功后返回JWT令牌。按照公司规范,他需要在今天下班前提交符合PEP8标准的代码注释和一份可用于Swagger的API文档。但他正忙于修复另一个紧急bug,急需一个工具能帮他快速生成初稿。
在代码对话框中输入如下提示词:
你是一名技术文档工程师,请为以下任务生成规范文档:
【任务类型】Python代码注释生成+RESTful API文档生成
【核心信息】
– 功能描述:用户登录认证
– 代码/接口详情:
– 请求方式:POST
– 接口路径:/api/v1/login
– 参数:username (str, 必填), password (str, 必填), captcha (str, 可选)
– 响应:JSON,成功时包含code=200, message, data(token, expire_time, username)
【输出要求】
1. 代码注释:符合Python PEP8规范,包含功能、参数、返回值、异常、备注。
2. API文档:包含接口路径、请求方法、参数详情、响应示例、错误码说明。
3. 格式清晰,支持直接复制到代码/Swagger。
输出结果如下:
Flask用户登录接口:
“””
@Author: 技术文档助手
@Version: 1.0
@Description: 用户登录认证接口模块,负责验证用户身份合法性,返回认证令牌
@Date: 2025-01-20
“””
from flask import Flask, request, jsonify
import jwt
import datetime
app = Flask(__name__)
app.config[‘SECRET_KEY’] = ‘your-secret-key’# 实际生产环境需使用环境变量存储
def verify_password(username: str, password: str) -> bool:
“””
验证用户名与密码合法性(模拟数据库校验逻辑)
Args:
username: 用户名(字符串,长度6-20位,仅含字母/数字)
password: 密码(字符串,长度8-20位,含字母+数字+特殊字符)
Returns:
bool: 验证通过返回True,否则返回False
Notes:
实际场景需对接数据库查询,此处为简化模拟;
生产环境需使用密码哈希校验(如bcrypt),禁止明文比对
“””
# 模拟数据库存储的用户名与加密后密码(示例数据)
mock_users = {
“test_user”: “$2b$12$EixZaYb4xU58Gpq1R0yWbeb00LU5qUaK6x6hTOj0K2qCk2aK6z2a”# 密码:Test@1234
}
if username not in mock_users:
return False
# 模拟哈希密码校验(实际需用bcrypt.checkpw(password.encode(), mock_users[username].encode()))
return password == “Test@1234”
@app.route(‘/api/v1/login’, methods=[‘POST’])
def user_login():
“””
用户登录认证接口:验证用户身份并生成JWT令牌
Request:
Content-Type: application/json
Body: {
“username”: string,// 用户名(必填)
“password”: string,// 密码(必填)
“captcha”: string// 验证码(可选,生产环境建议必填)
}
Response:
200 OK: {
“code”: 200,
“message”: “登录成功“,
“data”: {
“token”: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…”,// JWT令牌(有效期2小时)
“expire_time”: “2025-01-20T16:30:00Z”,
“username”: “test_user”
}
}
400 Bad Request: {
“code”: 400,
“message”: “参数缺失:用户名不能为空“
}
401 Unauthorized: {
“code”: 401,
“message”: “用户名或密码错误“
}
Errors:
400: 参数缺失/格式错误
401: 身份验证失败
500: 服务器内部错误
Notes:
1. JWT令牌有效期2小时,过期需重新登录;
2. 验证码功能需对接第三方验证码服务(如极验),此处简化省略;
3. 生产环境需添加HTTPS加密传输,避免密码泄露
“””
try:
data = request.get_json()
# 参数校验
if not data.get(“username”):
return jsonify({“code”: 400, “message”: “参数缺失:用户名不能为空“}), 400
if not data.get(“password”):
return jsonify({“code”: 400, “message”: “参数缺失:密码不能为空“}), 400
# 密码验证
if not verify_password(data[“username”], data[“password”]):
return jsonify({“code”: 401, “message”: “用户名或密码错误“}), 401
# 生成JWT令牌
expire = datetime.datetime.utcnow() + datetime.timedelta(hours=2)
token = jwt.encode(
{“username”: data[“username”], “exp”: expire},
app.config[‘SECRET_KEY’],
algorithm=”HS256″
)
return jsonify({
“code”: 200,
“message”: “登录成功“,
“data”: {
“token”: token,
“expire_time”: expire.isoformat() + “Z”,
“username”: data[“username”]
}
}), 200
except Exception as e:
return jsonify({“code”: 500, “message”: f”服务器内部错误:{str(e)}”}), 500
if __name__ == “__main__”:
app.run(debug=True, host=”0.0.0.0″, port=5000)
OpenAPI 3.0用户文档认证API文档:
openapi: 3.0.3
info:
title: 用户认证API
description: 提供用户登录、令牌验证等认证相关接口
version: 1.0.0
paths:
/api/v1/login:
post:
summary: 用户登录认证
description: 验证用户用户名和密码,生成有效期2小时的JWT令牌
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
username:
type: string
description: 用户名(6-20位,仅含字母/数字)
example: “test_user”
password:
type: string
description: 密码(8-20位,含字母+数字+特殊字符)
example: “Test@1234”
captcha:
type: string
description: 验证码(可选,生产环境建议必填)
example: “8F3D2A”
required:
– username
– password
responses:
‘200’:
description: 登录成功
content:
application/json:
schema:
type: object
properties:
code:
type: integer
example: 200
message:
type: string
example: “登录成功“
data:
type: object
properties:
token:
type: string
example: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…”
expire_time:
type: string
format: date-time
example: “2025-01-20T16:30:00Z”
username:
type: string
example: “test_user”
‘400’:
description: 参数缺失或格式错误
content:
application/json:
schema:
type: object
properties:
code:
type: integer
example: 400
message:
type: string
example: “参数缺失:用户名不能为空“
‘401’:
description: 身份验证失败
content:
application/json:
schema:
type: object
properties:
code:
type: integer
example: 401
message:
type: string
example: “用户名或密码错误“
‘500’:
description: 服务器内部错误
content:
application/json:
schema:
type: object
properties:
code:
type: integer
example: 500
message:
type: string
example: “服务器内部错误:xxx”
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
security:
– bearerAuth: []
代码注释符合 PEP8 规范(含功能、参数、备注),API文档支持 Swagger 导入(结构完整、包含参数/响应/错误码),可直接复制到项目中使用,方便同事调用和维护。


夜雨聆风