Google App Engine protorpc Python API Overview

Source: Internet
Author: User

Lai Yonghao (http://laiyonghoa.com
)

Note: Gae SDK 1.5.1 was released a few days ago. One of the new features is that the python SDK has added the protorpc API. I am not very interested in Gae, but recently I was writing RPC based on Google protobuf (different from my RPC based on TCP), so I checked the overview of protorpc with great interest, later, I translated it in a simple way, but it was not a sentence-by-Sentence Translation. If you are confused, please refer to the original article (the original article is also changing. I translated it from the version of June 25, 2011, if later updated, not on the number, not responsible): http://code.google.com/appengine/docs/python/tools/protorpc/overview.html

Protorpc is a simple solution for sending and receiving HTTP-based Remote Procedure Call (RPC) services. The so-called RPC service provides a bunch of message types and remote methods to expand the interaction between applications and Web applications in a structured manner. Because messages and services can only be defined using the python programming language, it is easier to develop services, test services, and achieve better scalability on the App Engine.
When protorpc is used for any HTTP-based RPC, some common application scenarios include:

  1. Publish Web APIs used by a third party
  2. Create a structured Ajax backend
  3. Clone long-running server interaction

You can define any number of protorpc remote methods in a single Python class. Each remote method accepts a request (including a specific set of parameters) and returns a specific response. All requests and responses are user-defined classes, which are also called messages.

 

Experimental!

Protorpc is an experimental, brand-new, and fast-changing new feature of App Engine. Do not use it in business-critical applications. We will tell you when it is fully available.

 

Hello world of protorpc

This section demonstrates receiving a message (including the username hellorequest. my_name) from the remote end and returning a response (helloresponse. Hello ).
From Google. appengine. EXT import webapp <br/> from Google. appengine. ext. webapp import util <br/> from protorpc import messages <br/> from protorpc. webapp import service_handlers <br/> from protorpc import remote <br/> package = 'hello' <br/> # create the request string containing the user's name <br/> class hellorequest (messages. message): <br/> my_name = messages. stringfield (1, required = true) <br/> # creat E The response string <br/> class helloresponse (messages. message): <br/> Hello = messages. stringfield (1, required = true) <br/> # create the RPC service to exchange messages <br/> class helloservice (remote. service): <br/> @ remote. remote (hellorequest, helloresponse) <br/> def Hello (self, request): <br/> return helloresponse (Hello = 'Hello there, % s! '% <Br/> request. my_name) <br/> # map the RPC service and path (/Hello) <br/> service_mappings = service_handlers.service_mapping (<br/> [('/hello', helloservice ), <br/>]) <br/> # apply the service mappings to webapp <br/> application = webapp. wsgiapplication (service_mappings) <br/> def main (): <br/> util. run_wsgi_app (Application) <br/> If _ name _ = '_ main _': <br/> main ()

Start your protorpc journey

