python django在服务器

时间:2016-09-17 13:11:55

标签: python django

我想创建一个网站应用程序来运行位于服务器中的bash脚本。基本上我想要这个网站:

  • 上传文件
  • 选择一些参数
  • 运行输入文件和参数
  • 的bash脚本
  • 下载结果

我知道你可以用php,javascript做到这一点......但我从来没有用这些语言编程。但是我可以在python中编程。为了类似的目的,我在python中使用了pyQT库。

这可以用django完成吗?或者我应该开始学习php& JavaScript的? 我在Django找不到任何关于这个特定任务的教程。

1 个答案:

答案 0 :(得分:2)

这可以使用Django框架在Python中完成。

首先创建一个包含FileField的表单和其他参数的字段:

from django import forms

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

在您的视图中加入UploadFileForm并调用您的函数来处理上传的文件:

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})

创建处理上传文件的函数并调用bash脚本:

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

查看https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/以获取有关如何在Django中上传句柄文件的更多示例和说明。

相关问题