【问题标题】:Read from uploaded XLSX file in Python CGI script using Pandas使用 Pandas 在 Python CGI 脚本中读取上传的 XLSX 文件
【发布时间】:2020-12-14 22:55:24
【问题描述】:

我正在创建一个工具

  1. 生成一个新的 XLSX 文件供用户下载
  2. 用户可以上传他们拥有的 XLSX 文件,我将读取该文件的内容,并使用它们生成一个新文件供用户下载。

我想利用 Pandas 将 XLSX 文件读入数据帧,这样我就可以轻松使用它。但是,我无法让它工作。你能帮帮我吗?

从 CGI 文件中提取的示例:

import pandas as pd
import cgi
from mako.template import Template
from mako.lookup import TemplateLookup
import http.cookies as Cookie
import os
import tempfile
import shutil
import sys

cookie = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE"))

method = os.environ.get("REQUEST_METHOD", "GET")

templates = TemplateLookup(directories = ['templates'], output_encoding='utf-8')

if method == "GET": # This is for getting the page
    
    template = templates.get_template("my.html")
    sys.stdout.flush()
    sys.stdout.buffer.write(b"Content-Type: text/html\n\n")
    sys.stdout.buffer.write(
        template.render())

if method == "POST":

    form = cgi.FieldStorage()
    print("Content-Type: application/vnd.ms-excel")
    print("Content-Disposition: attachment; filename=NewFile.xlsx\n")
    
    output_path = "/tmp/" + next(tempfile._get_candidate_names()) + '.xlsx'
    
    data = *some pandas dataframe previously created*

    if "editfile" in form:
        myfilename = form['myfile'].filename
        with open(myfilename, 'wb') as f:
            f.write(form['myfile'].file.read())                
        data = pd.read_excel(myfilename)

    data.to_excel(output_path)

    with open(path, "rb") as f:
        sys.stdout.flush()
        shutil.copyfileobj(f, sys.stdout.buffer)

从 HTML 文件中提取的示例:

<p>Press the button below to generate a new version of the xlsx file</p> 
<form method=post>
<p><input type=submit value='Generate new version of file' name='newfile'>
<div class="wrapper">
</div>
</form>
<br>
<p>Or upload a file.</p>
<p>In this case, a new file will be created using the contents of this file.</p>
<form method="post" enctype="multipart/form-data">
    <input id="fileupload" name="myfile" type="file" />
    <input value="Upload and create new file" name='editfile' type="submit" />
</form>

这在没有if "editfile" in form: 位的情况下有效,所以当我尝试访问用户上传的文件时,我知道出了点问题。

问题是在创建文件时,创建的文件的文件大小为 0 KB,无法在 Excel 中打开。至关重要的是,在我写出来的位置找不到用户上传的文件。

【问题讨论】:

  • 对于您更新的问题,当您说出了点问题时,您能否描述实际发生的情况并粘贴您遇到的任何错误。是内部服务器错误吗?如果是这样,最好检查日志,例如如果你使用 apache2,它会是这样的:tail -20 /var/log/apache2/error.log.
  • 感谢@costaparas,我在问题的末尾添加了几句话来澄清。
  • 运行此程序时,错误日志中不会添加任何内容。但是,我在访问日志中收到 408 消息 - 我认为是超时。
  • 我无法用当前代码完全重现这一点。这正是你正在运行的吗?您可能只需要切换到 XLS 格式,因为根据您的版本可能不支持 XLSX。查看详情here
  • 我在脚本开头启用了'cgitb'模块import cgitbcgitb.enable。现在,XLSX 文件输出的文件大小为 23 KB。当我在文本编辑器中打开它时,我可以看到一个错误日志,其中包含来自 Python 的错误描述 - 如果您正在运行 .py 文件,您会看到。这清楚地表明该错误与我可以修复的不相关的事情有关。我很高兴接受您解决此特定问题的答案。感谢您的帮助@costaparas。

标签: python pandas cgi


【解决方案1】:

您已将 myfilename 传递给 pandas;但是该文件在服务器上尚不存在。在使用之前,您必须先将文件保存在本地某处。

下面会将文件下载到当前目录(与 CGI 脚本相同的目录)。当然,根据您的设置,欢迎您将其保存到更合适的目录中。

form = cgi.FieldStorage()
myfilename = form['myfile'].filename
with open(myfilename, 'wb') as f:  # Save the file locally
    f.write(form['myfile'].file.read())
data = pd.read_excel(myfilename)

【讨论】:

  • 感谢您的解释。由于某种原因,这对我不起作用。运行此文件后,我无法在与 CGI 脚本相同的目录中看到该文件。我会扩展我的问题。也许我错过了原始帖子中的相关内容。
猜你喜欢
  • 2012-10-27
  • 1970-01-01
  • 2018-11-25
  • 2016-12-13
  • 2013-05-29
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多