[Answered ]-Python django run bash script in server

2👍

This can be done in Python using the Django framework.

First create a form including a FileField and the fields for the other parameters:

from django import forms

class UploadFileForm(forms.Form):
    my_parameter = forms.CharField(max_length=50)
    file = forms.FileField()

Include the UploadFileForm in your view and call your function for handling the uploaded file:

from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            my_parameter = form.cleaned_data['my_parameter']
            # Handle the uploaded file
            results = handle_uploaded_file(request.FILES['file'], title)
            # Clear the form and parse the results
            form = UploadFileForm()
            return render(request, 'upload.html', {'form': form, 'results': results})
    else:
        form = UploadFileForm()
    return render(request, 'upload.html', {'form': form})

Create the function to handle the uploaded file and call your bash script:

import subprocess
import os

def handle_uploaded_file(f, my_parameter):
    file_path = os.path.join('/path/to/destination/', f.name)
    # Save the file 
    with open(file_path, 'wb+') as destination:
        for chunk in f.chunks():
             destination.write(chunk)
    # Call your bash script with the
    output = subprocess.check_output(['./my_script.sh',str(file_path),str(my_parameter)], shell=True)
    return output

Check out https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/ for more examples and instructions on how the handle file uploads in Django.

Leave a comment