Crea e implementa una función de Cloud Run de HTTP con Python (1ª gen.)
En esta guía, se explica el proceso para escribir una función de Cloud Run con el entorno de ejecución de Python. Existen dos tipos de funciones de Cloud Run:
- Una función de HTTP, que se invoca a partir de solicitudes HTTP estándar
- Una función controlada por eventos, que se usa para manejar los eventos desde tu infraestructura de nube, como mensajes en un tema de Pub/Sub o cambios en un bucket de Cloud Storage
En el ejemplo, se muestra cómo crear una función de HTTP simple.
Antes de comenzar
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions and Cloud Build APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles. -
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions and Cloud Build APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles. - Instala e inicializa gcloud CLI.
- Instala y actualiza los componentes de
gcloud:gcloud components update
- Prepara tu entorno de desarrollo.
Crea un directorio en tu sistema local para el código de función:
Linux o MacOS X
mkdir ~/helloworld cd ~/helloworldWindows
mkdir %HOMEPATH%\helloworld cd %HOMEPATH%\helloworldCrea un archivo
main.pyen el directoriohelloworldcon el siguiente contenido:Esta función de ejemplo toma un nombre proporcionado en la solicitud HTTP y muestra un saludo o "Hello World!" cuando no se proporciona ningún nombre.
Crea un archivo
requirements.txten el directoriohelloworld.Agrega la dependencia de la función a tu archivo
requirements.txt, por ejemplo:# An example requirements file, add your dependencies below sampleproject==2.0.0Cuando la función termine de implementarse, toma nota de la propiedad
httpsTrigger.urlo búscala con el siguiente comando:gcloud functions describe hello_httpSe verá de la siguiente manera:
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http
Visita esta URL en tu navegador. Deberías ver el mensaje "Hello, World!".
Intenta pasar un nombre en la solicitud HTTP, por ejemplo, mediante la siguiente URL:
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http?name=NAME
Deberías ver el mensaje "Hello,
NAME!"
Crea una función
Especifica las dependencias
Las dependencias en Python se administran con pip
y se expresan en un archivo de metadatos llamado
requirements.txt.
Este archivo debe estar en el mismo directorio que el archivo main.py que contiene
el código de tu función.
No necesitas crear un requirements.txt para ejecutar esta muestra en particular,
pero supongamos que deseas agregar tus propias dependencias. Así puedes hacerlo:
Implementa la función
Ejecuta el siguiente comando en el directorio helloworld para implementar
la función con un activador HTTP:
gcloud functions deploy hello_http --no-gen2 --runtime python313 --trigger-http --allow-unauthenticated
La marca --allow-unauthenticated te permite acceder a la función
sin autenticación.
Para solicitar la
autenticación, omite la
marca.
Prueba la función
Visualiza registros
Los registros de Cloud Run Functions pueden verse con Google Cloud CLI y en la IU de Cloud Logging.
Usa la herramienta de línea de comandos
Para visualizar los registros de tu función con gcloud CLI, usa el comando
logs read seguido del
nombre de la función:
gcloud functions logs read hello_http
El resultado debe parecerse al siguiente:
LEVEL NAME EXECUTION_ID TIME_UTC LOG D hello_http pdb5ys2t022n 2019-09-18 23:29:09.791 Function execution started D hello_http pdb5ys2t022n 2019-09-18 23:29:09.798 Function execution took 7 ms, finished with status code: 200
Usa el panel de Logging
También puedes ver los registros de Cloud Run Functions desde la consola deGoogle Cloud .