简体   繁体   English

使用谷歌应用引擎python将图像从外部链接上传到谷歌云存储

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

I'm looking for a solution on how to upload a picture from an external url like http://example.com/image.jpg to google cloud storage using appengine python, 我正在寻找一个解决方案,如何使用appengine python从http://example.com/image.jpg等外部网址上传图片到google云存储,

I am now using 我现在正在使用

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

for users that want to upload a picture from their computer, calling 对于想要从他们的计算机上传图片的用户,请致电

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

on uploadSuccess and storing that as their profile image. 在uploadSuccess上并将其存储为他们的个人资料图片。 I'm trying to allow users to use their facebook or google profile picture after they login with oauth2. 我试图允许用户在使用oauth2登录后使用他们的脸书或谷歌个人资料图片。 I have access to their profile picture link, and I would just like to copy it for consistency. 我可以访问他们的个人资料图片链接,我只想复制它以保持一致性。 Pease help :) 皮斯帮助:)

To upload an external image you have to get it and save it. 要上传外部图像,您必须获取并保存。 To get the image you van use this code : 要获取图像,您可以使用此代码

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)

To save the image you can use the app engine GCS client code shown here 要保存图像,您可以使用此处显示的应用引擎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))

If you're looking for an updated way of doing this relying on storages package, I wrote those 2 functions: 如果你正在寻找一种依赖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)

Then normally call download_file() and pass url and prefered_file_name from anywhere within your system. 然后通常调用download_file()并从系统中的任何位置传递urlprefered_file_name

The class GoogleCloudStorage came from django-storages package. GoogleCloudStorage类来自django-storages包。

pip install django-storages

Django Storages Django存储

Here is my new solution (2019) using the google-cloud-storage library and upload_from_string() function only (see here ): 这是我的新解决方案(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.

相关问题 无法在Google App Engine和Python上显示来自云存储的图像 - Trouble displaying image from cloud storage on Google App Engine, Python 在App Engine上从Django上传到Google云端存储 - Uploading to Google Cloud Storage from Django on App Engine ferris2-framework,python,google app引擎,云存储-上传图像并将其公开吗? - ferris2-framework, python, google app engine, cloud storage — uploading an image and making it public? 使用Python从Google App Engine上的外部URL上传文件 - Uploading file from external URL on Google App Engine with Python 如何从 App Engine 将图像上传到 Google Cloud Storage - How to upload an image to Google Cloud Storage from App Engine 使用Python将文件从Google云端存储上传到Bigquery - Uploading a file from Google Cloud Storage to Bigquery using Python Google App Engine(Python) - 上传文件(图片) - Google App Engine (Python) - Uploading a file (image) 使用Google App Engine将文件上传到Google云端存储(Python) - Upload Files To Google Cloud Storage With Google App Engine (Python) Google App Engine + Google Cloud Storage + Sqlite3 + Django / Python - Google App Engine + Google Cloud Storage + Sqlite3 + Django/Python 使用Google App Engine和Python上传图像 - Uploading Images using google app engine with Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM