Si vous créez une fonction, consultez le guide de démarrage rapide de la console sur Cloud Run. Le contenu de cette page ne s'applique qu'aux anciennes fonctions existantes créées avec l'API Cloud Functions v1.
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Créer et déployer une fonction Cloud Run HTTP à l'aide de Python (1re génération)
Ce guide vous accompagne tout au long du processus d'écriture d'une fonction Cloud Run à l'aide de l'environnement d'exécution Python. Il existe deux types de fonctions Cloud Run :
Les fonctions HTTP, que vous appelez à partir des requêtes HTTP standards.
Les fonctions déclenchées par des événements, qui vous permettent de gérer les événements depuis votre infrastructure cloud tels que les messages sur un sujet Pub/Sub ou les modifications apportées à un bucket Cloud Storage.
L'exemple montre comment créer une fonction HTTP simple.
Avant de commencer
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.
Créez un répertoire sur votre système local pour le code de fonction :
Linux ou Mac OS X
mkdir~/helloworldcd~/helloworld
Windows
mkdir%HOMEPATH%\helloworldcd%HOMEPATH%\helloworld
Créez un fichier main.py dans le répertoire helloworld avec le contenu suivant :
importfunctions_frameworkfrommarkupsafeimportescape@functions_framework.httpdefhello_http(request):"""HTTP Cloud Function. Args: request (flask.Request): The request object. <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data> Returns: The response text, or any set of values that can be turned into a Response object using `make_response` <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>. """request_json=request.get_json(silent=True)request_args=request.argsifrequest_jsonand"name"inrequest_json:name=request_json["name"]elifrequest_argsand"name"inrequest_args:name=request_args["name"]else:name="World"returnf"Hello {escape(name)}!"
Cet exemple de fonction utilise un nom fourni dans la requête HTTP et renvoie un message d'accueil. Lorsqu'aucun nom n'est fourni, il renvoie le message "Hello World!".
Spécifier des dépendances
Dans Python, les dépendances sont gérées avec pip et exprimées dans un fichier de métadonnées appelé requirements.txt.
Ce fichier doit se trouver dans le même répertoire que le fichier main.py qui contient le code de votre fonction.
Vous n'avez pas besoin de créer de fichier requirements.txt pour exécuter cet exemple, mais supposons que vous souhaitiez ajouter vos propres dépendances. Voici la procédure à suivre :
Créez un fichier requirements.txt dans le répertoire helloworld.
Ajoutez la dépendance de la fonction à votre fichier requirements.txt, par exemple :
# An example requirements file, add your dependencies belowsampleproject==2.0.0
Déployer la fonction
Pour déployer la fonction avec un déclencheur HTTP, exécutez la commande suivante dans le répertoire helloworld :
Vous pouvez également consulter les journaux Cloud Run Functions depuis la consoleGoogle Cloud .
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/03 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/03 (UTC)."],[[["\u003cp\u003eThis guide provides instructions on creating and deploying an HTTP Cloud Run function using Python (1st gen).\u003c/p\u003e\n"],["\u003cp\u003eThe process involves setting up your development environment with the gcloud CLI and preparing a \u003ccode\u003emain.py\u003c/code\u003e file that contains the Python code for your function.\u003c/p\u003e\n"],["\u003cp\u003eDependencies for the function are managed using a \u003ccode\u003erequirements.txt\u003c/code\u003e file, which lists the necessary external libraries.\u003c/p\u003e\n"],["\u003cp\u003eDeployment is executed via the gcloud CLI with a command that sets up the function as an HTTP trigger, and testing is done by accessing a URL provided upon deployment.\u003c/p\u003e\n"],["\u003cp\u003eFunction logs can be viewed using both the gcloud CLI and the Google Cloud console's Logging dashboard.\u003c/p\u003e\n"]]],[],null,["Create and deploy an HTTP Cloud Run function by using Python (1st gen)\n\nThis guide takes you through the process of writing a Cloud Run function\nusing the Python runtime. There are two types of Cloud Run functions:\n\n- An HTTP function, which you invoke from standard HTTP requests.\n- An event-driven function, which you use to handle events from your Cloud infrastructure, such as messages on a Pub/Sub topic, or changes in a Cloud Storage bucket.\n\nThe sample shows how to create a simple HTTP function.\n| **Learn more** : For more details, read about [HTTP functions](/functions/1stgendocs/writing/write-http-functions) and [event-driven functions](/functions/1stgendocs/writing/write-event-driven-functions).\n\nBefore you begin\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions and Cloud Build APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com&redirect=https://cloud.google.com/functions/quickstart)\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions and Cloud Build APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com&redirect=https://cloud.google.com/functions/quickstart)\n\n1. [Install and initialize the gcloud CLI](/sdk/docs).\n2. Update and install `gcloud` components: \n\n ```bash\n gcloud components update\n ```\n| **Note** : Need a command prompt? You can use the [Google Cloud\n| Shell](https://console.cloud.google.com/?cloudshell=true). The Google Cloud Shell is a command line environment that already includes the Google Cloud CLI, so you don't need to install it. The Google Cloud CLI also comes preinstalled on Google Compute Engine Virtual Machines.\n3. Prepare your development environment.\n [Go to the Python setup guide](/python/docs/setup)\n\nCreate a function\n\n1. Create a directory on your local system for the function code:\n\n Linux or Mac OS X \n\n mkdir ~/helloworld\n cd ~/helloworld\n\n Windows \n\n mkdir %HOMEPATH%\\helloworld\n cd %HOMEPATH%\\helloworld\n\n2. Create a `main.py` file in the `helloworld` directory with the\n following contents:\n\n\n import functions_framework\n\n\n from markupsafe import escape\n\n @functions_framework.http\n def hello_http(request):\n \"\"\"HTTP Cloud Function.\n Args:\n request (flask.Request): The request o\u003cbject.\n https://flask.palletsprojects.com/en/1.1.x/api/#incomi\u003eng-request-data\n Returns:\n The response text, or any set of values that can be turned into a\n Response object using `make_res\u003cponse`\n https://flask.palletsprojects.com/en/1.1.x/api/#flas\u003ek.make_response.\n \"\"\"\n request_json = request.get_json(silent=True)\n request_args = request.args\n\n if request_json and \"name\" in request_json:\n name = request_json[\"name\"]\n elif request_args and \"name\" in request_args:\n name = request_args[\"name\"]\n else:\n name = \"World\"\n return f\"Hello {escape(name)}!\"\n\n This example function takes a name supplied in the HTTP request and returns\n a greeting, or \"Hello World!\" when no name is supplied.\n | **Note:** Cloud Run functions looks for deployable functions in `main.py` by default. Use the [`--source`](/sdk/gcloud/reference/functions/deploy#--source) flag when [deploying your function via `gcloud`](#deploying_the_function) to specify a different directory containing a `main.py` file.\n\nSpecify dependencies\n\nDependencies in Python are managed with [pip](https://pip.pypa.io/en/stable/)\nand expressed in a metadata file called\n[`requirements.txt`](https://pip.pypa.io/en/stable/user_guide/#requirements-files).\nThis file must be in the same directory as the `main.py` file that contains\nyour function code.\n\nYou don't need to create a `requirements.txt` to run this particular sample,\nbut suppose you wanted to add your own dependencies. Here's how you would do it:\n\n1. Create a `requirements.txt` file in the `helloworld` directory.\n\n2. Add the function's dependency, to your `requirements.txt` file, for example:\n\n # An example requirements file, add your dependencies below\n sampleproject==2.0.0\n\n| **Learn more** : For more details, read about [specifying dependencies](/functions/1stgendocs/writing/specifying-dependencies-python).\n\nDeploy the function\n\nTo deploy the function with an HTTP trigger, run the following\ncommand in the `helloworld` directory: \n\n```sh\ngcloud functions deploy hello_http --no-gen2 --runtime python312 --trigger-http --allow-unauthenticated\n```\n\nThe `--allow-unauthenticated` flag lets you reach the function\n[without authentication](/functions/1stgendocs/securing/managing-access-iam#allowing_unauthenticated_http_function_invocation).\nTo require\n[authentication](/functions/1stgendocs/securing/authenticating#developers), omit the\nflag.\n| **Learn more** : For more details, read about [deploying Cloud Run functions](/functions/1stgendocs/deploy#basics).\n\nTest the function\n\n1. When the function finishes deploying, take note of the `httpsTrigger.url`\n property or find it using the following command:\n\n gcloud functions describe hello_http\n\n It should look like this: \n\n ```\n https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http\n ```\n2. Visit this URL in your browser. You should see a \"Hello World!\" message.\n\n Try passing a name in the HTTP request, for example by using the following\n URL: \n\n ```\n https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http?name=NAME\n ```\n\n You should see the message \"Hello \u003cvar translate=\"no\"\u003eNAME\u003c/var\u003e!\"\n\nView logs\n\nLogs for Cloud Run functions are viewable using the Google Cloud CLI, and in the\nCloud Logging UI.\n\nUse the command-line tool\n\nTo view logs for your function with the gcloud CLI, use the\n[`logs read`](/sdk/gcloud/reference/functions/logs/read) command, followed by\nthe name of the function: \n\n```bash\ngcloud functions logs read hello_http\n```\n\nThe output should resemble the following: \n\n```bash\nLEVEL NAME EXECUTION_ID TIME_UTC LOG\nD hello_http pdb5ys2t022n 2019-09-18 23:29:09.791 Function execution started\nD hello_http pdb5ys2t022n 2019-09-18 23:29:09.798 Function execution took 7 ms, finished with status code: 200\n```\n| **Note:** There is typically a slight delay between when log entries are created and when they show up in Cloud Logging.\n\nUse the Logging dashboard\n\nYou can also view logs for Cloud Run functions from the\n[Google Cloud console](https://console.cloud.google.com/project/_/logs?service=cloudfunctions.googleapis.com).\n| **Learn more** : For more details, read about [writing, viewing, and responding to logs](/functions/1stgendocs/monitoring/logging)."]]