Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Scrivi e testa localmente un servizio web che pubblica un file HTML statico utilizzando Flask.
Poi crea i file di configurazione
necessari per il deployment del servizio web in App Engine.
In questo passaggio, crei e testi localmente una versione di un servizio web che
mostra dati segnaposto. L'obiettivo è garantire che il servizio web di base funzioni prima di aggiungere l'autenticazione Datastore e Firebase.
<!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>
Aggiungi comportamenti e stili con i file static/script.js e 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;}
Nel file main.py, utilizza Flask per eseguire il rendering del modello HTML con i dati
segnaposto:
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 tutte le dipendenze necessarie per il tuo servizio web nel file
requirements.txt:
Flask==3.0.0
Testare il servizio web
Testa il tuo servizio web eseguendolo localmente in un ambiente virtuale:
Se non ti trovi nella directory che contiene il codice campione, vai
alla directory che contiene il codice campione hello_world. Poi installa le dipendenze:
Naviga alla directory del progetto e installa le dipendenze. Se non ti trovi nella directory
che contiene ilcodice campioneo, vai alla directory che contiene il
codice campioneio hello_world. Poi installa le dipendenze:
Per eseguire il deployment del servizio web in App Engine, è necessario un file app.yaml.
Questo file di configurazione definisce le impostazioni del servizio web per
App Engine.
Per configurare il servizio web per il deployment in App Engine, crea
il file app.yaml nella directory radice del progetto, ad esempio
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
Tieni presente che per questo semplice servizio web, il file app.yaml deve definire
solo l'impostazione del runtime e i gestori per i file statici.
Per i servizi web più complessi, puoi configurare impostazioni aggiuntive
nel file app.yaml, come scalabilità, gestori aggiuntivi e altri
elementi dell'applicazione come variabili di ambiente e nomi di servizio.
Per ulteriori informazioni e un elenco di tutti gli elementi supportati, consulta il
riferimento app.yaml.
Passaggi successivi
Ora che hai configurato, creato e testato il tuo servizio web, puoi
eseguire il deployment di questa versione del servizio web in App Engine.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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."]]