From b06f987e55791c2c1b8307581790b62e6b397800 Mon Sep 17 00:00:00 2001 From: Revant Nandgaonkar Date: Mon, 19 Jun 2017 09:11:31 +0530 Subject: [PATCH] Download files using REST API and OAuth 2 Token (#3499) * Download files using REST API and OAuth 2 Token * Check permissions before file download via API * Solves Codacy issues https://www.codacy.com/app/netchampfaris/frappe/file/7377221800/issues/source?bid=4679759&fileBranchId=4768213#l364 --- frappe/utils/file_manager.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/frappe/utils/file_manager.py b/frappe/utils/file_manager.py index 4e011c5291..be2b1c4def 100644 --- a/frappe/utils/file_manager.py +++ b/frappe/utils/file_manager.py @@ -350,3 +350,22 @@ def get_file_name(fname, optional_suffix): partial, extn = f[0], "." + f[1] return '{partial}{suffix}{extn}'.format(partial=partial, extn=extn, suffix=optional_suffix) return fname + +@frappe.whitelist() +def download_file(file_url): + """ + Download file using token and REST API. Valid session or + token is required to download private files. + + Method : GET + Endpoint : frappe.utils.file_manager.download_file + URL Params : file_name = /path/to/file relative to site path + """ + file_doc = frappe.get_doc("File", {"file_url":file_url}) + file_doc.check_permission("read") + + with open(getattr(frappe.local, "site_path", None) + file_url, "rb") as fileobj: + filedata = fileobj.read() + frappe.local.response.filename = file_url[file_url.rfind("/")+1:] + frappe.local.response.filecontent = filedata + frappe.local.response.type = "download"