Ich habe Beispielfunktionen erstellt. Ich habe dies beides über Cloud Run Functions (console.cloud.google.com/functions/) gemacht. Hier wird „Bereitgestellt von“ als „Cloud Run-Funktionen“ und über Cloud Run (d. h. console.cloud.google.com/run) angezeigt. Hier wird „Bereitgestellt von“ als mein Konto angezeigt. Gleiche Ergebnisse.
Für das erste vorgefertigte Hallo-Welt-Beispiel lassen sich beide problemlos bereitstellen.
Jetzt fügen wir die Pub-Sub-Funktion hinzu. Fügen Sie google-cloud-pubsub zur Anforderungsdatei hinzu. Fügen Sie den Pub-Sub-Client zur App hinzu. Erstellen Sie ein Pub-Sub-Thema (was ich über die Benutzeroberfläche mache).
Jetzt sieht es also so aus...
Code: Select all
import json
import os
import functions_framework
from google.cloud import pubsub_v1
PROJECT_ID = "my project"
publisher = pubsub_v1.PublisherClient()
@functions_framework.http
def hello_http(request):
"""HTTP Cloud Function.
Args:
request (flask.Request): The request object.
Returns:
The response text, or any set of values that can be turned into a
Response object using `make_response`
.
"""
request_json = request.get_json(silent=True)
request_args = request.args
topic_name = 'projects/{project_id}/topics/{topic}'.format(
project_id=PROJECT_ID,
topic='test-topic',
)
message = {
'key': 'value',
'info': 'This is a test message'
}
future = publisher.publish(topic_name, json.dumps(message).encode("utf-8"))
future.result()
if request_json and 'name' in request_json:
name = request_json['name']
elif request_args and 'name' in request_args:
name = request_args['name']
else:
name = 'World'
return 'Hello {}!'.format(name)
WARNUNG: Alle Protokollmeldungen vor dem Aufruf von absl::InitializeLog() werden in STDERR geschrieben
E0000 00:00:1734272617.454893 1 init.cc:229] grpc_wait_for_shutdown_with_timeout() Zeitüberschreitung.
Außerdem erhalte ich seltsame Fehler in der Google Cloud Platform Run-Testkonsole, die scheinbar mit dem Build zusammenhängen (z. B. /bin/sh: 2c3d685a15e9). Manchmal kommt es zu Fehlern, manchmal nicht.
Code: Select all
[9:47:15 PM] - Preparing function sources ...
[9:47:15 PM] - Loading new function sources ...
[9:47:22 PM] - Starting function...
[9:47:22 PM] - WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
E0000 00:00:1734144439.303879 20 init.cc:229] grpc_wait_for_shutdown_with_timeout() timed out.
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
E0000 00:00:1734144441.495104 7 init.cc:229] grpc_wait_for_shutdown_with_timeout() timed out.
/bin/sh: 2c3d685a15e9: not found
/bin/sh: 2c3d685a15e9: not found
Mobile version