Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Développez et testez localement un service Web diffusant un fichier HTML statique à l'aide de Flask.
Créez ensuite les fichiers de configuration dont vous avez besoin pour déployer le service Web sur App Engine.
Dans cette étape, vous allez créer et tester localement une version d'un service Web qui affiche des données d'espace réservé. L'objectif est de vérifier que votre service Web de base fonctionne correctement avant d'activer Datastore et Firebase Authentication.
Pour configurer votre service Web, procédez comme suit :
Créez le fichier templates/index.html :
<!doctype html>
<!--
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<head>
<title>Datastore and Firebase Auth Example</title>
<script src="{{ url_for('static', filename='script.js') }}"></script>
<link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Datastore and Firebase Auth Example</h1>
<h2>Last 10 visits</h2>
{% for time in times %}
<p>{{ time }}</p>
{% endfor %}
</body>
</html>
Ajoutez des comportements et des styles à l'aide des fichiers static/script.js et static/style.css :
/** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */body{font-family:"helvetica",sans-serif;text-align:center;}
Dans le fichier main.py, utilisez Flask pour effectuer le rendu de votre modèle HTML avec les données d'espace réservé :
importdatetimefromflaskimportFlask,render_templateapp=Flask(__name__)@app.route("/")defroot():# For the sake of example, use static information to inflate the template.# This will be replaced with real information in later steps.dummy_times=[datetime.datetime(2018,1,1,10,0,0),datetime.datetime(2018,1,2,10,30,0),datetime.datetime(2018,1,3,11,0,0),]returnrender_template("index.html",times=dummy_times)if__name__=="__main__":# This is used when running locally only. When deploying to Google App# Engine, a webserver process such as Gunicorn will serve the app. This# can be configured by adding an `entrypoint` to app.yaml.# Flask's development server will automatically serve static files in# the "static" directory. See:# http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,# App Engine itself will serve those files as configured in app.yaml.app.run(host="127.0.0.1",port=8080,debug=True)
Configurez toutes les dépendances dont vous aurez besoin pour votre service Web dans le fichier requirements.txt :
Flask==3.0.0
Tester votre service Web
Testez votre service Web en l'exécutant localement dans un environnement virtuel :
Si vous n'êtes pas dans le répertoire qui contient l'exemple de code, accédez au répertoire qui contient l'exemple de code hello_world. Ensuite, installez les dépendances :
Accédez au répertoire de votre projet et installez les dépendances : Si vous n'êtes pas dans le répertoire qui contient l'exemple de code, accédez au répertoire qui contient l'exemple de code hello_world. Ensuite, installez les dépendances :
Dans votre navigateur Web, saisissez l'adresse suivante :
http://localhost:8080
Configurer votre service Web pour App Engine
Pour déployer votre service Web sur App Engine, vous avez besoin d'un fichier app.yaml.
Ce fichier de configuration définit les paramètres du service Web pour App Engine.
Pour configurer votre service Web pour le déploiement sur App Engine, créez votre fichier app.yaml dans le répertoire racine de votre projet, par exemple building-an-app :
# Copyright 2021 Google LLC## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.runtime:python313handlers:# This configures Google App Engine to serve the files in the app's static# directory.-url:/staticstatic_dir:static# This handler routes all requests not caught above to your main app. It is# required when static routes are defined, but can be omitted (along with# the entire handlers section) when there are no static files defined.-url:/.*script:auto
Notez que pour ce service Web simple, votre fichier app.yaml ne doit définir que le paramètre d'environnement d'exécution et les gestionnaires des fichiers statiques.
Pour les services Web plus complexes, vous pouvez configurer d'autres paramètres dans votre fichier app.yaml, comme le scaling, des gestionnaires supplémentaires et d'autres éléments d'application tels que les variables d'environnement et les noms des services.
Pour toute information complémentaire et pour obtenir la liste complète des éléments acceptés dans ce fichier de configuration, consultez la documentation de référence sur le fichier app.yaml.
Étapes suivantes
Maintenant que vous avez configuré, créé et testé votre service Web, vous pouvez déployer cette version du service sur App Engine.
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/04 (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/04 (UTC)."],[[["\u003cp\u003eThis guide provides instructions for creating and testing a Python web service using Flask, which serves a static HTML file and placeholder data.\u003c/p\u003e\n"],["\u003cp\u003eThe web service's file structure includes \u003ccode\u003eapp.yaml\u003c/code\u003e, \u003ccode\u003emain.py\u003c/code\u003e, \u003ccode\u003erequirements.txt\u003c/code\u003e, a \u003ccode\u003estatic/\u003c/code\u003e directory for CSS and JavaScript, and a \u003ccode\u003etemplates/\u003c/code\u003e directory for the HTML file.\u003c/p\u003e\n"],["\u003cp\u003eBefore deploying the service, you should set up a local Python 3 environment, install required dependencies using \u003ccode\u003epip\u003c/code\u003e, and test the application locally by running \u003ccode\u003epython main.py\u003c/code\u003e and navigating to \u003ccode\u003ehttp://localhost:8080\u003c/code\u003e in a browser.\u003c/p\u003e\n"],["\u003cp\u003eDeploying to Google App Engine requires an \u003ccode\u003eapp.yaml\u003c/code\u003e file that specifies the Python runtime and defines handlers for static files, with more settings available for complex services.\u003c/p\u003e\n"],["\u003cp\u003eFor new Python web services on Google Cloud, it's recommended to start with Cloud Run instead of App Engine, for which there is a provided quickstart link.\u003c/p\u003e\n"]]],[],null,["# Write a basic web service for App Engine\n\n\u003cbr /\u003e\n\n| **Note:** If you are deploying a new Python web service to Google Cloud, we recommend getting started with [Cloud Run](/run/docs/quickstarts/build-and-deploy/deploy-python-service).\n\nWrite and locally test a web service that serves a static HTML file using Flask.\nThen, create the configuration\nfiles that you need for deploying the web service to App Engine.\n\nIn this step, you create and locally test a version of a web service that\ndisplays placeholder data. The goal here is to ensure that your basic web\nservice is working before adding Datastore and Firebase authentication.\n\nBefore you begin\n----------------\n\n1. If you have not already created a Google Cloud project,\n [create a Google Cloud project](/appengine/docs/standard/python3/building-app/creating-gcp-project).\n\n2. If you have not already, set up your local environment for Python 3\n development by completing the following:\n\n - [Download and install Python 3](/python/docs/setup#installing_python)\n for developing your web service and running the Google Cloud CLI.\n\n - Use your Google Cloud user credentials to authenticate with the\n Google Cloud CLI and enable local testing with Datastore:\n\n gcloud auth application-default login\n\n | **Tip:** For more extensive testing, it is recommended that you set up a service account rather than using user-end credentials. For more information on service accounts and other types of authentication, see [Authentication Overview](/docs/authentication).\n\nStructure your web service files\n--------------------------------\n\nThe project directory where you create your web service will have the\nfollowing file structure:\n\n- `building-an-app/`\n - `app.yaml`\n - `main.py`\n - `requirements.txt`\n - `static/`\n - `script.js`\n - `style.css`\n - `templates/`\n - `index.html`\n\nThe following sections provide an example of how to set up the files in your\nproject directory.\n\nWrite your web service\n----------------------\n\nThe initial iteration of your web service uses Flask to serve a\n[Jinja-based HTML template](http://jinja.pocoo.org/docs/2.10/templates/).\n\nTo set up your web service:\n\n1. Create your `templates/index.html` file:\n\n \u003c!doctype html\u003e\n \u003c!--\n Copyright 2021 Google LLC\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n --\u003e\n\n \u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eDatastore and Firebase Auth Example\u003c/title\u003e\n \u003cscript src=\"{{ url_for('static', filename='script.js') }}\"\u003e\u003c/script\u003e\n \u003clink type=\"text/css\" rel=\"stylesheet\" href=\"{{ url_for('static', filename='style.css') }}\"\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n\n \u003ch1\u003eDatastore and Firebase Auth Example\u003c/h1\u003e\n\n \u003ch2\u003eLast 10 visits\u003c/h2\u003e\n {% for time in times %}\n \u003cp\u003e{{ time }}\u003c/p\u003e\n {% endfor %}\n\n \u003c/body\u003e\n \u003c/html\u003e\n\n2. Add behaviors and styles with `static/script.js` and `static/style.css` files:\n\n 'use strict';\n\n window.addEventListener('load', function () {\n\n console.log(\"Hello World!\");\n\n });\n\n /**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n body {\n font-family: \"helvetica\", sans-serif;\n text-align: center;\n }\n\n3. In your `main.py` file, use Flask to render your HTML template with the\n placeholder data:\n\n import datetime\n\n from flask import Flask, render_template\n\n app = Flask(__name__)\n\n\n @app.route(\"/\")\n def root():\n # For the sake of example, use static information to inflate the template.\n # This will be replaced with real information in later steps.\n dummy_times = [\n datetime.datetime(2018, 1, 1, 10, 0, 0),\n datetime.datetime(2018, 1, 2, 10, 30, 0),\n datetime.datetime(2018, 1, 3, 11, 0, 0),\n ]\n\n return render_template(\"index.html\", times=dummy_times)\n\n\n if __name__ == \"__main__\":\n # This is used when running locally only. When deploying to Google App\n # Engine, a webserver process such as Gunicorn will serve the app. This\n # can be configured by adding an `entrypoint` to app.yaml.\n # Flask's development server will automatically serve static files in\n # the \"static\" directory. See:\n # http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,\n # App Engine itself will serve those files as configured in app.yaml.\n app.run(host=\"127.0.0.1\", port=8080, debug=True)\n\n4. Configure all dependencies you will need for your web service in your\n `requirements.txt` file:\n\n Flask==3.0.0\n\nTest your web service\n---------------------\n\nTest your web service by running it locally in a virtual environment: \n\n### Mac OS / Linux\n\n1. Create an [isolated Python environment](/python/docs/setup#installing_and_using_virtualenv): \n\n python3 -m venv env\n source env/bin/activate\n\n2. If you're not in the directory that contains the sample code, navigate to the directory that contains the `hello_world` sample code. Then install dependencies: \n\n cd \u003cvar translate=\"no\"\u003eYOUR_SAMPLE_CODE_DIR\u003c/var\u003e\n pip install -r requirements.txt\n\n3. Run the application: \n\n ```bash\n python main.py\n ```\n4. In your web browser, enter the following address: \n\n ```bash\n http://localhost:8080\n ```\n\n### Windows\n\nUse\nPowerShell to run your Python packages.\n\n1. Locate your installation of [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-windows).\n2. Right-click on the shortcut to PowerShell and start it as an administrator.\n3. Create an [isolated Python environment](/python/docs/setup#installing_and_using_virtualenv). \n\n python -m venv env\n .\\env\\Scripts\\activate\n\n4. Navigate to your project directory and install dependencies. If you're not in the directory that contains the sample code, navigate to the directory that contains the `hello_world` sample code. Then, install dependencies: \n\n cd \u003cvar translate=\"no\"\u003eYOUR_SAMPLE_CODE_DIR\u003c/var\u003e\n pip install -r requirements.txt\n\n5. Run the application: \n\n ```bash\n python main.py\n ```\n6. In your web browser, enter the following address: \n\n ```bash\n http://localhost:8080\n ```\n\nConfigure your web service for App Engine\n-----------------------------------------\n\nTo deploy your web service to App Engine, you need an `app.yaml` file.\nThis configuration file defines your web service's settings for\nApp Engine.\n\nTo configure your web service for deployment to App Engine, create\nyour `app.yaml` file in the root directory of your project, for example\n`building-an-app`: \n\n # Copyright 2021 Google LLC\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # http://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n\n runtime: python313\n\n handlers:\n # This configures Google App Engine to serve the files in the app's static\n # directory.\n - url: /static\n static_dir: static\n\n # This handler routes all requests not caught above to your main app. It is\n # required when static routes are defined, but can be omitted (along with\n # the entire handlers section) when there are no static files defined.\n - url: /.*\n script: auto\n\nNotice that for this simple web service, your `app.yaml` file needs to define\nonly the runtime setting and handlers for static files.\n\nFor more complicated web services, you can configure additional settings\nin your `app.yaml`, like scaling, additional handlers, and other\napplication elements like environment variables and service names.\nFor more information and a list of all the supported elements, see the\n[`app.yaml` reference](/appengine/docs/standard/reference/app-yaml).\n\nNext steps\n----------\n\nNow that you've configured, created, and tested your web service, you can\ndeploy this version of your web service to App Engine."]]