最近想开发一个基础的服务(reportServer), 提供管理测试报告的相关功能
首先讲下大概业务逻辑, 提供2个接口:
因为以前学过Django基础, 而且觉得Django搭建起来还是挺方便的, 所以决定使用Django写几个接口, 完成此次功能
对于本次需求来说, 没涉及到数据库相关操作, 只需要关注其中的URL层 + View层即可!
# 豆瓣源
pip install Django -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
# 创建项目
django-admin startproject 项目名
# 本次使用
django-admin startproject reportServer
# 启动服务
python manage.py runserver
主要写了log的配置方法, 使用的loguru模块
# 豆瓣源
pip install loguru -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
文件内容如下:
from loguru import logger
import os
log_name = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), "log", "reportServer.log")
print("my_log_name: ", log_name)
logger.add(log_name, format = "{time:YYYY-MM-DD-HH:mm:ss} | {level} | {message}", enqueue = True,
backtrace = False)
我是在reportServer新创建了myView.py文件
文件内容如下:
from django.http import HttpResponse, JsonResponse
import os
import time
from reportServer.common.my_logger import logger
# 文件上传接口
def handle_upload_file(request):
if request.method == 'POST':
file_obj = request.FILES.get('file')
current_time = str(int(time.time()))
report_path = os.path.join(os.path.dirname(__file__), "report", current_time)
if not os.path.exists(report_path):
os.makedirs(report_path)
logger.info(
f"upload_request_info, request_path: {request.path}, report_path: {report_path}, file_name: {request.FILES['file'].name})")
try:
f = open(os.path.join(report_path, file_obj.name), 'wb')
for chunk in file_obj.chunks():
f.write(chunk)
f.close()
except IOError as e:
print("上传文件失败, error: ", e)
dic_response_error = {"msg": "upload error", "report_url": None, "error_msg":e}
return JsonResponse(dic_response_error, json_dumps_params = {'ensure_ascii': False})
visit_url = "http://127.0.0.1:8000" + "/report" + "/" + current_time + "/" + "report.html"
dic_response_success = {"msg": "upload success", "report_url": visit_url}
logger.info(f"handle_upload_file success: {dic_response_success}")
return JsonResponse(dic_response_success, json_dumps_params = {'ensure_ascii':False})
else:
dic_response_fail = {"msg": "upload Fail", "report_url": None}
logger.info(f"handle_upload_file fail: {dic_response_fail}")
return JsonResponse(dic_response_fail, json_dumps_params = {'ensure_ascii':False})
# 获取测试报告接口
def get_report(request, id):
report_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "report", str(id), "report.html")
print("report_path: ", os.path.join(os.path.abspath(os.path.dirname(__file__)), "report", str(id), "report.html"))
with open(report_path, "rb") as file:
response = HttpResponse(file.read())
request_path = request.path
logger.info(f"get_report success, request_path: {request_path}")
return response
# 启动服务
python manage.py runserver
外部调用上传接口示例, 如下图所示:
这样server就会将上传的html文件存储到report目录了!
胖虎觉得上面的功能并没有什么复杂的实现, 但是可以「解决实际问题」, 而且「非常实用」!
目前我是根据实际工作需要, 用到什么学什么, 遇到问题后, 尝试使用已掌握的知识储备解决问题, 这种思路去学习的, 希望对你有所启发~