Here we use the message board example (http://code.google.com/appengine/docs/python/gettingstarted/) of the App Engine Getting Started Guide (Python ). You can access this message board online (already included in the python SDK), write a message, and view all users' messages.
Next, we will apply the protorpc to this basic message board, so that the Web application can access its data. However, this tutorial only covers how to use protorpc to expand the message board function. In fact, you can do more, for example, you can write a tool to read all the messages submitted by the user or create a chart showing the number of messages each day. Depending on the specific application, you can use protorpc at will. What's important is that protorpc allows you to freely toss your data.
Everything starts with creating a file named postservice. py, where all remote methods for accessing the application data of the message board are implemented.

Create a postservice Module

Step 1: create a file named postservice. py in the application directory. It implements two methods: one for remote data submission and the other for remote data retrieval.

Burn, message!

A message is the basic data type of protorpc. It defines a message by declaring a subclass inherited by message, and then defines the class attributes corresponding to the Message field.
The message board service allows users to submit a message, so define a message to indicate a message:
From protorpc import messages <br/> class note (messages. message): <br/> text = messages. stringfield (1, required = true) <br/> when = messages. integerfield (2)
The note message defines two fields: Text and when. Each field has its own type. For example, the text field type is raised to a unicode string to indicate the content submitted on the message board page. The when field is an integer, used to indicate the time stamp submitted by the user. In addition:

  • Each field has a unique value (for example, text is 1 and when is 2), which is the field identifier used by the underlying network protocol.
  • Define text as a required field. Each field is optional by default. Therefore, you must use required = true to customize it as a required field.

You can assign values to fields by using the Construction Function of the Note class:
# Import the standard time Python library to handle the timestamp. <br/> Import time <br/> note_instance = Note (text = u'hello guestbook! ', When = int (Time. Time ())
You can also perform the same operations on common Python attributes to read and write segments. For example, the following code can change the message:
Print note_instance.text <br/> note_instance.text = u'good-bye guestbook! '<Br/> Print note_instance.text <br/> # which outputs the following <br/> Hello guestbook! <Br/> good-bye guestbook!

Define Service

A service is a class inherited from the service base class. The remote method of a service is identified by the remote modifier. Each method of the Service accepts a single message as a parameter and returns a message as a response.
Now let's define the first method of postservice. If you are not ready, remember to create the postservice. py file in your app directory first, or if you think it is necessary to read the message board tutorial (http://code.google.com/appengine/docs/python/gettingstarted ). Like the message board tutorial, postservice uses guestbook. greeting to store submitted data.
Import datetime <br/> from protorpc import message_types <br/> from protorpc import remote <br/> Import guestbook <br/> class postservice (remote. service): <br/> # Add the remote decorator to indicate the service methods <br/> @ remote. remote (note, message_types.voidmessage) <br/> def post_note (self, request): <br/> # If the note instance has a timestamp, use that timestamp <br/> If request. when is not none: <br/> when = datetime. datetime. utcfromtimestamp (request. when) <br/> # else use the current time <br/> else: <br/> when = datetime. datetime. now () <br/> note = guestbook. greeting (content = request. text, date = when) <br/> note. put () <br/> return message_types.voidmessage ()
The remote decorator has two parameters:

  • Request type. post_note () accepts a note instance as the request.
  • Response type. The protorpc has a built-in type called voidmessage (in protorpc. defined in the message_types module), which indicates messages without fields. Therefore, post_note () does not actually return anything meaningful to the caller.

Because note. when is an optional field, so the caller can not assign a value to it. At this time, the value of when is none. When note. the value of when is none, and post_note () uses the time when the message is received as the timestamp.
The Response Message is instantiated by a remote method. This is usually done when the remote method needs to return.

Registration Service

You can use the webapp framework (http://code.google.com/appengine/docs/python/tools/webapp/) of App Engine to publish new services. Protorpc has a small library (protorpc. service_handlers) to simplify this process. Create a service. py file in the application directory and copy the following code:
From Google. appengine. EXT import webapp <br/> from Google. appengine. ext. webapp import util <br/> from protorpc import service_handlers <br/> Import postservice <br/> # register mapping with application. <br/> application = webapp. wsgiapplication (<br/> service_handlers.service_mapping (<br/> [('/postservice', postservice. postservice)]), <br/> DEBUG = true) <br/> def main (): <br/> util. run_wsgi_app (Application) <br/> If _ name _ = '_ main _': <br/> main ()
Then add the following code to the app. yaml file:
-URL:/postservice. * <br/> Script: services. py
You can create basic webapp services ~

Test the service through command line

After creating a service, you can use curl or similar command line tools for testing:
# After starting the development web server: <br/> % curl-H/<br/> 'content-type: application/json'/<br/>-d {"text": "Hello guestbook! "} '/</P> <p> http: // localhost: 8080/postservice. post_note

If an empty JSON message is returned, the message is submitted successfully. You can view the message in the browser (http: // localhost: 8080.

Add message Fields

Now you can submit a message to postservice, and then add a new method. Define a request message in postservice. py, which has some default values and enumeration fields that have not been touched before (used to tell the server how to sort messages ). Let's add the following code before the postservice class:
Class getnotesrequest (messages. message): <br/> Limit = messages. integerfield (1, default = 10) <br/> on_or_before = messages. integerfield (2) <br/> class order (messages. enum): <br/> when = 1 <br/> text = 2 <br/> order = messages. enumfield (Order, 3, default = order. when)
The limit field in the message indicates the maximum number of messages requested. The default value is 10 (specified by the default = 10 keyword parameter ).
The order field introduces an enumfield class, which allows the value of the enum field type to be strictly limited to the defined symbol value range. Here, the Order field specifies how messages are sorted and displayed on the server. To define the enumerated value, you need to create a subclass of The enum class. Each of its class attributes should be a unique number and then be converted to an instance of Enumeration type that can be accessed through the class.
Print 'enum Value Order. % s has Number % d' % (order. When. Name, <br/> order. When. Number)
In addition to its name and number attributes, the enum value also has a "special skill" to easily convert its name and number, such as converting a value to a string or INTEGER:
Print 'enum Value Order. % s has Number % d' % (order. When, <br/> order. When)
The declaration of an enumerated field is similar to that of other fields. In addition to specifying its enumeration type in the first parameter, the enumerated field can also have a default value.

Define Response Message

Now define the Response Message of get_notes. This response should obviously contain a set of note messages, which can include other message consumption:
Class notes (messages. Message): <br/> Notes = messages. messagefield (note, 1, repeated = true)
Notes. the notes field is a repeated field (indicated by the repeated = true keyword parameter). The value of the repeated field is a list. In this example. notes is a list containing multiple note instances. The list is automatically created and cannot be assigned to none.
Example of how to create a notes object:
Response = Notes (notes = [Note (text = 'this is note 1'), <br/> note (text = 'this is note 2')]) <br/> Print 'the first note is: ', response. notes [0]. text <br/> Print 'The second note is: ', response. notes [1]. text

Implement get_notes

Now add the get_notes () method to the postservice class:
Import datetime <br/> from protorpc import remote <br/> class postservice (remote. service): <br/>... <br/> @ remote. remote (getnotesrequest, notes) <br/> def get_notes (self, request): <br/> query = guestbook. greeting. all (). order ('-date') <br/> If request. on_or_before: <br/> when = datetime. datetime. utcfromtimestamp (<br/> request. on_or_before) <br/> query. filter ('date <= ', when) <br/> Notes = [] <br/> for note_model in query. fetch (request. limit): <br/> If note_model.date: <br/> when = int (time. mktime (note_model.date.utctimetuple () <br/> else: <br/> when = none <br/> note = Note (text = note_model.content, when = when) <br/> notes. append (Note) <br/> If request. order = getnotesrequest. order. text: <br/> notes. sort (Key = Lambda Note: note. text) <br/> return notes (notes = notes)

Related Article

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.