当我尝试在函数中执行django核心管理代码时,它不起作用

时间:2017-11-23 15:33:16

标签: python django web file-upload views

我需要将cvs数据上传到数据库,然后我编写了代码来完成它。但我需要触发它:每次用户上传文件 - python脚本更新数据库。 在我的代码中:我有call_command(' uploadDb')当我把它放在函数上传中时 - 它可以工作,但当我把它放在上传函数中时 - 它没有 问题是什么? 谢谢

from django.shortcuts import render
import os
from django.core.management import call_command



# Create your views here.
from django.http import HttpResponse

def index(request):
    return HttpResponse("<h1>Upload the file</h1>")

def home(request):
    return render(request, 'index.htm', {'what':'File Upload'})

def upload(request):
    if request.method == 'POST':
        handle_uploaded_file(request.FILES['file'], str(request.FILES['file']))
        return HttpResponse("Successful")

    return HttpResponse("Failed")

def handle_uploaded_file(file, filename):
    if not os.path.exists('upload/'):
        os.mkdir('upload/')

    with open('upload/' + filename, 'wb+') as destination:

        for chunk in file.chunks():
            destination.write(chunk)


call_command('uploadDb')  

/ management / commands

中的uploadDb函数
from django.core.management.base import BaseCommand, CommandError
from data.models import MyCsvModel
from data.models import MyCsvModel2
from data.models import MyCsvModel3
from data.models import MyCsvModel4

class Command(BaseCommand):
    help = 'Command to do import to database'

    def handle(self, *args, **options):
        try:
            my_csv_list = MyCsvModel.import_data(data = open("C:\\Users\\kz938vk\\Desktop\\client.csv"))
            my_csv_list2 = MyCsvModel2.import_data(data = open("C:\\Users\\kz938vk\\Desktop\\product.csv"))
            my_csv_list3 = MyCsvModel3.import_data(data = open("C:\\Users\\kz938vk\\Desktop\\payment.csv"))
            my_csv_list4 = MyCsvModel4.import_data(data = open("C:\\Users\\kz938vk\\Desktop\\messages.csv"))
            print("I am here")
            pass
        except Exception as e:
            CommandError(repr(e))

0 个答案:

没有答案