首页 > 解决方案 > 当我制作猎鹰 API 时,我的 excel 已损坏

问题描述

我正在尝试制作一个 Web API 来将 csv 保存到模板 excel 文件中。我制作了一个功能,当我执行它时它可以完美运行。但是一旦我从函数 (def on_get(self, req, resp): ) 调用它,文件就会损坏。我可以进行哪些更改以防止文件损坏?

服务器代码:

class Test:
def on_get(self, req, resp):
    ct.save_df_into_excel(df_template, file_location, list_of_code_columns, new_location)
    """Handles GET requests"""
    response = {
        'status': 'success'
    }
    resp.media = response

功能:

def save_df_into_excel(df_template, file_location, list_of_code_columns, new_location = None):
if new_location == None:
    new_location = file_location
if df_template.columns.nlevels > 1:
    df_template.columns = df_template.columns.droplevel()

df_new_template = df_template.reindex(columns=list_of_code_columns)
workbook = openpyxl.load_workbook(file_location)
writer = pd.ExcelWriter(file_location, engine='openpyxl')
writer.book = workbook
writer.sheets = dict((ws.title, ws) for ws in workbook.worksheets)
worksheet = workbook.active
df_new_template.to_excel(writer, sheet_name=worksheet.title,
                     header=None, startrow=2, index=False)
writer.book.save(new_location)

标签: pythonpython-3.xpandasopenpyxlfalcon

解决方案


根据我的经验,使用 falcon 处理传入文件的最佳方法是使用 falcon-multipart 中间件,您可以在此处获取它https://github.com/yohanboniface/falcon-multipart并像这样使用它:

from falcon_multipart.middleware import MultipartMiddleware
api = falcon.API(middleware=[MultipartMiddleware()])

然后在你的端点使用这样的东西:

class UploadHandler():
    def on_post(self, req, resp):
        iFile = req.get_param('sentFile')

推荐阅读