【问题标题】:Accessing uploaded files from Django从 Django 访问上传的文件
【发布时间】:2018-11-18 21:43:39
【问题描述】:

我正在设计一个允许用户上传 .xls 文件的 Web 应用程序。上传时,应保存文件,转换为 .csv 文件,然后文件中包含的数据将通过 python 导入脚本导入。

所有用于导入和转换数据的功能都可以在 shell 中完全发挥作用,但是当通过 localhost 进行测试时,文件会转换为 .csv 并保存,但没有任何脚本在新文件上运行。

来自views.py:

    #for uploading data on the dashboard
    def file_upload(request):
        if request.method == 'POST':
            save_path = os.path.join(str(settings.MEDIA_ROOT), 'uploads', str(request.FILES['file']))
            try:
                validate_file_extension(request.FILES['file'])
                path = default_storage.save(save_path, request.FILES['file'])
                data = xls_to_csv(save_path, str(settings.MEDIA_ROOT))
                create_athlete(data, filename)
                create_phase(data)
                create_health_report(data)
                create_workout_report(data)
            except:
                return redirect('polar:dashboard')
            return redirect('polar:dashboard')

来自 importscript.py

    def xls_to_csv(file_name, save_path):
        #Formats into pandas dataframe.
        formatted_dataframe = pd.read_excel(file_name, index_col=None)
        #Converts the formatted into a csv file and save it.
        file_name = file_name.replace('.xls', '.csv')
        new_file = formatted_dataframe.to_csv(file_name))
        module_dir = os.path.dirname(settings.BASE_DIR)
        file_path = os.path.join(module_dir, 'uploads', file_name)
        sample_data = open(file_name, 'r')
        unfiltered_data = sample_data.readlines()
        data = unfiltered_data[1:]
        return data

好像 Django 正在阻止打开和读取新创建的 .csv 文件。任何解决此问题的提示将不胜感激!

【问题讨论】:

  • 你当前的代码是什么?

标签: python django csv web file-upload


【解决方案1】:

如果在 Linux 或 Mac 环境下工作,请务必授予上传目录读写权限。 或者,如果那不是问题,那么您在处理 xls 到 CSV 文件时似乎遇到了问题,请参阅这个

import xlrd
import unicodecsv

def xls2csv (xls_filename, csv_filename):
    # Converts an Excel file to a CSV file.
    # If the excel file has multiple worksheets, only the first 
    #worksheet is converted.
    # Uses unicodecsv, so it will handle Unicode characters.
    # Uses a recent version of xlrd, so it should handle old .xls and 
   # new 
   #.xlsx equally well.

   wb = xlrd.open_workbook(xls_filename)
   sh = wb.sheet_by_index(0)

   fh = open(csv_filename,"wb")
   csv_out = unicodecsv.writer(fh, encoding='utf-8')

   for row_number in xrange (sh.nrows):
       csv_out.writerow(sh.row_values(row_number))

   fh.close()

取自here

【讨论】:

  • 不幸的是,我已经尝试过,我的两个团队成员也在他们自己的计算机上尝试过。这似乎是 Django 方面的一个问题。
  • 工作是什么意思?我们正在为我们大学的体育部门开发一款应用程序,因此数据非常敏感,因为它与学生运动员及其私人信息有关。
  • 我的意思是我看到你已经添加的示例代码。让我研究一下你的问题,看看我能不能帮忙?
  • 尝试在您的 html 表单标签中添加 enctype="multipart/form-data"
  • 那已经在表格中了。在上传方面一切正常,但是在将文件输入 create_* 函数之前尝试打开文件时,问题似乎出现在 xls_to_csv 函数中。
猜你喜欢
  • 2018-04-18
  • 1970-01-01
  • 2013-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 2017-12-01
  • 2017-08-30
相关资源
最近更新 更多