I need code to create a one-time download link for file uploaded using Flask. This link should be sent as email to the client. I have been able to create the dynamic link as per this solution:Link generator using django or any python module Modified part of the code(for flask):
def genUrl(filepath, fname):
# create a onetime salt for randomness
salt = ''.join(['{0}'.format(random.randrange(10) for i in range(10))])
key = hashlib.md5('{0}{1}'.format(salt, filepath)).hexdigest()
s = select([msettings.c.DL_URL])
rs = conn.execute(s).fetchone()
newpath = os.path.join(rs[msettings.c.DL_URL], key)
shutil.copy2(filepath, newpath)
ins = my_dlink.insert().values(key=key,
download_date=datetime.datetime.utcnow(),
orgpath=filepath,
newpath=newpath
)
rs1 = conn.execute(ins)
print rs1.inserted_primary_key[0], 'inserted_primary_key'
rs1.url = "{0}/{1}/{2}".format(
rs[msettings.c.DL_URL], key, os.path.basename(fname))
return rs1.url
@app.route('/archival/api/v1.0/archival_docs/<int:arc_file_id>/url',
methods=['POST'])
def generate_one_time_download_url_for_file(arc_file_id):
path = ''
s = select([archival_docs]).where(archival_docs.c.id == arc_file_id)
rs = conn.execute(s).fetchone()
if rs:
path = os.path.join(("%s/%s" %
(rs[archival_docs.c.path_map],
rs[archival_docs.c.stored_name].encode('utf-8'))))
new_link = genUrl(path, rs[archival_docs.c.stored_name])
# Use BytesIO instead of StringIO here.
buffer = BytesIO()
buffer.seek(0)
content_type = mimetypes.guess_type(path)[0]
print content_type, 'content_type'
return send_file(buffer, as_attachment=True,
attachment_filename=rs[archival_docs.c.stored_name],
mimetype='text/plain')#content_type)
# response = make_response(send_file(path))
# response.headers["Content-Disposition"] = \
# "attachment; " \
# "filename={ascii_filename};" \
# "filename*=UTF-8''{utf_filename}".format(
# ascii_filename=rs[archival_docs.c.stored_name],
# utf_filename=(os.path.basename(path))
# )
# print response
#return response
How to send this as 1 time download link to client? After client downloads, this link should get disabled.i.e response should indicate that the file was downloaded(cron job should take care of it). What should be the exact code changes?