您可以trigger a Cloud Function from a Google Cloud Storage bucket,通过选择Event Type为Finalize/Create,每次在bucket中上传文件,都会调用Cloud Function。
每次在存储桶中创建新对象时,云函数都会收到带有Cloud Storage object format 的通知。
现在,进入第二步,我找不到任何可以将文件从云存储上传到实例 VM 的 API。但是,我做了以下解决方法,假设您的实例 VM 配置了可以接收 HTTP 请求的服务器(例如 Apache 或 Nginx):
main.py
import requests
from google.cloud import storage
def hello_gcs(data, context):
"""Background Cloud Function to be triggered by Cloud Storage.
Args:
data (dict): The Cloud Functions event payload.
context (google.cloud.functions.Context): Metadata of triggering event.
Returns:
None; the file is sent as a request to
"""
print('Bucket: {}'.format(data['bucket']))
print('File: {}'.format(data['name']))
client = storage.Client()
bucket = client.get_bucket(data['bucket'])
blob = bucket.get_blob(data['name'])
contents = blob.download_as_string()
headers = {
'Content-type': 'text/plain',
}
data = '{"text":"{}"}'.format(contents)
response = requests.post('https://your-instance-server/endpoint-to-download-files', headers=headers, data=data)
return "Request sent to your instance with the data of the object"
requirements.txt
google-cloud-storage
requests
最好将对象名称和存储桶名称发送到您的服务器端点,然后使用Cloud Client Library 从那里下载文件。
现在你可能会问...
如何制作 Compute Engine 实例来处理请求?
创建一个 Compute Engine 实例虚拟机。确保它与云函数位于同一区域,并在创建它时允许对其进行 HTTP 连接。 Documentation。我在这个测试中使用了debian-9 图片。
-
SSH 进入实例,并运行以下命令:
-
为您的应用程序设置环境:
cd ~/
mkdir app
sudo ln -sT ~/app /var/www/html/app
最后一行应该指向 apache 提供 index.html 文件的文件夹路径。
- 在
/home/<user_name>/app中创建您的应用程序:
main.py
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def receive_file():
file_content = request.form['data']
# TODO
# Implement process to save this data onto a file
return 'Hello from Flask!'
if __name__ == '__main__':
app.run()
- 在同一目录中创建 wsgi 服务器入口点:
main.wsgi
import sys
sys.path.insert(0, '/var/www/html/app')
from main import app as application
-
将以下行添加到/etc/apache2/sites-enabled/000-default.conf,在DocumentRoot 标记之后:
WSGIDaemonProcess flaskapp threads=5
WSGIScriptAlias / /var/www/html/app/main.wsgi
<Directory app>
WSGIProcessGroup main
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
-
运行sudo apachectl restart。您应该能够将发布请求发送到您的应用程序,发送到 VM 实例的内部 IP(您可以在控制台的 Compute Engine 部分中看到它)。一旦你有了它,在你的云函数中,你应该将响应行更改为:
response = requests.post('<INTERNAL_INSTANCE_IP>/', headers=headers, data=data)
return "Request sent to your instance with the data of the object"