[Fuente: https://cloud.google.com/appengine/docs/python/gettingstartedpython27/introduction?hl=es]
Introduction
Welcome to Google App Engine! Creating an App Engine application is easy, and only takes a few minutes. And it’s free to start: upload your app and share it with users right away, at no charge and with no commitment required.
Google App Engine applications can be written in the Python 2.7, Java, Go or PHP programming languages. This tutorial covers Python 2.7. If you would prefer to use Java, Go or PHP to build your applications, see the Java, Go or PHP guides.
In this tutorial, you will learn how to:
- build an App Engine application using Python
- use the
webapp2
web application framework - use the App Engine datastore with the Python modeling API
- integrate an App Engine application with Google Accounts for user authentication
- use Jinja2 templates with your app
- upload your app to App Engine
By the end of the tutorial, you will have implemented a working application, a simple guest book that lets users post messages to a public message board.
Run/Modify
While going through this tutorial you will see buttons that allow you to test the code sample right in your browser in the Google Cloud Playground. These are labeled “Run/Modify.” You can even make changes to the code and see the results in real-time!
Get set up
Before we continue, you will need to download the Google App Engine Python SDK, which includes a web server application that simulates the App Engine environment, and tools to deploy your application to the App Engine production environment. Follow the directions for your operating system, then come back here so we can get going!
Hello, World!
Let’s begin by implementing a tiny application that displays a short message.
Creating a Simple Request Handler
Create a directory named helloworld
. All files for this application reside in this directory.
Inside the helloworld
directory, create a file named helloworld.py
, and give it the following contents:
[Fuente: https://cloud.google.com/appengine/docs/python/gettingstartedpython27/introduction?hl=es]
Introduction
Welcome to Google App Engine! Creating an App Engine application is easy, and only takes a few minutes. And it’s free to start: upload your app and share it with users right away, at no charge and with no commitment required.
Google App Engine applications can be written in the Python 2.7, Java, Go or PHP programming languages. This tutorial covers Python 2.7. If you would prefer to use Java, Go or PHP to build your applications, see the Java, Go or PHP guides.
In this tutorial, you will learn how to:
- build an App Engine application using Python
- use the
webapp2
web application framework - use the App Engine datastore with the Python modeling API
- integrate an App Engine application with Google Accounts for user authentication
- use Jinja2 templates with your app
- upload your app to App Engine
By the end of the tutorial, you will have implemented a working application, a simple guest book that lets users post messages to a public message board.
Run/Modify
While going through this tutorial you will see buttons that allow you to test the code sample right in your browser in the Google Cloud Playground. These are labeled “Run/Modify.” You can even make changes to the code and see the results in real-time!
Get set up
Before we continue, you will need to download the Google App Engine Python SDK, which includes a web server application that simulates the App Engine environment, and tools to deploy your application to the App Engine production environment. Follow the directions for your operating system, then come back here so we can get going!
Hello, World!
Let’s begin by implementing a tiny application that displays a short message.
Creating a Simple Request Handler
Create a directory named helloworld
. All files for this application reside in this directory.
Inside the helloworld
directory, create a file named helloworld.py
, and give it the following contents:
import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.write('Hello, World!') application = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True)
This Python script responds to a request with an HTTP header that describes the content and the message Hello, World!
.
Note: Ensure that you save the files you create as plain text. You may encounter errors otherwise.
Creating the Configuration File
An App Engine application has a configuration file called app.yaml
. Among other things, this file describes which handler scripts should be used for which URLs.
Inside the helloworld
directory, create a file named app.yaml
with the following contents:
application: grouchy_smurf version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: /.* script: helloworld.application
From top to bottom, this configuration file says the following about this application:
- The application identifier is
your-app-id
. Every new application on App Engine has a unique application identifier. You’ll choose the identifier for your application when you register it in the next step. Until then you can just leave the value here set toyour-app-id
because this value is not important when developing locally. - This is version number
1
of this application’s code. If you adjust this before uploading new versions of your application software, App Engine will retain previous versions, and let you roll back to a previous version using the administrative console. - This code runs in the
python27
runtime environment, API version1
. Additional runtime environments and languages may be supported in the future. - This application is
threadsafe
so the same instance can handle several simultaneous requests. Threadsafe is an advanced feature and may result in erratic behavior if your application is not specifically designed to be threadsafe. - Every request to a URL whose path matches the regular expression
/.*
(all URLs) should be handled by theapplication
object in thehelloworld
module.
The syntax of this file is YAML. For a complete list of configuration options, see the app.yaml reference.
Testing the Application
With a handler script and configuration file mapping every URL to the handler, the application is complete. You can now test it with the web server included with the App Engine SDK.
If you’re using the Google App Engine Launcher, you can set up the application by selecting the File menu, Add Existing Application…, then selecting the helloworld
directory. Select the application in the app list, click the Run button to start the application, then click the Browse button to view it. Clicking Browse simply loads (or reloads) http://localhost:8080/ in your default web browser.
If you’re not using Google App Engine Launcher, start the web server with the following command, giving it the path to the helloworld
directory:
<path-to-Python-SDK>/dev_appserver.py helloworld/
The web server is now running, listening for requests on port 8080. You can test the application by visiting the following URL in your web browser:
For more information about running the development web server, including how to change which port it uses, see the Dev Web Server reference, or run the command with the option --help
.
Iterative Development
You can leave the web server running while you develop your application. The web server knows to watch for changes in your source files and reload them if necessary.
Try it now: Leave the web server running, then edit helloworld.py
to change Hello, World!
to something else. Reload http://localhost:8080/ or click Browse in Google App Engine Launcher to see the change.
To shut down the web server, make sure the terminal window is active, then press Control-C (or the appropriate “break” key for your console), or click Stop in Google App Engine Launcher.
You can leave the web server running for the rest of this tutorial. If you need to stop it, you can restart it again by running the command above.
Explaining the webapp2 Framework
The Web Server Gateway Interface (WSGI) standard is simple, but it would be cumbersome to write all of the code that uses it by hand. Web application frameworks handle these details for you, so you can focus your development efforts on your application’s features. Google App Engine supports any framework written in pure Python that speaks WSGI, including Django, CherryPy, Pylons, web.py, and web2py. You can bundle a framework of your choosing with your application code by copying its code into your application directory.
App Engine includes a simple web application framework, called webapp2
. The webapp2
framework is already installed in the App Engine environment and in the SDK, so you do not need to bundle it with your application code to use it. We will use webapp2
for the rest of this tutorial.
Hello, webapp2!
A webapp2
application has two parts:
- one or more
RequestHandler
classes that process requests and build responses - a
WSGIApplication
instance that routes incoming requests to handlers based on the URL
Let’s take another look at our friendly greeting application:
import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.write('Hello, World!') application = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True)
What webapp2 Does
This code defines one request handler, MainPage
, mapped to the root URL (/
). When webapp2
receives an HTTP GET request to the URL /
, it instantiates the MainPage
class and calls the instance’s get
method. Inside the method, information about the request is available using self.request
. Typically, the method sets properties on self.response
to prepare the response, then exits. webapp2
sends a response based on the final state of the MainPage
instance.
The application itself is represented by a webapp2.WSGIApplication
instance. The parameter debug=true
passed to its constructor tells webapp2
to print stack traces to the browser output if a handler encounters an error or raises an uncaught exception. You may wish to remove this option from the final version of your application.
We’ll use a few more features of webapp2 later in this tutorial. For more information about webapp2
, see the webapp2 documentation.
Using the Users Service
Google App Engine provides several useful services based on Google infrastructure, accessible by applications using libraries included with the SDK. One such service is the Users service, which lets your application integrate with Google user accounts. With the Users service, your users can use the Google accounts they already have to sign in to your application.
Let’s use the Users service to personalize this application’s greeting.
Using Users
Edit helloworld/helloworld.py
again, and replace its contents with the following:
from google.appengine.api import users import webapp2 class MainPage(webapp2.RequestHandler): def get(self): # Checks for active Google account session user = users.get_current_user() if user: self.response.headers['Content-Type'] = 'text/plain' self.response.write('Hello, ' + user.nickname()) else: self.redirect(users.create_login_url(self.request.uri)) application = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True)
User
object based on that username.When your application is running on App Engine, users will be directed to the Google Accounts sign-in page, then redirected back to your application after successfully signing in or creating an account.
The Users API
Let’s take a closer look at the new pieces:
# Checks for active Google account session user = users.get_current_user()
If the user is already signed in to your application, get_current_user()
returns the User
object for the user. Otherwise, it returns None
.
if user: self.response.headers['Content-Type'] = 'text/plain' self.response.write('Hello, ' + user.nickname())
If the user has signed in, display a personalized message, using the nickname associated with the user’s account.
else: self.redirect(users.create_login_url(self.request.uri))
If the user has not signed in, tell webapp2
to redirect the user’s browser to the Google account sign-in screen. The redirect includes the URL to this page (self.request.uri
) so the Google account sign-in mechanism will send the user back here after the user has signed in or registered for a new account.
For more information about the Users API, see the Users reference.
Handling Forms with webapp2
If we want users to be able to post their own greetings, we need a way to process information submitted by the user with a web form. The webapp2
framework makes processing form data easy.
From Hello World to Guestbook
In order to prepare the Hello World app we’ve created thus far, please make the following changes:
- Rename the top level
helloworld
directory toguestbook
- Rename
helloworld.py
toguestbook.py
- Replace the
handlers
section ofapp.yaml
with: -
handlers: - url: /.* script: guestbook.application
Restart the development server using the new guestbook
directory.
Handling Web Forms With webapp2
Declare that you are using webapp2
by adding this libraries
section to your app.yaml
:
libraries: - name: webapp2 version: latest
Replace the contents of guestbook/guestbook.py
with the following:
Reload the page to see the form, then try submitting a message.
This version has two handlers: MainPage
, mapped to the URL /
, displays a web form. Guestbook
, mapped to the URL /sign
, displays the data submitted by the web form.
The Guestbook
handler has a post()
method instead of a get()
method. This is because the form displayed byMainPage
uses the HTTP POST method (method="post"
) to submit the form data. If for some reason you need a single handler to handle both GET and POST actions to the same URL, you can define a method for each action in the same class.
The code for the post()
method gets the form data from self.request
. Before displaying it back to the user, it uses cgi.escape()
to escape HTML special characters to their character entity equivalents. cgi
is a module in the standard Python library; see the documentation for cgi
for more information.