使用Google App Engine Python从外部链接上传图片到Google Cloud Storage

7 投票
3 回答
5514 浏览
提问于 2025-04-18 17:57

我想找个办法,把一个外部网址的图片,比如 http://example.com/image.jpg,上传到谷歌云存储,使用的是appengine的python。

现在我正在使用

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

对于那些想从自己电脑上传图片的用户,我会调用

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

在上传成功后,把图片存储为他们的个人资料图片。我想让用户在用oauth2登录后,可以使用他们的Facebook或谷歌头像。我已经能获取到他们头像的链接,只想把它复制过来,以保持一致性。请帮帮我 :)

3 个回答

0

如果你想要一个更新的方法来使用 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 Storages

2

这是我在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())
13

要上传一张外部图片,你需要先获取这张图片并保存下来。
获取图片时,你可以使用这段代码

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))

撰写回答