响应csv
主要处理
def get_Incident_view() -> HttpResponse:
status_list = [choices[0] for choices in RepairOrder.STATUS.choices if choices[0] != RepairOrder.STATUS.CHECKED_OUT]
# repair_order_part_queryset = []
# dict = {
# rop_r.repair_order : rop_r
# for rop_r in RepairOrderPart.objects.select_related("repair_order").order_by('-id').filter(status__in=status_list)
# }
# for repair_order in dict:
# primary_part = RepairOrder.objects.get(pk=repair_order.id).primary_part
# repair_order_part_queryset.append(primary_part)
repair_order_part_queryset = RepairOrderPart.objects.select_related("repair_order").order_by('-id').filter(status__in=status_list, parent_part__isnull=True)
csv_header = [
"Line Work Order No", "Work Nature Level 1", "Reported Date", "Location", "Incident Description",
"Failure Symptom", "Remark", "Incident Follow Up", "Delay (I)", "Delay (A)",
"CEWS Work order", "Stock code", "Equipment Description", "Serial Number", "Check In Date",
"Workgroup", "Test Result", "Follow up actions", "Check out date"
]
csv_fields = [
"line_work_order","Level_1", "reported_date", "location", "detail_description",
"failure_symptom","remark","incident_follow_up","delay_i","delay_a",
"work_order_no","stock_code","incident_description","serial_no","check_in",
"workgroup","test_result","follow_up_actions","last_check_out"
]
cvs_data_row_list= []
for repair_order_part in repair_order_part_queryset:
data = { field:" " for field in csv_fields}
if p := repair_order_part.part:
data["Level_1"] = p.lv1
if r_o := repair_order_part.repair_order:
data["line_work_order"] = r_o.line_work_order
if report_date := r_o.report_date:
data["reported_date"] = report_date
data["location"] = r_o.location
data["failure_symptom"] = r_o.failure_symptom + "\t"
data["remark"] = r_o.remark + "\t"
data["delay_i"] = r_o.delay_i + "\t"
data["delay_a"] = r_o.delay_a + "\t"
data["work_order_no"] = r_o.work_order_no + "\t"
if check_in := r_o.check_in:
check_in = timezone.localtime(check_in)
data["check_in"] = check_in.strftime("%Y/%m/%d %H:%M:%S") + "\t"
if check_out := r_o.check_out:
check_out = timezone.localtime(check_out)
data["last_check_out"] = check_out.strftime("%Y/%m/%d %H:%M:%S") + "\t"
data["workgroup"] = r_o.workgroup
if detail_queryset := r_o.repairorderrepairdetails_set:
data["test_result"] = detail_queryset.first().test_result
data["detail_description"] = "To be Comfirm"
data["serial_no"] = str(repair_order_part.serial_no) + "\t"
data["stock_code"] = str(repair_order_part.stock_code) + "\t"
data["incident_description"] = repair_order_part.detail_description
data["incident_follow_up"] = "To be Comfirm"
data["follow_up_actions"] = "To be Comfirm"
data_one_row = [data[filed] for filed in csv_fields]
cvs_data_row_list.append(data_one_row)
response = csv_response(csv_header, cvs_data_row_list, file_name="incident_view.csv")
return response
并且设置csv
def csv_response(csv_header: List[str], cvs_data_row_list: List[List], file_name: str) -> HttpResponse:
"""
csv响应
"""
csvfile = io.StringIO()
writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerow(csv_header)
writer.writerows(cvs_data_row_list)
csv_str = csvfile.getvalue().encode('gbk', errors='ignore')
response = HttpResponse(csv_str, content_type='text/csv')
response['Content-Disposition'] = f"attachment; filename={file_name}"
return response
上传csv时获取编码格式
@action(detail=False, methods=["post"], schema=AutoDocSchema())
def upload_Incident_view(self, request):
csvfile = request.FILES['file']
data = csvfile.read()
res = chardet.detect(data)
encoding = res["encoding"]
decoded_file = data.decode(encoding)
reader = csv.reader(decoded_file.splitlines())
try:
res = ReportService.upload_Incident_view(reader)
except ValueError as e:
return Response(status=200, data=str(e))
return Response(status=200, data={
"code": 1,
"data": {"update_count": res}
})
csv上传后读取里面的数据,有改动保存到数据库, 批量修改
def upload_Incident_view(reader):
"""用户上传csv, 修改数据库"""
csv_header = [
"Line Work Order No", "Work Nature Level 1", "Reported Date", "Location", "Incident Description",
"Failure Symptom", "Remark", "Incident Follow Up", "Delay (I)", "Delay (A)",
"CEWS Work order", "Stock code", "Equipment Description", "Serial Number", "Check In Date",
"Workgroup", "Test Result", "Follow up actions", "Check out date"
]
# update_fields = ["Incident Description","Failure Symptom","Remark", "Incident Follow Up", "Delay (I)", "Delay (A)", "CEWS Work order"]
# update fields
failure_symptom_index =csv_header.index("Failure Symptom")
remark_index = csv_header.index("Remark")
delay_i_index = csv_header.index("Delay (I)")
delay_a_index = csv_header.index("Delay (A)")
cews_work_order_index =csv_header.index("CEWS Work order")
incident_description_index = csv_header.index("Incident Description")
incident_follow_up_index = csv_header.index("Incident Follow Up")
follow_up_actions_index = csv_header.index("Follow up actions")
# query fields
check_out_date_index =csv_header.index("Check out date")
check_in_date_index =csv_header.index("Check In Date")
serial_no_index =csv_header.index("Serial Number")
stock_code_index =csv_header.index("Stock code")
if csv_header != next(reader):
raise ValueError("请检查表头是否正确")
r_o_p_update_list = []
row_count = 0
for row in reader:
row_count += 1
query = Q()
if (check_in := row[check_in_date_index]) != " ":
check_in = timezone.make_aware(datetime.strptime(check_in.replace("\t", ""), "%Y/%m/%d %H:%M:%S"), timezone.get_current_timezone())
query &= Q(repair_order__check_in__year=check_in.year,
repair_order__check_in__month=check_in.month,
repair_order__check_in__day=check_in.day,
repair_order__check_in__hour=check_in.hour,
repair_order__check_in__minute=check_in.minute,
repair_order__check_in__second=check_in.second)
else:
query &= Q(repair_order__check_in__isnull=True)
if (check_out := row[check_out_date_index]) != " ":
check_out = timezone.make_aware(datetime.strptime(check_out.replace("\t", ""), "%Y/%m/%d %H:%M:%S"), timezone.get_current_timezone())
query &= Q(repair_order__check_out__year=check_out.year,
repair_order__check_out__month=check_out.month,
repair_order__check_out__day=check_out.day,
repair_order__check_out__hour=check_out.hour,
repair_order__check_out__minute=check_out.minute,
repair_order__check_out__second=check_out.second)
else:
query &= Q(repair_order__check_out__isnull=True)
s_c = row[stock_code_index].replace("\t", "")
s_n = row[serial_no_index].replace("\t", "")
repair_order_part_queryset = RepairOrderPart.objects.filter(stock_code=s_c, serial_no=s_n, parent_part__isnull=True).filter(query)
if repair_order_part_queryset.exists():
r_o_p = repair_order_part_queryset.first()
if r_o := r_o_p.repair_order:
r_o.failure_symptom = row[failure_symptom_index].replace("\t", "")
r_o.remark = row[remark_index].replace("\t", "")
r_o.delay_i = row[delay_i_index].replace("\t", "")
r_o.delay_a = row[delay_a_index].replace("\t", "")
r_o.work_order_no = row[cews_work_order_index].replace("\t", "")
r_o_p_update_list.append(r_o)
else:
raise ValueError("请检查行数:{}, 请勿修改无关的数据".format(row_count))
chunk_size = 10
print(f"修改长度:{len(r_o_p_update_list)}, 上传数据长度: {row_count}")
update_count = 0
for i in range(0, len(r_o_p_update_list), chunk_size):
count = RepairOrder.objects.bulk_update(r_o_p_update_list[i:i+chunk_size],["failure_symptom", "remark", "delay_i", "delay_a", "work_order_no"])
update_count += count
if count != len(r_o_p_update_list[i:i+chunk_size]):
raise ValueError(f"区间{i}~{i+chunk_size}: 异常修改数量:{count}")
return update_count
最新版
from io import BytesIO
import codecs
class CsvView(View):
def get(self, request):
output = BytesIO()
# 使用 GBK 编码打开字节流对象并创建 CSV 写入器
writer = csv.writer(codecs.getwriter("gbk")(output))
# 获取数据并写入 CSV 文件
t = list(TestModels.objects.all().values_list())
writer.writerows(t)
# 创建响应对象,并将字节流对象的内容作为响应体
response = HttpResponse(content_type="text/csv")
response["Content-Disposition"] = 'attachment; filename="somefilename.csv"'
output.seek(0)
response.write(output.getvalue())
return response
def post(self, request):
file = request.FILES["file"]
content = file.read()
data = csv.reader(content.decode("gbk").splitlines())
for row in data:
TestModels.objects.filter(id=row[0]).update(username=row[1])
print(row)
return JsonResponse({"file": file.name})