I have a python code which gives a download url of an image file from azure blob storage. If we copy paste this url in browser, it simply downloads the file. I have to create a download api which when called will simply download the file. Below is the code I have as of now:
from urllib.request import urlopen
from flask import Flask, jsonify
import uuid
from flask_cors import CORS
from datetime import datetime
from azure.storage.blob import generate_blob_sas, AccountSasPermissions
import datetime
from datetime import timedelta
app = Flask(__name__)
CORS(app)
uid_secret_key = str(uuid.uuid4())
app.secret_key = uid_secret_key
# Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app.wsgi_app
@app.route('/download')
def download():
account_name = "deeusblobstorage"
container_name = "rperodct"
blob_name = "face_1_7285.jpg"
account_key = "hMlIRXCjAomfDRfied8Y5FPwTVnWEkEDuVsw//CQtkiOdcFD/y5wUcxH9Ou7Ni+DtDQFwe23YbZ3Qia9gw=="
url = f"https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}"
sas_token = generate_blob_sas(
account_name=account_name,
account_key=account_key,
container_name=container_name,
blob_name=blob_name,
permission=AccountSasPermissions(read=True),
expiry=datetime.datetime.utcnow() + timedelta(hours=1)
)
url_with_sas = f"{url}?{sas_token}"
print(url_with_sas)
urlopen(url_with_sas)
@app.route('/')
def hello_world():
return jsonify({'Status': 'ok', 'date': '05.25.21'}), 200
if __name__ == '__main__':
import os
HOST = os.environ.get('SERVER_HOST', 'localhost')
try:
PORT = int(os.environ.get('SERVER_PORT', '5555'))
except ValueError:
PORT = 5555
app.run(HOST, PORT)
/download
api contains the code which gets the download url of a blob from azure container in variable name url_with_sas
. Now I want to make this API in such a way that if we hit this, it should automatically download the file from the url. So for this I thought of adding urlopen(url_with_sas)
which will open the url. But seems like its not working. Can anyone give some suggestions for this. Thanks
As in the comment mentioned the solution is via a return redirect(url_with_sas)
so the whole function looks like this:
@app.route('/download')
def download():
account_name = "deeusblobstorage"
container_name = "rperodct"
blob_name = "face_1_7285.jpg"
account_key = "hMlIRXCjAomfDRfied8Y5FPwTVnWEkEDuVsw//CQtkiOdcFD/y5wUcxH9Ou7Ni+DtDQFwe23YbZ3Qia9gw=="
url = f"https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}"
sas_token = generate_blob_sas(
account_name=account_name,
account_key=account_key,
container_name=container_name,
blob_name=blob_name,
permission=AccountSasPermissions(read=True),
expiry=datetime.datetime.utcnow() + timedelta(hours=1)
)
url_with_sas = f"{url}?{sas_token}"
return redirect(url_with_sas)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.