Чтение загруженного файла fasta в django с помощью библиотеки Bio

в файле index.html я использовал <input type="file" name="upload_file">

в файле views.py

from Bio import SeqIO
def index(request):
    if request.method == "POST":
        try:
            text_file = request.FILES['upload_file']

            list_1, list_2 = sequence_extract_fasta(text_file)

            context = {'files': text_file}
            return render(request, 'new.html', context)

        except:
            text_file = ''

        context = {'files': text_file}

    return render(request, 'index.html')

def sequence_extract_fasta(fasta_files):
    # Defining empty list for the Fasta id and fasta sequence variables
    fasta_id = []
    fasta_seq = []


    # opening a given fasta file using the file path

    with open(fasta_files, 'r') as fasta_file:
        print("pass")
        # extracting multiple data in single fasta file using biopython
        for record in SeqIO.parse(fasta_file, 'fasta'):  # (file handle, file format)
        
            print(record.seq)
            # appending extracted fasta data to empty lists variables
            fasta_seq.append(record.seq)
            fasta_id.append(record.id)
        

    # returning fasta_id and fasta sequence to both call_compare_fasta and call_reference_fasta
    return fasta_id, fasta_seq

Метод sequence_extract_fasta(fasta_files) работает на python. Но не на фреймворке Django. Если я смогу найти временное местоположение загруженного файла, то, используя путь, я смогу вызвать метод. Есть ли какой-нибудь эффективный способ решить эту проблему? Ваша помощь будет высоко оценена. Спасибо за ваше время.

Я нашел один способ сделать это.

def sequence_extract_fasta(fasta_file):
# Defining empty list for the Fasta id and fasta sequence variables
    fasta_id = []
    fasta_seq = []
    # fasta_file = fasta_file.chunks()
    print(fasta_file)
    # opening given fasta file using the file path
    
    # crating a backup file with original uploaded file data
    with open('data/temp/name.bak', 'wb+') as destination:
        for chunk in fasta_file.chunks():
            destination.write(chunk)

    # opening created backup file and reading
    with open('data/temp/name.bak', 'r') as fasta_file:
        # extracting multiple data in single fasta file using biopython
        for record in SeqIO.parse(fasta_file, 'fasta'):  # (file handle, file format)
            
            fasta_seq.append(record.seq)
            fasta_id.append(record.id)

    # returning fasta_id and fasta sequence to both call_compare_fasta and call_reference_fasta
    return fasta_id, fasta_seq
Вернуться на верх