Django-缓存InMemoryUploadedFile(request.FILES ['file'])

时间:2019-03-27 09:49:28

标签: django python-3.x caching django-forms

有没有一种方法可以缓存request.FILES ['file']以在第二个请求中使用它。

我正在尝试确认文件上传。因此,我有两种形式。一种将文件上传到服务器,另一种确认上传。但是,在第二种形式中,request.FILES ['file']当然是空的,因为它是一个新请求。如何缓存文件以在第二个请求中使用它。

这是我的views.py

def file_upload(request):
    save = False
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        # In form2 the request.FILES should contain the file I selected in the UploadFileForm
        form2 = ConfirmationForm(request.POST, request.FILES)
        if not form2:
            save = True
        elif form.is_valid():
            save = False
        print("request.POST: ", request.POST)
        print("request.FILES: ", request.FILES) # empty
        print("save: ", save) #false
        print("form: ", form)
        print("form2: ", form2) # empty
        if not request.FILES:
            print("empty")
        else:
            print("not empty")
        updated_obj = 0
        created_obj = 0
        duplicate_obj = 0
        count = 0
        # Prüfen ob CSV Datei valide ist (keine doppelten Datensätze)
        if form.is_valid():
            csv_file = request.FILES['file']
            print("csv_file: ", csv_file)
            rs1 = list()
            rs2 = list()
            d_list1 = list()
            d_list2 = list()
            file = csv_file.read().decode('utf-8').splitlines()
            reader_orig = csv.reader(file)
            for row in reader_orig:
                try:
                    row_set1 = [row[0], row[1], row[2], row[3], row[4]]
                    row_set2 = [row[5], row[6]]
                    if row_set1 not in rs1:
                        rs1.append(row_set1)
                    else:
                        d_list1.append(row_set1)
                    if row_set2 not in rs2:
                        rs2.append(row_set2)
                    else:
                        d_list2.append(row_set2)
                except IndexError:
                    break
            if len(d_list1) and len(d_list2):
                messages.error(request, "In der CSV Datei sind folgende Datensätze mehrfach vorhanden")
                messages.error(request, "Dosen: %s " % d_list1)
                messages.error(request, "Ports: %s " % d_list2)
                return redirect('appp:index')
            elif len(d_list1) and not len(d_list2):
                messages.error(request, "In der ausgewählten CSV Datei sind folgende Dosen mehrfach vorhanden")
                messages.error(request, "%s " % d_list1)
                return redirect('appp:index')
            elif not len(d_list1) and len(d_list2):
                messages.error(request, "In der ausgewählten CSV Datei sind folgende Ports mehrfach vorhanden")
                messages.error(request, "%s " % d_list2)
                return redirect('appp:index')
            # Wenn CSV Datei valide ist --> Datei hochladen
            csv_file = request.FILES['file']
            # print("csv: ", csv_file.name)
            #print("csv_file: ", csv_file)
            #row_count = csv_file.
            # print("length: ", row_count)
            # csv_file.close()
            #print("csv.seek: ", csv_file.seek(0))
            #print("current_pos: ", csv_file.tell())
            csv_file.seek(0)
            decoded_file = csv_file.read().decode('utf-8').splitlines()
            row_count = len(decoded_file)
            #print("d_file: ", decoded_file)
            reader = csv.reader(decoded_file)
            updated_list = list()
            created_list = list()
            for row in reader:
                count += 1
                try:
                    datet = datetime.now().date()
                    datum = datet.strftime("%d.%m.%Y")
                    row[7] = datum
                    row[8] = str(request.user)
                    #d = [row[0], row[1], row[2], row[3], row[4]]
                    dataset1 = CSV5.objects.filter(gebaeudebereich=row[0],
                                                     gebaeudenummer=row[1], ebene=row[2],
                                                     raum=row[3], dose=row[4])#.values_list("gebaeudebereich", "gebaeudenummer",
                                                     #                                       "ebene", "raum", "dose")
                    dataset2 = CSV5.objects.filter(switch_ip=row[5], switch_port=row[6])#.values_list("switch_ip", "switch_port")
                    ds1 = CSV5.objects.values_list("gebaeudebereich", "gebaeudenummer", "ebene",
                                                                      "raum", "dose")
                    ds2 = CSV5.objects.values_list("switch_ip", "switch_port")
                    #print("ds1: ", ds1)
                    print("count: ", count)
                    print("dataset1: ", dataset1)
                    print("dataset2: ", dataset2)
                    print("dataset1: ", dataset1.exists())
                    print("dataset2: ", dataset2.exists())
                    print("save: ", save)

                    if (dataset1.exists() and not dataset2.exists()):
                        #instance = get_object_or_404(CSV5, id=count)
                        print("Fall 1")
                        ins = CSV5.objects.filter(gebaeudebereich=row[0],
                                                     gebaeudenummer=row[1], ebene=row[2],
                                                     raum=row[3], dose=row[4])
                        #liste.append(ins.values_list())
                        #print("liste: ", liste)
                        print ("instance: ", ins)
                        if save == True:
                            ins.update(switch_ip=row[5], switch_port=row[6], datum = row[7], akteur = row[8])
                        else:
                            updated_list.append(ins)
                        updated_obj += 1
                    elif not dataset1.exists() and dataset2.exists():
                        print("Fall 2")
                        ins = CSV5.objects.filter(switch_ip=row[5], switch_port=row[6])
                        print("instance: ", ins)
                        if save == True:
                            ins.update(gebaeudebereich = row[0], gebaeudenummer = row[1], ebene = row[2], raum = row[3],
                                       dose = row[4], datum = row[7], akteur = row[8])
                        else:
                            updated_list.append(ins.values_list())
                            print("dat2: ", dataset2)
                        updated_obj += 1
                    elif (dataset1.exists() and dataset2.exists()):
                        print("Fall 3")
                        #liste.append(dataset1)
                        #print("liste: ", liste)
                        duplicate_obj += 1
                    elif not (dataset1.exists() and dataset2.exists()):
                        print("Fall 4")
                        if save == True:
                            ins = CSV5.objects.get_or_create(id=CSV5.objects.count() + 1, gebaeudebereich=row[0],
                                                         gebaeudenummer=row[1], ebene=row[2],
                                                         raum=row[3], dose=row[4], switch_ip=row[5], switch_port=row[6],
                                                         datum=row[7], akteur=row[8])
                            created_list.append(ins)
                            ins.save()
                        created_obj += 1
                except IndexError:
                    print("IndexError")
                    break
                except IntegrityError:
                    duplicate_obj += 1
                    print("IntegrityError")

            messages.success(request, "Objects created: %s" % created_obj)
            messages.success(request, "Objects updated: %s " % updated_obj)
            messages.success(request, "Duplicate Objects: %s " % duplicate_obj)

            # After the validation of the file this file is rendered
            form2 = ConfirmationForm()
            return render(request, "appp/confirmation.html", {'form' : form2})



    form = UploadFileForm()
    return render(
        request, "appp/file_upload.html", {"form": form}
    )

因此,form2中的request.FILES不应为空,而应包含UploadFileForm的文件。如何缓存文件。任何帮助将不胜感激。

0 个答案:

没有答案