Simple Google App Engine tutorial

Source: Internet
Author: User

 

This article uses a simple example to show you how to create a simple App Engine program. First, we will introduce you to Google App Engine.

Introduction to Google App Engine

Google App Engine provides a complete set of development components to allow users to easily build and debug network applications locally, and then allow users to deploy and run network applications on Google's powerful infrastructure, the application is automatically expanded based on the load of the application, and maintenance tasks such as user and server are not required. At the same time, it provides a large number of free quotas and flexible tariff standards. In terms of development languages, Java and Python are now supported, and basically the same functions and APIs are provided for these two languages.

Example

This example is very simple: Submit a blog table and store it in the datastore of App Engine. If you are interested in the source code, you can download it through this address. This article focuses on the Python version of APP engine. The Java version of App Engine is not discussed in this article.

Build Environment

There are three steps as follows. The third step is optional:

    1. Install the latest stable version of Python runtime ),. There are three notes: first, the Linux system should bring Python; second, after installing python on Windows, add the python directory to the system path; and third, the Application Server version on the App Engine is 2.6.5. Therefore, do not add the features introduced after Python 2.6.5 is added to the project.
    2. Install the App Engine SDK ,. There are two points to note: first, after installing the App Engine SDK on Windows, you also need to add the SDK directory to the system path. Second, you do not need to install the App Engine SDK on Linux, you only need to decompress the package and place it in the appropriate directory.
    3. Install the eclipse and pydev plug-ins. This step is optional for those who just want to try the App Engine. However, due to the mature development environment of Eclipse, added the built-in code coloring, automatic prompts, and powerful debugging of pydev, and added complete support for Google App Engine in version 1.4.6, therefore, it is necessary for those who are preparing to develop the App Engine program. For more information, click here.

 

Although you are not familiar with python, it does not affect your understanding of this Article. If you want to learn python in depth, click here to read the Chinese version of dive into python. In addition, I personally recommend that you use Linux as the App Engine Development Platform, because it comes with many tools and complete command lines.

Initialize a project

The App Engine SDK comes with a project template named "new_project_template". There are three files in the Project template:

    1. App. yaml: this file is the configuration file of the entire project. It is similar to the Web. xml file in the Java Web project.
    2. Main. py: This Python script is the "Hello World" file of the app engine. It mainly demonstrates how to handle the most basic Web requests.
    3. Index. yaml: This file sets the index of the data model created by the project. Note that this file is generally automatically maintained by the App Engine system. When the App Engine is debugging or deploying an application, it will analyze the data model contained in the application to determine whether to add a new index to the data.

 

We can initialize the project by copying this project template. Next, we will gradually edit and create each file, and the first file to be edited is app. yaml.

Edit app. yaml

As mentioned above, app. yaml is the core configuration file of the entire project. Its suffix "yaml" indicates that this file is based on the yaml language, and yaml is a highly readable data serialization language. Compared with XML, it is more readable and supports a wide range of data types. The following figure shows the edited app. yaml.

Application: Sample
Version: 1
Runtime: Python
Api_version: 1

Handlers:
-URL :/.*
Script: Main. py

Code 1. app, yaml

You can configure the following parameters in APP. yaml:

    1. Application name: the corresponding location is "application", which is used to set the name of the entire project. During local debugging, the project name can be any string, however, when you deploy this project on the cloud App Engine platform, make sure that the Application name is the same as that created on the app engine management interface, therefore, the application name must be unique across the App Engine and cannot conflict with the name of a project created by another user.
    2. Project version: The corresponding location is "version", which is used to configure the application version number. You can use it to manage the application version. Because this example is newly created, the version number is 1.
    3. Runtime: the corresponding position is "RunTime", which is used to set the development language of the project. The current project has two development languages: Python and Java, because this example uses python, enter "Python" here ".
    4. API version: The corresponding location is "api_version". It refers to the version number of the App Engine API used. Currently, it is 1.
    5. Class for processing Web requests: The corresponding location is "handlers". This part is configured with the correspondence between the URL and the Python script, meaning that when the App Engine receives a Web request, it calls the corresponding script according to its url. In the above example, when the URL is "/. * ", the main..

 

Create an HTML file

The following is the code of index.html:

<HTML>
<Head>
<Meta content = "text/html; charset = UTF-8" http-equiv = "Content-Type"/>
<Title> App Engine demo </title>
</Head>
<Body>
<Form method = "Post" Action = "/">
Article name: <input type = "text" name = "title" size = 30/> <br>
Keywords: <input type = "text" name = "tags" size = 30/> <br>
Content: & nbsp; <textarea name = "content" Cols = "30" rows = "5"> </textarea> <br>
<Br>
<Input type = "Submit" name = "Submit" value = "Submit">
</Form>
</Body>
</Html>

Code 2. index.html

This is the HTML page corresponding to the example. It consists of two text boxes and a textarea to allow users to enter the blog article name, keyword, and content. After the user inputs the three data, click the submit button to post the input data to the backend server and process it with the Python script corresponding to the URL, that is, the above "Main. PY"

