Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
Hier erfahren Sie, wie Sie einen Webdienst, der eine statische HTML-Datei mithilfe von Flask bereitstellt, schreiben und lokal testen.
Anschließend erstellen Sie die Konfigurationsdateien, die zum Bereitstellen des Webdienstes in App Engine erforderlich sind.
In diesem Schritt erstellen Sie eine Version eines Webdienstes, der Platzhalterdaten anzeigt. Anschließend testen Sie den Dienst lokal. Damit soll dafür gesorgt werden, dass Ihr einfacher Webdienst funktioniert, bevor Sie die Datastore- und Firebase-Authentifizierung hinzufügen.
<!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>
Fügen Sie Verhaltensweisen und Stile mit den Dateien static/script.js und static/style.css hinzu:
/** * 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;}
Verwenden Sie in der Datei main.py Flask, um die HTML-Vorlage mit den Platzhalterdaten zu rendern:
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)
Konfigurieren Sie alle Abhängigkeiten, die Sie für Ihren Webdienst benötigen, in der Datei requirements.txt:
Flask==3.0.0
Webdienst testen
Testen Sie jetzt Ihren Webdienst. Führen Sie ihn dazu lokal aus und verwenden Sie eine virtuelle Umgebung:
Wenn Sie sich nicht in dem Verzeichnis befinden, das den Beispielcode enthält, wechseln Sie zu dem Verzeichnis, das den Beispielcode hello_world enthält: Installieren Sie dann Abhängigkeiten:
Gehen Sie zu Ihrem Projektverzeichnis und installieren Sie die Abhängigkeiten: Wenn Sie sich nicht in dem Verzeichnis befinden, das den Beispielcode enthält, wechseln Sie zum Verzeichnis mit dem Beispielcode hello_world. Installieren Sie dann Abhängigkeiten:
Zum Bereitstellen Ihres Webdiensts in App Engine benötigen Sie eine app.yaml-Datei.
In dieser Konfigurationsdatei werden die Einstellungen Ihres Webdienstes für App Engine festgelegt.
Zum Konfigurieren Ihres Webdiensts für die Bereitstellung in App Engine erstellen Sie die Datei app.yaml im Stammverzeichnis Ihres Projekts, z. B. 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
Für diesen einfachen Webdienst müssen Sie in der Datei app.yaml nur die Laufzeiteinstellung und die Handler für statische Dateien festlegen.
Für komplexere Webdienste können Sie zusätzliche Einstellungen in app.yaml konfigurieren, zum Beispiel Skalierung, zusätzliche Handler und andere Anwendungselemente wie Umgebungsvariablen und Dienstnamen.
Weitere Informationen und eine Liste aller unterstützten Elemente finden Sie in der Referenz zu app.yaml.
Nächste Schritte
Nachdem Sie jetzt den Webdienst konfiguriert, erstellt und getestet haben, können Sie diese Version des Webdiensts in App Engine bereitstellen.
[[["Leicht verständlich","easyToUnderstand","thumb-up"],["Mein Problem wurde gelöst","solvedMyProblem","thumb-up"],["Sonstiges","otherUp","thumb-up"]],[["Schwer verständlich","hardToUnderstand","thumb-down"],["Informationen oder Beispielcode falsch","incorrectInformationOrSampleCode","thumb-down"],["Benötigte Informationen/Beispiele nicht gefunden","missingTheInformationSamplesINeed","thumb-down"],["Problem mit der Übersetzung","translationIssue","thumb-down"],["Sonstiges","otherDown","thumb-down"]],["Zuletzt aktualisiert: 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."]]