簡體   English   中英

使用谷歌應用引擎python將圖像從外部鏈接上傳到谷歌雲存儲

[英]Uploading an Image from an external link to google cloud storage using google app engine python

我正在尋找一個解決方案,如何使用appengine python從http://example.com/image.jpg等外部網址上傳圖片到google雲存儲,

我現在正在使用

blobstore.create_upload_url('/uploadSuccess', gs_bucket_name=bucketPath)

對於想要從他們的計算機上傳圖片的用戶,請致電

images.get_serving_url(gsk,size=180,crop=True)

在uploadSuccess上並將其存儲為他們的個人資料圖片。 我試圖允許用戶在使用oauth2登錄后使用他們的臉書或谷歌個人資料圖片。 我可以訪問他們的個人資料圖片鏈接,我只想復制它以保持一致性。 皮斯幫助:)

要上傳外部圖像,您必須獲取並保存。 要獲取圖像,您可以使用此代碼

from google.appengine.api import urlfetch

file_name = 'image.jpg'
url = 'http://example.com/%s' % file_name
result = urlfetch.fetch(url)
if result.status_code == 200:
    doSomethingWithResult(result.content)

要保存圖像,您可以使用此處顯示的應用引擎GCS客戶端代碼

import cloudstorage as gcs
import mimetypes

doSomethingWithResult(content):

    gcs_file_name = '/%s/%s' % ('bucket_name', file_name)
    content_type = mimetypes.guess_type(file_name)[0]
    with gcs.open(gcs_file_name, 'w', content_type=content_type,
                  options={b'x-goog-acl': b'public-read'}) as f:
        f.write(content)

    return images.get_serving_url(blobstore.create_gs_key('/gs' + gcs_file_name))

如果你正在尋找一種依賴storages包的更新方式,我寫了這兩個函數:

import requests
from storages.backends.gcloud import GoogleCloudStorage


def download_file(file_url, file_name):
    response = requests.get(file_url)
    if response.status_code == 200:
        upload_to_gc(response.content, file_name)


def upload_to_gc(content, file_name):
    gc_file_name = "{}/{}".format("some_container_name_here", file_name)
    with GoogleCloudStorage().open(name=gc_file_name, mode='w') as f:
        f.write(content)

然后通常調用download_file()並從系統中的任何位置傳遞urlprefered_file_name

GoogleCloudStorage類來自django-storages包。

pip install django-storages

Django存儲

這是我的新解決方案(2019),僅使用google-cloud-storage庫和upload_from_string()函數(參見此處 ):

from google.cloud import storage
import urllib.request

BUCKET_NAME = "[project_name].appspot.com" # change project_name placeholder to your preferences
BUCKET_FILE_PATH = "path/to/your/images" # change this path

def upload_image_from_url_to_google_storage(img_url, img_name):
    """
    Uploads an image from a URL source to google storage.
    - img_url: string URL of the image, e.g. https://picsum.photos/200/200
    - img_name: string name of the image file to be stored
    """
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(BUCKET_NAME)
    blob = bucket.blob(BUCKET_FILE_PATH + "/" + img_name + ".jpg")

    # try to read the image URL
    try:
        with urllib.request.urlopen(img_url) as response:
            # check if URL contains an image
            info = response.info()
            if(info.get_content_type().startswith("image")):
                blob.upload_from_string(response.read(), content_type=info.get_content_type())
                print("Uploaded image from: " + img_url)
            else:
                print("Could not upload image. No image data type in URL")
    except Exception:
        print('Could not upload image. Generic exception: ' + traceback.format_exc())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM