使用Bio库在django中读取上传的fasta文件

Read uploaded fasta file in django using Bio library

在 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