Skip to content

Instantly share code, notes, and snippets.

@feliperyan
Created June 12, 2024 03:04
Show Gist options
  • Save feliperyan/0795eec670aa33a5944d0ae520babb26 to your computer and use it in GitHub Desktop.
Save feliperyan/0795eec670aa33a5944d0ae520babb26 to your computer and use it in GitHub Desktop.
from flask import Flask, send_file, render_template_string
from google.cloud import storage
import os
import io
app = Flask(__name__)
# Configure the environment variable for GCS credentials
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/to/your/service-account-file.json"
# Function to download image from GCS
def download_blob(bucket_name, source_blob_name):
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(source_blob_name)
image_data = blob.download_as_bytes()
return io.BytesIO(image_data)
# Specify your GCS bucket name and the file path within the bucket
bucket_name = 'your-bucket-name'
source_blob_name = 'path/to/your/image.jpg'
@app.route('/')
def home():
html_content = '''
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Flask Image Display</title>
</head>
<body>
<h1>Image from Google Cloud Storage</h1>
<img src="/image" alt="GCS Image">
</body>
</html>
'''
return render_template_string(html_content)
@app.route('/image')
def display_image():
image_stream = download_blob(bucket_name, source_blob_name)
image_stream.seek(0)
return send_file(image_stream, mimetype='image/jpeg')
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment