Home > Enterprise >  Read uploaded fasta file in django using Bio library
Read uploaded fasta file in django using Bio library

Time:04-18

in index.html I used <input type="file" name="upload_file">

in 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

The method sequence_extract_fasta(fasta_files) work with python. But not on the Django framework. If I can find the temporary location of the uploaded file then using the path, I may be able to call the method. Is there any efficient way to solve this? your help is highly appreciated. Thank you for your time.

CodePudding user response:

I found a one way of doing this.

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
  • Related