我正在研究一个Django项目(Django 1.10,Python 3.4.3),其中我试图上传python子进程中的文件。我需要上传文件,并在上传文件时计算一些总和,并且我们希望系统在这样做时仍然可用,所以我们认为将这些任务放在子进程中是可行的。在python子进程中上传文件
现在,我正在努力让文件上传。
第一次尝试:
应用程序/视图/ UploadView.py
class NewUploadView(TemplateView):
template_name = "../templates/simulation/upload.html"
@transaction.atomic
def post(self, request):
if request.method == 'POST':
if not request.FILES['input_file']:
return HttpResponseBadRequest("No 'input_file' is provided")
else:
sim_name = self.request.POST.get(u"name", None)
p = Popen(["/.virtualenvs/env/bin/python3.4", "manage.py",
"load_simulation", str(request.FILES['input_file'],
str(sim_name)])
p.communicate()
# Redirect to appropriate page
HttpResponseRedirect(reverse('home.display_simulations'))`
应用程序/管理/命令/ load_simulation.py
import csv
import os
from django.conf import settings
from django.core.management.base import BaseCommand
from website.apps.home.models import Simulation, Location, Data, SimulationModel
class Command(BaseCommand):
help = 'Upload csv data file and save objects in database'
def add_arguments(self, parser):
parser.add_argument("my_file", type=str)
parser.add_argument("simulation_name", type=str)
def handle(self, *args, **options):
"""
Upload data file
:param args:
:param options:
:return:
"""
my_file = options["my_file"]
simulation_name = options["simulation_name"]
# Save the simulation object, with the data_file
simulation = Simulation.objects.create(name=simulation_name, data_file=my_file)
simulation.save()
filename = os.path.join(settings.MEDIA_ROOT, "simulation_files", simulation.getfilename())
file_obj = open(filename, 'r')
dictreader = csv.DictReader(file_obj)
line = None
for line in dictreader:
location = Location.objects.filter(
department_code=line['department_code'],
municipality_code=line['municipality_code'],
).first()
if not location:
location = Location.objects.create(
department=line['department'],
department_code=line['department_code'],
municipality=line['municipality'],
municipality_code=line['municipality_code'],
)
Data.objects.create(
location=location,
date=line['date'].split(" ")[0], # Assuming date is in "YYYY-MM-DD HH:MM:SS" format
simulation=simulation,
value_low=line['value_low'],
value_mid=line['value_mid'],
value_high=line['value_high'],
)
simulation.is_uploaded = True
simulation.save()
print("DONE WITH LOAD SIMULATION!")
我有设置,以便该文件将被保存在/media/simulation_files
目录。但该文件不会保存到服务器,这意味着它在load_simulation.py
文件中失败,因为该文件不在该位置,因此该文件尝试打开该文件。
然后我意识到,我传递一个TemporaryFile作为一个字符串,所以也许这是问题的一部分。
第二次尝试
我改变了部分UploadView.py把该文件作为标准输入英寸
p = Popen(["/.virtualenvs/env/bin/python3.4", "manage.py",
"load_simulation", str(sim_name), is_historical],
stdin=PIPE)
p.communicate(input=request.FILES['output_file'])
和修改load_simulation.py开始如下:
class Command(BaseCommand):
help = 'Upload csv data file and save objects in database'
def add_arguments(self, parser):
parser.add_argument("my_file", type=str)
parser.add_argument("simulation_name", type=str)
def handle(self, *args, **options):
"""
Upload data file
:param args:
:param options:
:return:
"""
simulation_name = options["simulation_name"]
my_file = input()
# Save the simulation object, with the data_file
simulation = Simulation.objects.create(name=simulation_name, data_file=my_file.name)
simulation.save()
filename = os.path.join(settings.MEDIA_ROOT, "simulation_files", simulation.getfilename())
file_obj = open(filename, 'r')
dictreader = csv.DictReader(file_obj)
... same as before ...
这是我从下面的问题/答案了: Python3 subprocess communicate example
这给了我一个错误
TypeError: 'InMemoryUploadedFile' does not support the buffer interface
我是新来的子流程的工作,并在接下来尝试尝试。我意识到p.communicate()
可能并不是这里的最佳选择,但我希望这可以使基本功能失效,然后我可以改进它。建议和意见是非常感谢!