Google App Engine                                                            Property is the superclass for data model def...
get_current_user()                                                                User   invalid_email_reason(email_addres...
Upcoming SlideShare
Loading in …5

Google app engine cheat sheet


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Google app engine cheat sheet

  1. 1. Google App Engine Property is the superclass for data model definitions. Query uses objects and methods to prepare queries. Python SDK 1.2.2 REVISION 1.1 05.21.09 CONSTRUCTOR CONSTRUCTOR class Property(verbose_name=None, name=None, Datastore google.appengine.ext.db class Query(model_class) indexed=True, default=None, choices=NoneA scalable storage and query engine. required=False, validator=None) INSTANCE METHODS filter(property_operator, value) selfPACKAGE FUNCTIONS CLASS ATTRIBUTES order(property) selfget(key) Model instance data_type ancestor(model_instance|key) selfYou can also pass multiple keys and it will return multiple Model instances. INSTANCE METHODS get() model instance or Noneput(model_instance) Key object default_value() value fetch(limit, offset=0) list of model instancesYou can also pass multiple model instances and it will return multiple keys. validate(value) value or exception count(limit=None) integerdelete(model_instance|key) empty(value) boolrun_in_transaction(function, *args, **kwargs) TYPE AND PROPERTY CLASSES Key represents a unique key for a datastore entity.run_in_transaction_custom_retries(retries, function, Property Class Value Type Sort Order CONSTRUCTOR *args, **kwargs) StringProperty str Unicode (str is treated as ASCII) class Key(encoded=None) unicodeModel is the superclass for data model definitions. CLASS METHODS ByteStringProperty db.ByteString byte orderCONSTRUCTOR Key.from_path(*args, **kwds) BooleanProperty bool False True This example creates a key for an Address entity with the numeric ID 9876 whose par-class Model(parent=None, key_name=None, **kwds) ent is a User entity with the named key ‘Boris’: IntegerProperty int NumericCLASS METHODS long k = Key.from_path(‘User’, ‘Boris’, ‘Address’, 9876)get(key) Key object FloatProperty float Numeric INSTANCE METHODSget_by_id(id, parent=None) Model instance DateTimeProperty datetime.datetime Chronological app() Application name (string)You can also pass multiple ids and it will return multiple Model instances. DateProperty kind() Kind (string)get_by_key_name(key_name, parent=None) see above TimeProperty ListProperty list If ascending, by least element; if id() Numeric ID (int)You can also pass multiple ids and it will return multiple Model instances. StringListProperty descending, by greatest element name() Entity name (string)get_or_insert(key_name, **kwds) see above ReferenceProperty db.Key By path elements (kind, ID or name) id_or_name() Numeric ID(int) or name (string) SelfReferencePropertyall() Query object has_id_or_name() bool UserProperty user.User By email addressgql(query_string, *args, **kwds) GQLQuery object parent() KeyExamples: BlobProperty db.Blob (not orderable)s = Story.gql(“WHERE title = :1”, “The Little Prince”) TextProperty db.Text (not orderable) GQL is a SQL-like language for retrieving entities.s = Story.gql(“WHERE title = :title”, title=”The Little Prince”) SYNTAX CategoryProperty db.Category Unicode WHERE condition [AND condition ...]kind() Kind LinkProperty db.Link Unicode ORDER BY property [ASC | DESC] [,property [ASC | DESC]…]properties() dict LIMIT [offset,]count EmailProperty db.Email UnicodeINSTANCE METHODS OFFSET offsetkey() Key GeoPtProperty db.GeoPt By latitude, then longitude condition := property { | = | | = | = | != } valueput() Key IMProperty db.IM Unicode condition := property IN listdelete() condition := ANCESTOR IS entity or key PhoneNumberProperty db.PhoneNumber Unicode list := (value, …)is_saved() bool PostalAddressProperty db.PostalAddress Unicode Note that :NUMBER and :NAME are substitutions for positional and keyword argu-parent() Model ments, referrring to *args (starting at 1) and **kwds respectively. See RatingProperty db.Rating Unicodeparent_key() Key Model.gql() for example usage. Key-only queries are supported using eitherto_xml() XML SELECT __key__.
  2. 2. get_current_user() User invalid_email_reason(email_address, field) stringMemcache google.appengine.api.memcache is_current_user_admin() bool is_email_valid(email_address) BooleanA distributed in-memory data cache that can be used in front of or in EXCEPTIONS send_mail(sender, to, subject, body, **kw)place of persistent storage. Error, UserNotFound(), RedirectTooLongError() send_mail_to_admins(sender, subject, body, **kw)FUNCTIONS EXCEPTIONSset(key, value, time=0, min_compress_len=0) bool URL Fetch google.appengine.api.urlfetch Error, BadRequestError, InvalidEmailError, The URLFetch API can retrieve data using HTTP and HTTPS URLs. InvalidAttachmentTypeError, MissingRecipientsError,True means done while False means an error occured. MisssingSenderError, MissingSubjectError,Note that a Memcache key is an arbitrary string, not an instance of db.Key. MissingBodyError FUNCTIONSset_multi(mapping, time=0, key_prefix=’’, list MESSAGE FIELDS (**fields) fetch(url, payload=None, method=GET, Response object min_compress_len=0) headers=(), allow_truncated=False, sender, to, cc, bcc, reply_to, subject, body, html,get(key) value follow_redirects=True, deadline=5) attachmentsget_multi(keys, key_prefix=’’) dict RESPONSE OBJECTSdelete(key, seconds=0) error code content Images google.appengine.api.imagesdelete_multi(keys, seconds=0, key_prefix=’’) bool The body content of the response. Provides image manipulation using the Picassa Web infrastructure.add(key, value, time=0, min_compress_len=0) bool content_was_truncatedadd_multi(mapping, time=0, key_prefix=’’, list Image represents image data to be transformed. True if the allow_truncated parameter to fetch() was True and the min_compress_len=0) response exceeded the maximum response size. In this case, the content attribute CONSTRUCTORreplace(key, value, time=0, min_compress_len=0) bool contains the truncated response. class Image(image_data)replace_multi(mapping, time=0, key_prefix=’’, list status_code PROPERTIES min_compress_len=0) The HTTP status code. width, heightincr(key, delta=1) int, long or None headers INSTANCE METHODSdecr(key, delta=1) int, long or None The HTTP response headers, as a mapping of names to values. resize(width=0, height=0)flush_all() bool EXCEPTION CLASSES crop(left_x, top_y, right_x, bottom_y)get_stats() dict Error, InvalidURLError, DownloadError, The four number arguments are multiplied by the image’s width and height to define ResponseTooLargeError a bounding box that crops the image. The upper left point of the bounding box is atUser google.appengine.api.users (left_x*image_width, top_y*image_height) the lower right point is atAn App Engine application can redirect a user to a Google Accounts (right_x*image_width, bottom_y*image_height).page to sign in register, or sign out. Mail google.appengine.api.urlfetch rotate(clockwise_degrees) Provides two ways to send an email message: the mail.send_mail() horizontal_flip() function and the EmailMessage class.User represents a user with a Google account. vertical_flip()CONSTRUCTOR EmailMessage represents an email message. im_feeling_lucky()class User(email=None) composite(inputs, width, height, color=0, CONSTRUCTORINSTANCE METHODS output_encoding=images.PNG) class EmailMessage(**fields)email() string histogram(image_data) listnickname() string INSTANCE METHODS execute_transforms() Image Object check_initialized() user_id() string FUNCTIONS initialize(**fields)This can be the user id of an email address or the full email address if it differs from the They are the same as the instance methods, but they can be performedapplication’s auth domain ( or the Google Apps domain for which the applica- is_initialized() bool directly on image_data. There is no need to queue them using execute_trans-tion is registered). forms(). They include an additional parameter which is the expected send() output_encoding image type, which defaults to PNG.FUNCTIONS FUNCTIONScreate_login_url(dest_url) string (URL) EXCEPTIONS check_email_valid(email_address, field)create_logout_url(dest_url) string (URL) Error, TransformationError, BadRequestError, This raises an InvalidEmailError when the email_address is invalid. NotImageError, BadImageError, LargeImageError