1

Currently, I have a static JS file which is returned to user on a specific api request. The code which handles this is as follow

@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('js', path)

However, What i want to do is modify the current JS file (add some user specific modifications) and then return it to the user. Being a Java developer, I would have first read the file, made the in-memory modification and write those bytes to response object.

However, while trying to google send_file and send_from_directory i couldn't find a way where i can provide content of the file?

How should i implement this in flask?

Em Ae
  • 8,167
  • 27
  • 95
  • 162

1 Answers1

0

you can use StringIO.

@app.route('/js/<path:path>')
def send_js(path):
    path = secure_filename(path)
    with open(os.path.join("js", path), "rb") as fd:
        data = fd.read()
    #do stuff with data
    return send_file(StringIO(data), attachment_filename=path)

StringIO create a file-like object from a string

The imports are the follows:

from werkzeug.utils import secure_filename
try:
    from StringIO import StringIO
except ImportError:
from io import StringIO