Use Google App Engine to write a message board Program (1)

Source: Internet
Author: User
Document directory
  •  

I will share my experiences with Google App Engine. The entire article includes the following parts:

· Introduction to Google App Engine
· Development Environment Configuration
· Start, write Hello, World! Test
· The object entity of App Engine. You can use Datastore API to add and display the message content.
· Use the Users API to create user logon and administrator identification, reply to and delete messages
· Make your program more robust, capture and handle exceptions and errors
· Use templates for exciting scenarios!
· How to use static files in a program, such as CSS, scripts, images, and videos.
· Free test server http://application-id.appspot.com for uploading apps to Google App Engine

This is the first part of the article.

What is Google App Engine?
Google App Engine is a hosted service that allows you to build Web applications locally using Google infrastructure. After the service is completed, you can deploy the applications on Google infrastructure (Google's server environment ). Google App Engine is divided into free and paid versions. The free version provides a quota system that limits the free storage, CPU, and bandwidth available for applications. Currently, the free version includes three applications/developers, 2000 MB of storage/applications, and emails/day (24 hours in a row) 10 GB inbound bandwidth, 10 GB outbound bandwidth, 200 m cpu g week, 650 k HTTP request, 2.5 M Datastore API call, and 160 k URL Fetch API call. This is enough for us to create a small learning experiment program.
Currently, Google App Engine only provides Python language support, and more languages may be supported in the future (it is estimated that the short term is unlikely ).
Google App Engine SDK can be viewed as similar. the same platform as the. NET Framework (this metaphor is not appropriate, But you can understand it first). This environment runs on Google servers, google has made many restrictions and adjustments to its security and performance. In addition, Google App Engine supports Python selectively, and you cannot use all the features of Python.

For more information about Google App Engine, refer to Google's Web development tool: AppEngine


Development Environment configuration (the system environment described in this article is windows ):

1. Google App Engine is running on Python2.5 basis, if Python 2.5 is not installed, please download and install the corresponding operating system version from the official Python website (http://www.python.org.
2. Download the App Engine SDK (http://code.google.com/appengine/downloads.html ). Before writing an article, the latest SDK version is 1.1. After downloading and running the installation program, follow the prompts.
3. There are two important commands to help us process the operating program.
· Dev _ appserver. py, Web server development
Http://code.google.com/appengine/docs/thedevwebserver.html)
· Appcfg. py, used to upload your program to App Engine
Http://code.google.com/appengine/docs/appcfgpy.html)
After the SDK is installed normally, the Windows Installer directly places these commands in the command path. After installing the SDK, you can directly run these commands in the command line window.

Start, write Hello, World! Test

1. Create a directory named helloworld. All files mentioned in this program are stored in this directory.
Go to the helloworld directory, create a text file named helloworld. py, and add the following code:

#-*-Coding: UTF-8 -*-
Print 'content-Type: text/plain'
Print''
Print 'hello, world! '

This Python script responds to a request, which includes an HTTP header describing the content type and a blank line.
And "Hello world !".

2. Create a configuration file
The App Engine application has a configuration file named app. yaml. This file describes which processor (handler) script corresponds to which URL. In the helloworld directory, create a file named app. yaml and add the following content:

Application: helloworld
Version: 1
Runtime: python
Api_version: 1

Handlers:
-Url :/.*
Script: helloworld. py

The syntax for this file is YAML (http://www.yaml.org /). To view the complete list of configuration options, see the app. yaml reference (http://code.google.com/appengine/docs/configuringanapp.html ).
You can use this file as the web. config file of asp.net, mainly to configure the necessary information of the program.

3. Test
On the desktop, click Start> attachment> command prompt. In the command prompt state, run the following command to start the Web server. The path is the helloworld directory:
Dev_appserver.py helloworld/
Note: It is outside the directory, and the directory name cannot contain spaces
Normally, the Web server starts running and can listen to requests from port 8080. Test the program by accessing the following address in a browser. Http: // localhost: 8080/. If everything is normal, the browser displays Hello world! . You can edit the helloworld. py file and change Hello, world! With other characters, refresh the browser to see the changes. To disable the Web server, press Control-C (or Control-Break) when the terminal window is activated ). Or close the window directly.

Next we start to write a message board program.

1. Create a directory named messageboard, create an app. yaml file, and add the following content:

Application: messageboard
Version: 1
Runtime: python
Api_version: 1

Handlers:
-Url :/
Script: messageboard. py

2. Create a messageboard. py and add the following content:

#-*-Coding: UTF-8 -*-

Import OS
Import re
Import cgi
Import datetime
Import wsgiref. handlers
From google. appengine. ext import db
From google. appengine. api import users
From google. appengine. ext import webapp
From google. appengine. ext. webapp import template


#-*-Coding: UTF-8-*-indicates that the file is in UTF-8 format (you must save the file as UTF-8 when saving it). The import Statement is equivalent to the using of asp.net, import the required class library to the program. * starts with the library in the Google App Engine SDK. For details about the differences between import and from, refer to the python documentation.

3. Continue. Create an object class and add the following code to messageboard. py.

Class Message (db. Model ):
Title = db. StringProperty ()
Nickname = db. StringProperty ()
Email = db. EmailProperty ()
Website = db. LinkProperty ()
Content = db. StringProperty (multiline = True)
Reply = db. StringProperty (multiline = True)
Ipaddress = db. StringProperty ()
Adddate = db. DateTimeProperty (auto_now_add = True)


This class defines a Model of the message information, such as the message title, nickname, email, and other attributes, in which db. code such as StringProperty () specifies the Data Type of the property, db. stringProperty () indicates that this property is a string, db. stringProperty (multiline = True) is a db with the multiline = True parameter. stringProperty type. You can specify a property to store multiple lines of text. Db. emailProperty () and db. linkProperty () is the property type defined by the SDK for us. The specified property must be in the Email format and hyperlink format, with the auto_now_add = True parameter. the DateTimeProperty type specifies that when an object is created, if the application does not assign other values, the new object will be automatically assigned a date time. For more information, see (http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html)

4. Add the following code to messageboard. py:

Class MainPage (webapp. RequestHandler ):
Def get (self ):
Self. response. out. write ("""
<Form action = "/sign" method = "post">
<Div> <input type = "text" name = "title"/> </div>
<Div> <input type = "text" name = "nickname"/> </div>
<Div> <input type = "text" name = "email"/> </div>
<Div> <input type = "text" name = "website"/> </div>
<Div> <textarea name = "content" rows = "3" cols = "60"> </textarea> </div>
<Div> <input type = "submit" value = "Sign Guestbook"> </div>
</Form>
</Body>
</Html> """)

Class Add (webapp. RequestHandler ):
Def post (self ):
Message = Message ()
Message. title = self. request. get ('title ')
Message. nickname = self. request. get ('nickname ')
Message. email = self. request. get ('email ')
Message. website = self. request. get ('website ')
Message. content = self. request. get ('content ')
Message. put ()
Self. redirect ('/')

Def main ():
Application = webapp. WSGIApplication ([('/', MainPage), ('/sign', Add)], debug = True)
Wsgiref. handlers. CGIHandler (). run (application)

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

The code added this time is a little more, mainly in two classes. One is the form used by MainPage to display the message, and the program directly writes the hard code to the page; the Add class stores submitted forms in the database. Message. put () is used to save our Message object to the database and go to the start page.
The main function is used to accept requests and specify the processor for request matching (MainPage class and Add class). For example, when a webapp receives an http get request for the URL "/", it instantiates the MainPage class and calls the get method of this instance. The debug = true parameter can capture errors or exceptions and display them.
The application itself is presented by the webapp. WSGIApplication instance. The Code uses the wsgiref module from the Python standard library to run WSGIApplication, which is a CGI adaptation. For more information about this module, visit the wsgiref module documentation (http://docs.python.org/lib/module-wsgiref.html ). For more information about webapp, see webapp reference (http://code.google.com/appengine/docs/webapp ).

5. Next, modify the app. yaml file.

Application: messageboard
Version: 1
Runtime: python
Api_version: 1

Handlers:
-Url :/
Script: messageboard. py

-Url:/add
Script: messageboard. py

Now you can run dev_appserver.py messageboard/for debugging. Enter http: // localhost: 8080/in the browser to view the message form and enter some content for testing. Clicking the submit button does not change. In fact, the data is stored. Develop a Web server and use a local database to test your application, that is, use temporary files. As long as the temporary file is wrong, the data will always exist, and the Web server will not reset these files
Unless you want. If you want the development server to clear the database in advance at startup, add the -- clear_datastore option when starting the server:
Dev_appserver.py -- clear_datastore messageboard

6. How can we display the stored data? Modify Your MainPage class as follows:

Class MainPage (webapp. RequestHandler ):
Def get (self ):
Messages = db. GqlQuery ("SELECT * FROM Message order by adddate desc limit 10 ")
For message in messages:
Self. response. out. write ('% s message on % s:' % (message. nickname, message. adddate ))
Self. response. out. write ('Self. response. out. write ("""
<Form action = "/add" method = "post">
<Div> title: <input type = "text" name = "title"/> </div>
<Div> nickname: <input type = "text" name = "nickname"/> </div>
<Div> email: <input type = "text" name = "email"/> </div>
<Div> URL: <input type = "text" name = "website"/> </div>
<Div> content: <textarea name = "content" rows = "3" cols = "60"> </textarea> </div>
<Div> <input type = "submit" value = "submit"> </div>
</Form>
</Body>
</Html> """)

Look at this message = db. gqlQuery ("SELECT * FROM Message order by adddate desc limit 10"), Google App Engine queries databases using statements similar to SQL statements called gql, this query returns the Message object model of the added information. Next
For message in messages:
Self. response. out. write ('% s message on % s:' % (message. nickname, message. adddate ))
Self. response. out. write ('This is used to traverse the messages object set and write the content ..
GQL has a high degree of similarity with SQL, where GQL has added some special syntaxes that have adapted to the App Engine environment to view the complete GQL and query API description, see Data Storage reference (http://code.google.com/appengine/docs/datastore ).

Debug our program. If the test server is not closed, refresh the browser (http: // localhost: 8080/) to see the submitted message, you can try to submit a message and view the changes.
Note: If the entered Email and Url do not conform to the standard, the test server will capture and display the error. For example, BadValueError: Invalid URL: ww.124.cm indicates that the added Url is incorrectly formatted, we can write processing code based on this mechanism to make our programs more robust and secure.

Through the above learning, we initially built a program that can run in the local App Engine environment. Of course, it is still very immature, the program is not robust, the interface is unfriendly, and there is no distinction between user identities, storage data cannot be managed. The next article will help you solve these problems. The next article will be announced:

  • · Use the Users API to create user logon and administrator identification, reply to and delete messages
    · Make your program more robust, capture and handle exceptions and errors
    · Use templates for exciting scenarios!
    · How to use static files in a program, such as CSS, scripts, images, and videos.
    · Free test server http://application-id.appspot.com for uploading apps to Google App Engine

Download complete code

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.