flask send_file&send_from_directory

尽量不要使用send_file(),而使用send_from_directory,后者限定了文件夹,更安全

flask.send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=None, conditional=False, last_modified=None)
参数说明
filename_or_fp需要发送的文件
mimetypethe mimetype of the file if provided. If a file path is given, auto detection happens as fallback, otherwise an error will be raised.
as_attachmentet to True if you want to send this file with a Content-Disposition: attachment header.
attachment_filenamethe filename for the attachment if it differs from the file’s filename.
add_etagsset to False to disable attaching of etags.
conditionalset to True to enable conditional responses.
cache_timeoutthe timeout in seconds for the headers.
last_modified
flask.send_from_directory(directory, filename, **options)
参数描述
directorythe directory where all the files are stored.
filenamethe filename relative to that directory to download.
optionsoptional keyword arguments that are directly forwarded to send_file().

参考文献:
http://flask.pocoo.org/docs/0.12/api/#flask.send_from_directory
https://stackoverflow.com/questions/38252955/flask-when-to-use-send-file-send-from-directory?r=SearchResults

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Flask 中,`send_from_directory` 和 `send_file` 都用于向客户端文件,但有一些区别。 send_from_directory` 函数用于从指定目录中发送文件。它提供了方便的方式来发送静态文件,如图像、CSS、JavaScript 等。以下是一个示例代码: ```python from flask import Flask, send_from_directory app = Flask(__name__) @app.route('/images/<path:filename>') def get_image(filename): # 从指定目录中发送文件 return send_from_directory('static/images', filename) if __name__ == '__main__': app.run() ``` 在上面的示例中,当请求 `/images/filename.jpg` 时,`get_image` 函数会从 `static/images` 目录中发送名为 `filename.jpg` 的文件。 `send_file` 函数用于发送任意类型的文件。它可以发送动态生成的文件(如通过 Pandas 导出的 XLSX 文件),或者从任意路径中发送文件。以下是一个示例代码: ```python from flask import Flask, send_file import pandas as pd app = Flask(__name__) @app.route('/api/export') def export_data(): # 生成文件或从文件路径中获取文件 # ... # 发送文件 return send_file('path/to/file.xlsx', as_attachment=True) if __name__ == '__main__': app.run() ``` 在上面的示例中,当请求 `/api/export` 时,`export_data` 函数会发送名为 `file.xlsx` 的文件。 总结来说,`send_from_directory` 适用于发送静态文件,而 `send_file` 则适用于发送各种类型的文件,包括动态生成的文件。根据你的需求选择合适的函数。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值