我在使用 Flask azure 應用程式時遇到問題。我在存盤中保存了一些檔案(pdf 和 html),我需要在呼叫 get_file_safe 端點時回傳這些檔案。此方法采用 file_id 引數并訪問資料庫,轉到 blob azure,創建一個臨時檔案并回傳該檔案。當我傳遞參考 PDF 檔案的代碼時,它運行良好,檔案顯示在螢屏上。當代碼與 HTML 檔案匹配時,答案為空。有誰知道它可能是什么?非常感謝你 !(注意:當我使用 GCP 時它可以作業,但我必須遷移,所以我把它放在這里,它是天藍色的)。
from flask import Flask, flash, jsonify, session, redirect, url_for, escape, request, render_template, session, send_file
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__, ContentSettings
def get_file_safe():
#login and security stuff (...) Logic goes here ->>>
file_id = request.args.get('file_id')
cursor.execute(
"""SELECT link, mimetype from TABLE where id = %s """, (file_id))
rows = cursor.fetchall()
link = rows[0][0]
mimetype = rows[0][1]
filename = link.split("/")[-1]
print("Filename{}".format(filename))
print("Mimetype {}".format(mimetype))
# google cloud version, commented
#client = storage.Client()
#bucket = client.get_bucket('BUCKET_NAME')
#blob = bucket.blob(link)
#with tempfile.NamedTemporaryFile() as temp:
# blob.download_to_filename(temp.name)
# return send_file(temp.name, attachment_filename=filename)
# azure verson
bucket_name = 'BUCKET-NAME'
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
blob_client = blob_service_client.get_blob_client(container=bucket_name, blob=link)
with tempfile.NamedTemporaryFile() as temp:
temp.write(blob_client.download_blob().readall())
#return send_file(temp.name, attachment_filename=filename, mimetype=mimetype)
return send_file(temp.name, download_name=filename)
uj5u.com熱心網友回復:
正如你提到的只有無法讀取的 html 檔案,所以我嘗試使用 html 檔案讀取臨時檔案將其顯示在瀏覽器上
我試過tempfile.NamedTemporaryFile() as temp:但得到了黑頁然后我也試過tempfile.NamedTemporaryFile('w', delete=False, suffix='.html') as f:
我把資料寫成能夠得到頁面的字串
你能試試tempfile.NamedTemporaryFile('w', delete=False, suffix='.html') as f:for html 檔案嗎
from azure.storage.blob import BlobServiceClient
import tempfile
import webbrowser
blob_service_client = BlobServiceClient.from_connection_string("Connection String ")
# Initialise container
blob_container_client = blob_service_client.get_container_client("test")
# Get blob
blob_client = blob_container_client.get_blob_client("test.html")
print("downloaded the blob ")
# Download
str=blob_client.download_blob().readall()
print(str)
print(str.decode("utf-8"))
//Getting the Blank Page
with tempfile.NamedTemporaryFile() as temp:
url = 'file://' temp.name
temp.write(blob_client.download_blob().readall())
#temp.write(str)
webbrowser.open(url)
//Getting page
html=str.decode("utf-8")
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.html') as f:
url = 'file://' f.name
f.write(html)
webbrowser.open(url)
這是輸出的外觀


轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/391087.html
標籤:Python 烧瓶 azure-blob-storage
下一篇:嘗試訪問Xamarin.FormsAndroid上的服務器時拋出System.AggregateException