Write database code

Before explaining the database code in the example, we will introduce the entity model and data type of App Engine.

Entity model

The main data model of App Engine is called "entity model". An entity consists of a primary key and a set of attributes. The entity model is implemented by inheriting the model class, in addition, each attribute can be selected from multiple data types.

Data Type

The main basic data types include string, bytestring, Boolean, integer, float, and datetime), list, stringlist, text, blob, and reference type used to represent the relationship between objects ).

In addition to the basic data types, you can also inherit the expando class to customize a new data type.

Blog table structure

The following table describes the structure of the blog table used in the example:

Attribute name Type
Title String (string)
Tags Stringlist (string List)
Content Text)

Table 1. Structure of the blog table

The blog table has three fields: String-type title attribute, string list-type tags attribute, and text-type content attribute. below is the blogdb for creating the blog table. the code of the py script.

From Google. appengine. Ext import DB

Class blog (db. Model ):
Title = dB. stringproperty ()
Tags = dB. stringlistproperty ()
Content = dB. textproperty ()

Def save (self, _ title, _ tags, _ content ):
Blog = blog ()
Blog. Title = _ title
Blog. content = _ content
If _ tags:
Blog. tags = _ tags. Split ("")
Else:
Blog. tags = []
Blog. Put ()

Code 3. blogdb. py

This script consists of two parts. One is to inherit the database. the model class creates the blog entity model and declares the three attributes of title, tags, and content. The second is to define a method named "save". In this method, first, create a new blog entity, and insert the input parameters _ title, _ tags, and _ content into the newly created blog entity, the put method of the object is used to save the object in the database. Other classes can store blog-related data by calling the Save method in the blog class.

Add web Processing Method

In this example, you need to add the code used to process two Web requests: one is the code used to display index.html, that is, the code used to process the access URL "/retrieve the getrequest, and the other is to save the blog data entered by the user on index.html, that is, it is used to process the POST request for accessing the URL "/". The following is the main. PY code:

From Google. appengine. Ext import webapp
From Google. appengine. Ext. webapp. util import run_wsgi_app
From Google. appengine. Ext. webapp import Template
Import OS
Import CGI
From blogdb import blog
From Google. appengine. Ext import DB

Class main (webapp. requesthandler ):
Def get (Self ):
Path = OS. Path. Join (OS. Path. dirname (_ file _), 'index.html ')
Self. response. Out. Write (template. Render (path, [])
Def post (Self ):
_ Title = CGI. Escape (self. Request. Get ('title '))
_ Tags = CGI. Escape (self. Request. Get ('tags '))
_ Content = CGI. Escape (self. Request. Get ('content '))
Blog = blog ()
Blog. Save (_ title, _ tags, _ content)
Self. response. Out. Write ('Save successfully ')

Application = webapp. wsgiapplication ([('/', main)], DEBUG = true)

Def main ():
Run_wsgi_app (Application)

If _ name _ = "_ main __":
Main ()

Code 4. Main. py

 

From top to bottom, the main. py code can be divided into three parts:

    1. Get method: This method reads index.html through the python ossag, and sends the data of the retrieved index.html file to the browser through the HTTP responsestream. In this way, index.html is displayed on the client's browser.
    2. POST method: This method obtains the input data of title, tags, and content from the input HTTP request stream, and calls the Save aspect of the blog entity model to save it, send the message "Save successfully" to the client.
    3. Register the main class: Initialize webapp in the code. the wsgiapplication class corresponds to the main class and the URL "/". For example, the client sends a GET request to the URL "/", the system will call the get method of the main class to process this request. Note that the correspondence between the URL and the class is further set after the setting in APP and yaml.

 

The Code section is complete. The following describes how to test and deploy this project.

 

Testing and deployment

The following three steps are involved:

Local Test

Call the dev_appserver.py script in the SDK to start the local development environment. The specific command format is "dev_appserver.py sample". Here "sample" refers to the project name. If the pydev plug-in exists, you can start the debugging mode of the Local Development Environment on Eclipse. After the environment is started successfully, you can test the basic functions of this project through the URL http: // localhost: 8080.

Create an application

Figure 1. My applications

Click "Create an application" on "My applications" in the Management Interface (https://appengine.google.com/) of the App Engine to enter the "Create an application" interface.

Figure 2. Create an application

Then, in the "Create an application" interface, enter the application name or ID (which must be unique across the App Engine) in the "applcation identifier" text box ), enter the full name of the application in the "Application title" text box, and click "create applcation" to create the application on the App Engine.

Publish an application

Use appcfg In SDK. the py script deploys the application on the App Engine platform. The specific command format is "appcfg. PY update sample/", here" Sample/"represents the directory where the project is located. After deployment, you can access and manage the application through the App Engine Management Interface.

 

References:

    1. Yaml introduction.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.