Download file from google drive using button in html file - python

I have one file stored in google drive which I download using:
url = 'https://docs.google.com/spreadsheets/d/ID/edit?usp=sharing'
output = 'file.xlsx'
gdown.download(url, output, quiet=False)
My goal is to make that file downloadable in a html file through a button using Google Drive as a backend. Is there any way to do that?
Summarizing:
Some user open an html file where there's a button to download some file placed in my drive.
the flask template I am thinking to use looks like:
from flask import Flask, Response
app = Flask(__name__)
#app.route("/")
def hello():
return '''
<html><body>
Hello. Click me.
</body></html>
'''
#app.route("/getPlotCSV")
def getPlotCSV():
# with open("outputs/Adjacency.csv") as fp:
# csv = fp.read()
excel = '1,2,3\n4,5,6\n'
return Response(
excel,
mimetype="xlsx",
headers={"Content-disposition":
"attachment; filename=file.xlsx"})
EDIT:
I mapped my html button with
"""<form action={url}> <input type=submit value=Go to Google/></form>"""
but it takes me directly to the spreadsheet in google sheets. How do I assign an action to that button so that the file is downloaded locally to the user?

Related

How to read a URL from a text file in python and return its content in a JSON format?

I have a txt file containing URL. I want to read that text file and if it contains the URL read that URL and returns its content as a JSO, else return the contents of the text file if something else. My codes represent a FLASK application and I want to represent if as if elif else.
However, when I run the application it only shows me the URL itself not the contents of that URL.
However, when I run the application and click on the provided address, it shows me "true" and then opens a new tab and shows me connection error. I expect, when I click on the link, it shows me the json content of the URL.
Could you please help me to fix it?
from flask import Flask, jsonify
import json,re, requests
import webbrowser
app = Flask(__name__)
#app.route('/', methods = ['GET','POST'])
def test_function():
with open('test1.txt', encoding='utf-8', errors='ignore') as j:
contents = j.read()
#for line in contents:
if re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', contents):
for url in contents:
s = webbrowser.open_new_tab(url)
return jsonify(s)
else:
return jsonify(contents)
if __name__ == '__main__':
app.run(debug=True)

Read or save a PDF file uploaded to Flask

I'm uploading multiple files to flask using a form, I'm getting the file objects in the flask backend without a problem but the issue is I want to read the PDF files to extract text from them. I can't do it on the file objects I received from the form, another method I thought of was saving the file in the local storage then read them again when I did that using file.save(path, filename) it created an empty text file with the name - filename.pdf
app=Flask(__name__)
#app.route('/')
def index():
return '''
<form method='POST' action='/saveData'>
<input type='file' name='testReport'>
<input type='submit'>
</form>
'''
#app.route('/saveData', methods=['POST'])
def saveData():
if 'testReport' in request.files:
testReport= request.files['testReport']
#This isn't working, a text file is saved with the same name ,ending in pdf
testReport.save(os.path.join(app.config['UPLOAD_FOLDER'], testReport.filename))
return f'<h1>File saved {testReport.filename}</h1>'
else:
return 'Not done'
How do we operate on PDF files after uploading them to flask ?
How do we operate on PDF files after uploading them to flask ?
You should treat them just like normal PDF files - if they were uploaded via Flask application or gathered using other method is irrelevant here. As you
want to read the PDF files to extract text from them.
you should use PDF text-extraction tool, for example pdfminer.six, as this is external module you need to install it first: pip install pdfminer.six
You can directly follow the flask own way as mentioned [here]
This easily works with pdfs. Just don't forget to include your extension in ALLOWED_EXTENSIONS

My function containing send_file() does not seem to update

I am using a Flask application to update some PDF files, convert them to an Excel file and send this file back to the user. I am using an instance folder to store the pdf and the excel files.
But when the user press the button "Download" in order to download the generated Excel file, an old file is downloaded (from an older session).
Moreover, when I try to change my code, for example, I changed the name of this Excel file: I can see the new name in the instance folder, but when I download the file with the webapp, it is still the old name (and old file). I have no idea where the webapp is looking for this old file...
MEDIA_FOLDER = '/media/htmlfi/'
app = Flask(__name__)
app.config.from_object(Config)
INSTANCE_FOLDER = app.instance_path
app.config['UPLOAD_FOLDER'] = INSTANCE_FOLDER+MEDIA_FOLDER
#app.route('/file/')
def send():
folder = app.config['UPLOAD_FOLDER']
try:
return send_file(folder+ "file.xlsx", as_attachment=True)
finally:
os.remove(folder+ "file.xlsx")
<a href="{{ url_for('send') }}" ><button class='btn btn-default'>DOWNLOAD</button></a>
I am really new to webapp in general, thank you for your help :)
send_file takes a cache_timeout parameter which is the number of seconds you want to cache the download. By default is 12 hours.
return send_file(
file.file_path(),
as_attachment=True,
cache_timeout=app.config['FILE_DOWNLOAD_CACHE_TIMEOUT'],
attachment_filename=file.file_name
)
http://flask.pocoo.org/docs/1.0/api/

Download file from root directory using flask

I am generating a xlsx file which I would like to download once it is created. The file is created using a module called 'xlsxwriter'. It saves the file in my root directory, however I cant figure out how to access it via flask, so that it starts a download.
This is how I create the file:
workbook = xlsxwriter.Workbook('images.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write(..someData..)
It saves the file in my root directory.
Now I am trying to access it in order to download it via flask:
app = Flask(__name__, static_url_path='')
#app.route('/download')
def download():
# do some stuff
return Response(
app.send_static_file('images.xlsx'),
mimetype="xlsx",
headers={"Content-disposition":
"attachment; filename=images.xlsx"})
However, I get a 404 Error. Is using send_static_file the correct way to go here?
I found a solution using 'send_file' instead. Providing the path to my file like so:
from flask import send_file
return send_file(pathToMyFile, as_attachment=True)

How to download a file from Flask and render template afterwards?

In Flask I want the user to be able to download a file from a S3 bucket using Boto. Of course if Flask downloads something from S3 it stores the file on the server. However I want the the file to be downloaded to the users machine if they click a download button. Is that possible? My idea was the following. When the download button gets clicked Flask fetches the file from S3 and stores it on the server afterwards the users machine downloads the file. Afterwards the file on the server gets deleted. Please tell me if there is a better way. If I do it like this it works. Unfortunately I need to render my dashboard again after the file was downloaded so I can't return the file.
Flask:
#app.route('/download')
#login_required
def dowloadfile():
try:
#Boto3 downloading the file file.csv here
return send_file('file.csv', attachment_filename='file.csv')
except Exception as ermsg:
print(ermsg)
return render_template('dashboard.html', name=current_user.username, ermsg=ermsg)
HTML:
<button class="buttonstyle" onclick="showImage();">Download</button>
The problem is that when the download button is clicked a full screen image is shown which is my loading screen. This loading screen disappears when the function is done and a new html is rendered. With the code above the loading screen appears and stays forever even when the file is aready downloaded to the users machine. How could you fix that?

Categories