一、个人任务
我的任务主要是对后端的功能进行丰富,后端的性能、可用性、安全性进行提升
二、任务——后端改进和优化
2.1 service层
1.前台
相比于之前的逻辑处理,我增加了对异常的处理和对传参的检查,提高系统健壮性
下面举出部分例子
在feedback.py中,代码修改为
def insert_feedback(db_conn, user_id, content, type_):
c_time = datetime.now()
try:
# 使用参数化查询来避免 SQL 注入
query = """
INSERT INTO user_feedback (user_id, content, created_at, status, type)
VALUES (%s, %s, %s, %s, %s)
"""
params = (user_id, content, c_time, 0, type_)
# 假设 db_conn.execute 返回插入的行数(或受影响的行数)
num = db_conn.execute(query, params)
db_conn.commit() # 确保提交事务
return num
except Exception as e:
print(f"Failed to insert feedback: {e}")
return None
def check_feedback_params(user_id, content, type_):
if not user_id or not content or not type_:
return False, "User ID, content and type are required"
return True, None
records.py中
def get_specific_pre_records(db_conn, user_id, record_type):
sql_str = """
SELECT
user_id, record_id, question, answer, type, q_time
FROM
records
WHERE
user_id = %s AND type = %s
ORDER BY
q_time ASC
"""
try:
# 假设 db_conn.execute_query 是一个返回结果集的函数
results = db_conn.execute_query(sql_str, (user_id, record_type))
# 格式化结果集
formatted_results = [
{'record_id': r[1], 'question': r[2], 'answer': r[3], 'type': r[4], 'q_time': r[5]}
for r in results
]
return formatted_results
except Exception as e:
print(f"Error fetching specific pre-records: {e}")
return None
def validate_input(user_id, record_type):
if not user_id:
return False, "User ID is required"
if not record_type:
return False, "Record type is required"
return True, None
2.后台
和前台同理,增加了对输入的验证和对异常的处理
def get_full_logindata_week(db_conn, start_time, end_time):
"""
获取指定时间范围内的登录数据。
:param db_conn: 数据库连接
:param start_time: 起始时间
:param end_time: 结束时间
:return: 登录数据列表
"""
db_conn = get_db_conn()
# 验证输入参数
if not isinstance(db_conn, type(db_conn)):
raise ValueError("Invalid db_conn provided.")
if not isinstance(start_time, datetime):
raise ValueError("Invalid start_time provided.")
if not isinstance(end_time, datetime):
raise ValueError("Invalid end_time provided.")
if start_time >= end_time:
raise ValueError("Start time should be before end time.")
# 生成所有可能的时间段列表
time_intervals = generate_time_intervals6(start_time, end_time)
# 从数据库中获取登录次数(使用批量查询)
try:
db_results = get_full_logindata2(db_conn, time_intervals) # 假设这个函数存在
except Exception as e:
print(f"Error fetching login counts from DB: {e}")
# 构造一个字典,方便根据时间段查找登录次数
db_results_dict = {result[0]: result[1] for result in db_results if
isinstance(result, (tuple, list)) and len(result) == 2}
# 初始化Logindata6列表,并用0填充所有时间段
Logindata6 = [0] * len(time_intervals)
# 遍历时间段列表,并更新Logindata6中对应的值
for i, (start, end) in enumerate(time_intervals):
hour_interval = start.hour
if hour_interval in db_results_dict:
Logindata6[i] = db_results_dict[hour_interval]
else:
print(f"No login data for time interval {start}-{end}")
2.2 controller层
同理,也增加了对异常的处理
前台
@app.route('/api/front/set_feedback', methods=['GET']) # 通常反馈是通过 POST 发送的
def set_feedback():
try:
# 从请求体中获取 user_id, content 和 type
# 注意:GET 请求通常不包含请求体,但在这里我们假设使用 POST 或其他方法
user_id = request.json.get('user_id')
content = request.json.get('content')
type_ = request.json.get('type')
# 检查参数是否有效
valid, error_msg = FeedbackService.check_feedback_params(user_id, content, type_)
if not valid:
return jsonify({"error": error_msg}), 400
# 插入反馈
num = FeedbackService.insert_feedback( user_id, content, type_)
if num is None:
return jsonify({"error": "Failed to insert feedback"}), 500
return jsonify({"message": "成功添加"}), 200
except Exception as e:
print(e)
return jsonify({"error": "Internal Server Error"}), 500
@app.route('/api/front/getSpePreRecords', methods=['GET'])
def getSpecPreRecords():
"""
获取指定用户的特定类型记录
"""
try:
# 从请求参数中获取 user_id 和 type
user_id = request.args.get('user_id')
record_type = request.args.get('type')
# 验证输入
is_valid, error_message = RecordService.validate_input(user_id, record_type)
if not is_valid:
return jsonify({'error': error_message}), 400
db_conn = get_db_conn()
# 调用服务层函数获取特定用户的记录
results = RecordService.get_specific_pre_records(db_conn, user_id, record_type)
if results is None:
return jsonify({'error': 'Internal Server Error'}), 500
if not results:
return jsonify({'message': 'No records found for the given user_id and type'}), 200
return jsonify(results), 200
except Exception as e:
print(e)
return jsonify({'error': 'Internal Server Error'}), 500
@app.route('/api/front/getRandomQues', methods=['GET'])
def getRandomQues():
try:
# 调用服务层函数获取随机问题
data = RecordService.get_random_questions()
if not data:
return jsonify({'message': 'No questions found'}), 200
return jsonify(data), 200
except Exception as e:
print(e)
return msg(500, 'Internal Server Error')
@app.route('/api/front/set_Records', methods=['GET'])
def set_Records():
try:
# 从请求中获取user_id
user_id = request.args.get('user_id')
if not user_id:
return msg(400, 'User ID is required')
# 调用服务层函数获取用户记录
results = RecordService.get_user_records(user_id)
if not results:
return jsonify({'message': 'No records found for the given user_id'}), 200
return jsonify(results), 200
except Exception as e:
print(e)
return msg(500, 'Internal Server Error')
后台
@app.route('/back/record/deleteRecord/', methods=['DELETE']) # 推荐使用DELETE方法删除资源
def deleteRecord():
record_id = request.args.get('id')
if not record_id:
return jsonify({'error': 'Record ID is required'}), 400 # 如果缺少ID,返回400错误
# 调用服务层函数
result = RecordService.delete_record_by_id(record_id)
if result:
return jsonify({'message': 'Record deleted successfully'}), 200 # 如果删除成功,返回200状态码和消息
else:
return jsonify({'error': 'Failed to delete record'}), 404 # 如果删除失败,返回404错误
@app.route('/back/record/getBarChart11/', methods=['GET'])
def getBarChart11():
now = datetime.now()
yesterday_start = now - timedelta(days=1)
yesterday_start = yesterday_start.replace(hour=0, minute=0, second=0, microsecond=0)
yesterday_end = yesterday_start + timedelta(days=1)
data = RecordService.get_login_data_for_period(get_db_conn(), yesterday_start, yesterday_end, get_full_logindata2)
if data is None:
return jsonify({"error": "Failed to fetch data"}), 201
return jsonify(data), 200
四、总结
1、任务概述
本次个人任务聚焦于后端系统的功能扩展、性能优化、可用性增强和安全性加固。通过精心策划和实施,我成功实现了这些目标,为后端系统带来了显著的改进。
项目最后的树状结构图如下
E:\MODEL\TASK_L
├─.idea
│ └─inspectionProfiles
├─controller
│ ├─back
│ └─front
├─database_service
├─env
│ ├─Lib
│ │ └─site-packages
│ │ ├─blinker
│ │ │ └─__pycache__
│ │ ├─blinker-1.8.2.dist-info
│ │ ├─click
│ │ │ └─__pycache__
│ │ ├─click-8.1.7.dist-info
│ │ ├─colorama
│ │ │ ├─tests
│ │ │ │ └─__pycache__
│ │ │ └─__pycache__
│ │ ├─colorama-0.4.6.dist-info
│ │ │ └─licenses
│ │ ├─dbutils
│ │ │ └─__pycache__
│ │ ├─DBUtils-3.1.0.dist-info
│ │ ├─flask
│ │ │ ├─json
│ │ │ │ └─__pycache__
│ │ │ ├─sansio
│ │ │ │ └─__pycache__
│ │ │ └─__pycache__
│ │ ├─flask-3.0.3.dist-info
│ │ ├─itsdangerous
│ │ │ └─__pycache__
│ │ ├─itsdangerous-2.2.0.dist-info
│ │ ├─jinja2
│ │ │ └─__pycache__
│ │ ├─jinja2-3.1.4.dist-info
│ │ ├─markupsafe
│ │ │ └─__pycache__
│ │ ├─MarkupSafe-2.1.5.dist-info
│ │ ├─pip
│ │ │ ├─_internal
│ │ │ │ ├─cli
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─commands
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─distributions
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─index
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─locations
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─metadata
│ │ │ │ │ ├─importlib
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─models
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─network
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─operations
│ │ │ │ │ ├─build
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ ├─install
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─req
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─resolution
│ │ │ │ │ ├─legacy
│ │ │ │ │ ├─resolvelib
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─utils
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─vcs
│ │ │ │ │ └─__pycache__
│ │ │ │ └─__pycache__
│ │ │ ├─_vendor
│ │ │ │ ├─cachecontrol
│ │ │ │ │ ├─caches
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─certifi
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─chardet
│ │ │ │ │ ├─cli
│ │ │ │ │ ├─metadata
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─colorama
│ │ │ │ │ └─tests
│ │ │ │ ├─distlib
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─distro
│ │ │ │ ├─idna
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─msgpack
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─packaging
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─pkg_resources
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─platformdirs
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─pygments
│ │ │ │ │ ├─filters
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ ├─formatters
│ │ │ │ │ ├─lexers
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ ├─styles
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─pyparsing
│ │ │ │ │ ├─diagram
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─pyproject_hooks
│ │ │ │ │ ├─_in_process
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─requests
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─resolvelib
│ │ │ │ │ ├─compat
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─rich
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─tenacity
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─tomli
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─urllib3
│ │ │ │ │ ├─contrib
│ │ │ │ │ │ ├─_securetransport
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ ├─packages
│ │ │ │ │ │ ├─backports
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ ├─util
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─webencodings
│ │ │ │ └─__pycache__
│ │ │ └─__pycache__
│ │ ├─pip-23.2.1.dist-info
│ │ ├─pkg_resources
│ │ │ ├─extern
│ │ │ │ └─__pycache__
│ │ │ ├─_vendor
│ │ │ │ ├─importlib_resources
│ │ │ │ ├─jaraco
│ │ │ │ │ ├─text
│ │ │ │ │ │ └─__pycache__
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─more_itertools
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─packaging
│ │ │ │ │ └─__pycache__
│ │ │ │ ├─platformdirs
│ │ │ │ │ └─__pycache__
│ │ │ │ └─__pycache__
│ │ │ └─__pycache__
│ │ ├─pymysql
│ │ │ ├─constants
│ │ │ │ └─__pycache__
│ │ │ └─__pycache__
│ │ ├─PyMySQL-1.1.1.dist-info
│ │ ├─setuptools
│ │ │ ├─command
│ │ │ ├─config
│ │ │ │ └─_validate_pyproject
│ │ │ ├─extern
│ │ │ ├─_distutils
│ │ │ │ └─command
│ │ │ └─_vendor
│ │ │ ├─importlib_metadata
│ │ │ ├─importlib_resources
│ │ │ ├─jaraco
│ │ │ │ └─text
│ │ │ ├─more_itertools
│ │ │ ├─packaging
│ │ │ └─tomli
│ │ ├─setuptools-68.2.0.dist-info
│ │ ├─werkzeug
│ │ │ ├─datastructures
│ │ │ │ └─__pycache__
│ │ │ ├─debug
│ │ │ │ ├─shared
│ │ │ │ └─__pycache__
│ │ │ ├─middleware
│ │ │ │ └─__pycache__
│ │ │ ├─routing
│ │ │ │ └─__pycache__
│ │ │ ├─sansio
│ │ │ │ └─__pycache__
│ │ │ ├─wrappers
│ │ │ │ └─__pycache__
│ │ │ └─__pycache__
│ │ ├─werkzeug-3.0.3.dist-info
│ │ ├─wheel
│ │ │ ├─cli
│ │ │ └─vendored
│ │ │ └─packaging
│ │ ├─wheel-0.41.2.dist-info
│ │ ├─_distutils_hack
│ │ │ └─__pycache__
│ │ └─__pycache__
│ └─Scripts
├─models
│ └─front
└─service
├─back
└─front
2、功能丰富
- 新增了多个关键业务功能的API接口,有效支持了新业务场景的需求。
- 对现有功能进行了深度优化和扩展,提升了系统的灵活性和可扩展性。
3、性能提升
- 通过代码优化和重构,减少了资源消耗,提高了系统响应速度。
- 引入缓存机制,显著减少了数据库访问次数,进一步提升了系统性能。
- 实现了异步处理模式,有效避免了阻塞主线程,提高了系统吞吐量。
4、可用性增强
- 设计并实施了全面的容错处理机制,确保了系统的稳定性和可靠性。
- 建立了实时监控和报警系统,能够及时发现并处理系统异常。
- 完善了日志记录功能,为故障排查和恢复提供了有力支持。
5、安全性加固
- 加强了用户输入验证,有效防止了SQL注入、XSS等常见安全问题。
6、总结
在本次任务中,我成功实现了后端系统的功能丰富、性能提升、可用性增强和安全性加固。这些改进不仅提升了系统的整体性能,还增强了用户体验和数据安全性。