python - 当我制作猎鹰 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)
解决方案
根据我的经验,使用 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')
推荐阅读
- python - 如何让 Python 程序加载和使用几个不同的同名包?
- java - 回文程序没有按预期工作
- gradle - 如何查看可以为 gragle.properties 设置的所有选项
- python - 我创建了一个不和谐级别的机器人,但它得到错误说未定义
- python-3.x - Pandas:如何根据列值将大 df 分成多个 df
- android - 颤振错误:参数类型“列表”
?不能分配给参数类型“列表” ' - javascript - 如何使 Node JS 中的函数只运行一次
- c# - UnityWebRequest POST 不发送正文
- javascript - d3 x.invert 从 d3.pointer 返回无效日期。d3 v6
- sql-server - 如何使用 Azure 密钥保管库将 SQL Server 的连接字符串存储为 Azure 数据工厂中的机密