Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Escribe y prueba de forma local un servicio web que entregue un archivo HTML estático con Flask.
Luego, crea los archivos de configuración que necesitas para implementar el servicio web en App Engine.
En este paso, crearás y probarás localmente una versión de un servicio web que muestra datos de marcador de posición. El objetivo aquí es garantizar que el servicio web básico esté funcionando antes de agregar la autenticación de Datastore y Firebase.
Para configurar tu servicio web, sigue estos pasos:
Crea tu archivo 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>
Agrega comportamientos y estilos con los archivos static/script.js y 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;}
En tu archivo main.py, utiliza Flask para generar la plantilla HTML con los datos del marcador de posición:
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)
Configura todas las dependencias que necesitarás para el servicio web en tu archivo requirements.txt:
Flask==3.0.0
Prueba tu servicio web
Para probar un servicio web, ejecútalo de forma local en un entorno virtual:
Si no estás en el directorio que contiene el código de muestra, navega al directorio que contiene el código de muestra hello_world. Luego, instala las dependencias:
Navegue al directorio del proyecto y luego instale las dependencias. Si no estás en el directorio que contiene el código de muestra, navega al directorio que contiene el código de muestra hello_world. Luego, instala las dependencias:
En el navegador web, ingresa la siguiente dirección:
http://localhost:8080
Configura tu servicio web para App Engine
Para implementar tu servicio web en App Engine, necesitas un archivo app.yaml.
Este archivo de configuración define la configuración de tu servicio web para App Engine.
Para configurar tu servicio web para la implementación en App Engine, crea tu archivo app.yaml en el directorio raíz de tu proyecto, por ejemplo 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
Ten en cuenta que, para este servicio web simple, el archivo app.yaml debe definir solo la configuración del entorno de ejecución y los controladores para archivos estáticos.
Para servicios web más complicados, puedes configurar ajustes adicionales en tu archivo app.yaml, como escalamiento, controladores adicionales y otros elementos de aplicaciones, por ejemplo, variables del entorno y nombres de servicio.
Para obtener más información y una lista de todos los elementos compatibles, consulta la referencia de app.yaml.
Próximos pasos
Ahora que has configurado, creado y probado tu servicio web, puedes implementar esta versión del servicio web en App Engine.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 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."]]