[google-app-engine-oil] push by ping.nsr...@gmail.com - Document the rest of codes in oildrum/lib/gaeo, with TODO added for fu... on 2010-11-26 15:44 GMT

3 views
Skip to first unread message

google-app...@googlecode.com

unread,
Nov 26, 2010, 10:45:38 AM11/26/10
to google-app...@googlegroups.com
Revision: 456f959fba
Author: Ping Yeh <pi...@pingyeh.net>
Date: Fri Nov 26 07:12:06 2010
Log: Document the rest of codes in oildrum/lib/gaeo, with TODO added for
functions/methods that I don't understand.
http://code.google.com/p/google-app-engine-oil/source/detail?r=456f959fba

Modified:
/oildrum/lib/gaeo/app.py
/oildrum/lib/gaeo/controller.py
/oildrum/lib/gaeo/model.py
/oildrum/lib/gaeo/router.py
/oildrum/lib/gaeo/session.py
/oildrum/lib/gaeo/utils.py

=======================================
--- /oildrum/lib/gaeo/app.py Thu Nov 25 07:32:57 2010
+++ /oildrum/lib/gaeo/app.py Fri Nov 26 07:12:06 2010
@@ -99,7 +99,8 @@
"""Gets a list of argument names provided in either the query
string or
POST body.

- Returns: a list of strings for the argument names.
+ Returns:
+ A list of strings for the argument names.
"""
return list(set(self.params.keys()))

@@ -337,14 +338,14 @@
write(body_string) callable.

Args:
- status: status string of the form "200 OK".
- headers: a list of (header name, header value) tuples for HTTP header
- to be written out.
- exc_info: [optional] exception information 3-tuple, should be
supplied
- only if called by an error handler.
+ status: status string of the form "200 OK".
+ headers: a list of (header name, header value) tuples for HTTP
header
+ to be written out.
+ exc_info: [optional] exception information 3-tuple, should be
supplied
+ only if called by an error handler.

Returns:
- a callable that takes a HTTP response body string as the sole
argument.
+ A callable that takes a HTTP response body string as the sole
argument.
"""
if exc_info:
raise exc_info[0], exc_info[1], exc_info[2]
@@ -369,9 +370,6 @@

Args:
app: the GaeoApp instance to be started.
-
- Returns:
- None.
"""
env = dict(os.environ)
env["wsgi.input"] = sys.stdin
=======================================
--- /oildrum/lib/gaeo/controller.py Mon Nov 15 06:37:03 2010
+++ /oildrum/lib/gaeo/controller.py Fri Nov 26 07:12:06 2010
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

-""" The gaeo controller module.
+"""The gaeo controller module.

Classes:
Controller:
@@ -26,8 +26,12 @@
_rendered = False

def __init__(self, request, response, params={}):
- '''
- Constructor
+ '''Initializes a Controller object.
+
+ Args:
+ request: a GaeoRequest object.
+ response: a GaeoResponse object.
+ params: a dict of request parameters and routing parameters.
'''
self.request = request
self.response = response
@@ -63,14 +67,33 @@
raise

self.view.session = self.session
-
+
def before_action(self):
+ """Performs work needed before the action method is called.
+
+ This is the template method pattern. Subclasses should provide
+ an implementation.
+ """
pass
-
+
def after_action(self):
+ """Performs work needed after the action method returns.
+
+ This is the template method pattern. Subclasses should provide
+ an implementation.
+ """
pass
-
+
def redirect(self, url, permanently=False):
+ """Sets HTTP headers to redirect the client.
+
+ Args:
+ url: the URL to redirect to.
+ permanantly: True if the redirect should be permanent.
+
+ Side effect:
+ Marks this request as rendered.
+ """
if permanently:
self.response.set_status(301, 'Move Permanently')
else:
@@ -78,34 +101,59 @@
self.response.headers['Location'] = url
self.response.clear()
self._rendered = True
-
+
def output(self, *html):
+ """Writes data to client.
+
+ Args:
+ html: a list of data items to be written out.
+
+ Side effect:
+ Marks this request as rendered.
+ """
for h in html:
self.response.out.write(h)
self._rendered = True
-
+
def set_no_render(self):
+ """Marks this request as rendered."""
self._rendered = True
-
+
def json_output(self, json_data={}):
+ """Writes data to client in JSON format.
+
+ Args:
+ json_data: data object to be jsonized and written out.
+
+ Side effect:
+ Marks this request as rendered.
+ """
from django.utils import simplejson
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(simplejson.dumps(json_data))
self._rendered = True
-
+
def complete(self):
- """If the controller hasn't output something to client,
- call the view.render() method to render the template file.
+ """Completes the rendering.
+
+ Asks the view to render itself if the request isn't marked as
rendered.
"""
if not self._rendered:
self.view.render()
-
+
def no_action(self, template_path='', params={}):
- """Invoke while the action is missing. If the template_path
- argument is set, output the specified content.
+ """Handles the request when no action method is found.
+
+ Feeds the params to the template at template_path for rendering and
+ writes the result to the client.

Args:
- template_path: the path of specified template
+ template_path: the path of the template to use, bypass
rendering
+ if it is ''.
+ params: the parameters to feed to the template.
+
+ Returns:
+ True if rendering is done, False otherwise.
"""
if template_path:
import os
@@ -116,8 +164,16 @@
return True
except:
pass
-
+ return False
+
def set_cookie(self, name, value, max_age=None):
+ """Sets a cookie in the HTTP header.
+
+ Args:
+ name: the name of the cookie.
+ value: the value of the cookie.
+ max_age: [optional] the maximum age of the cookie before it
expires.
+ """
cookie_data = [
'%s=%s' % (name, value),
'path=%s' % settings.SESSION_COOKIE_PATH
@@ -133,8 +189,15 @@
cookie_str = '; '.join(cookie_data)
self.response.headers.add_header('Set-Cookie', cookie_str)
logging.debug("Set-Cookie: %s" % cookie_str)
-
+
def _get_session(self):
+ """Returns the session object for this request.
+
+ 1. If the session cookie is present in HTTP header, return the
session
+ associated with the cookie.
+ 2. Otherwise return a newly created session object with its cookie
+ inserted into the HTTP header.
+ """
session = None
session_key = settings.SESSION_COOKIE_NAME
if session_key in self.cookies:
@@ -145,23 +208,44 @@
session = Session(controller=self)

return session
-
- def __appender(self, dict, arr, val):
+
+ def __appender(self, dict, arr, value):
+ """Sets dict[arr[0]][arr[1]]...[arr[N-1]] = value.
+
+ Args:
+ dict: the dict object to insert value into.
+ arr: the list of keys to map to the value.
+ value: the value to be inserted.
+ """
if len(arr) > 1:
try:
dict[arr[0]]
except KeyError:
dict[arr[0]] = {}
- return {arr[0]: self.__appender(dict[arr[0]], arr[1:], val)}
+ return {arr[0]: self.__appender(dict[arr[0]], arr[1:], value)}
else:
- dict[arr[0]] = val
+ dict[arr[0]] = value
return

- def __nested_params(self, prm):
- prm2 = {}
- for param in prm:
- parray = param.replace(']', '').split('[')
+ def __nested_params(self, params):
+ """Converts a flat dict into a nested dict.
+
+ A flat dict of key -> value with key in the form of
+ 'key0[key1][key2]...[keyN]' is converted to a nested dict
+ like key0['key1']['key2']...['keyN'] -> value.
+
+ If key0 contains dashes ('-'), it is split into multiple keys.
+
+ Args:
+ params: a flat dict.
+
+ Returns:
+ The nested dict.
+ """
+ result = {}
+ for key in params:
+ parray = key.replace(']', '').split('[')
if len(parray) == 1:
parray = parray[0].split('-')
- self.__appender(prm2, parray, prm[param])
- return prm2
+ self.__appender(result, parray, params[key])
+ return result
=======================================
--- /oildrum/lib/gaeo/model.py Tue Sep 28 23:47:08 2010
+++ /oildrum/lib/gaeo/model.py Fri Nov 26 07:12:06 2010
@@ -11,14 +11,35 @@
"""
GAEO enhanced model in Datastore implementation
"""
-
+
def before_put(self):
- pass
-
+ """The template method called before putting the entity to
DataStore.
+
+ This is a template method pattern. It is a hook that self.put()
calls
+ before actually putting the entity to DataStore.
+
+ Returns:
+ False if the entity should NOT be put into DataStore.
+ """
+ return True
+
def after_put(self):
+ """The template method called after putting the entity to
DataStore.
+
+ This is a template method pattern. It is a hook that self.put()
calls
+ after the entity is put to DataStore.
+ """
pass
-
+
def put(self, **kwargs):
+ """Puts the entity to DataStore.
+
+ Args:
+ **kwargs: the keyword arguments to be passed to db.Model.put().
+
+ Returns:
+ the key of the entity put into DataStore.
+ """
if self.before_put() is not False:
if kwargs:
key = super(DatastoreModel, self).put(**kwargs)
@@ -26,16 +47,20 @@
key = super(DatastoreModel, self).put()
self.after_put()
return key
-
+
# alias
update = put
-
+
def set_attributes(self, **attrs):
+ """TODO: document this method.
+ """
props = self.properties()
for prop in props.values():
if prop.name in attrs:
prop.__set__(self, attrs[prop.name])
-
+
def update_attributes(self, **attrs):
+ """TODO: document this method.
+ """
self.set_attributes(**attrs)
self.update()
=======================================
--- /oildrum/lib/gaeo/router.py Tue Sep 28 23:47:08 2010
+++ /oildrum/lib/gaeo/router.py Fri Nov 26 07:12:06 2010
@@ -18,23 +18,24 @@
"""
Represents a routing rule.
"""
+
def __init__(self, pattern='', *matches, **args):
- """ Create a rule instance.
-
+ """Initializer.
+
Args:
- pattern
- matches
- args
+ pattern: [string] the pattern for the rule.
+ matches: TODO: document this arg.
+ args: TODO: document this arg.
"""
self._pattern = pattern[:-1] if pattern.endswith('/') else pattern
self._regex = self._pattern
self._args = args
self.__inlines = re.findall(':([^/.]+)', self._pattern)
-
+
self._matches = []
for i in xrange(len(matches)):
self._matches.append((i+1, matches[i]))
-
+
# transform the pattern to a valid RegEx
for i in range(len(self.__inlines)):
param = self.__inlines[i]
@@ -42,23 +43,22 @@
self._regex = self._regex.replace(':' + self.__inlines[i],
'([^/.]+)')
self._matches = sorted(self._matches, key=operator.itemgetter(0))
-
+
# normalize the RegEx
if not self._regex.startswith('^'):
self._regex = '^' + self._regex

if not self._regex.endswith('$'):
self._regex = self._regex + '$'
-
-
+
def match_url(self, uri):
- """ Check if the URL is mapped to this rule.
-
+ """Check if the URL is mapped to this rule.
+
Args:
- uri
-
- Return:
-
+ uri: The full URL of the request.
+
+ Returns:
+ TODO: document the return value.
"""
url = uri[:-1] if uri.endswith('/') else uri
matches = re.findall(self._regex, url)
@@ -81,6 +81,7 @@
def __eq__(self, other):
return self._regex == other._regex

+
class Router(object):
"""
The request router class.
@@ -88,34 +89,58 @@
__rules = []

def __init__(self):
- '''
- Constructor
- '''
+ """Initializer."""
pass
-
+
def add(self, rule):
+ """Adds the routing rule into the Router.
+
+ The rule is ignored if the same rule is already in the Router.
+
+ Args:
+ rule: a RoutingRule object.
+ """
if rule not in (x[0] for x in self.__rules):
self.__rules.append((rule, None))
-
+
def remove(self, rule):
+ """Removes the routing rule from the Router.
+
+ This method is a no op if the input rule is not in the Router.
+
+ Args:
+ rule: a RoutingRule object.
+ """
for r in self.__rules:
if r[0] == rule:
self.__rules.remove(rule)
break
-
+
def resolve(self, uri):
+ """Finds the rule that matches to the URL.
+
+ Args:
+ uri: The full URL of the request.
+
+ Returns:
+ TODO: document the return value.
+ """
for rule in self.__rules:
params = rule[0].match_url(uri)
if params:
return (params, rule[1])

return None
-
+
def restful(self, rule, **args):
"""Add a RESTful service routing.
-
+
+ TODO: document this method.
+
Args:
rule:
+
+ Returns:
"""
# default RESTful routing
restful_routing = {
=======================================
--- /oildrum/lib/gaeo/session.py Tue Sep 28 23:47:08 2010
+++ /oildrum/lib/gaeo/session.py Fri Nov 26 07:12:06 2010
@@ -27,18 +27,22 @@


class Session(dict):
- """ The base session class.
- """
+ """The base session class."""
__key = None
__destroyed = False

__controller = None

def __new__(cls, key=None, auto_create=False, controller=None):
- """ The creation of the session.
+ """Constructor.

If the key argument is passed in, try to fetch the stored
session first. Otherwise, create a new one.
+
+ Args:
+ key:
+ auto_create:
+ controller:
"""
session = None
cls.__controller = controller
=======================================
--- /oildrum/lib/gaeo/utils.py Tue Sep 28 23:47:08 2010
+++ /oildrum/lib/gaeo/utils.py Fri Nov 26 07:12:06 2010
@@ -5,10 +5,27 @@
from datetime import tzinfo, timedelta

def select_trusy(x, y):
- """ Select the trusy value. """
+ """Select the trusy value.
+
+ TODO: document this function.
+
+ Args:
+ x:
+ y:
+
+ Returns:
+ """
return x if x else y

def bbcode(value):
+ """Convert the bbcodes to their HTML counterparts.
+
+ Args:
+ value: the input string that may contain bbcodes.
+
+ Returns:
+ The string with bbcodes converted to HTML.
+ """
bbdata = [
(r'\[url\](.+?)\[/url\]', r'<a href="\1">\1</a>'),
(r'\[url=(.+?)\](.+?)\[/url\]', r'<a href="\1">\2</a>'),
@@ -51,7 +68,21 @@

return value

+
def safeout(value):
+ """Converts the input string to an HTML segment.
+
+ This function does 3 things:
+ 1. replaces angle brackets of HTML tags with &lt; and &gt;,
+ 2. converts the bbcodes to HTML tags,
+ 3. replaces newlines with <br> tags.
+
+ Args:
+ value: the input string to be escape-encoded.
+
+ Returns:
+ The escape-encoded string.
+ """
# strip tags
pat = re.compile(r'<([^>]*?)>', re.DOTALL | re.M)
value = re.sub(pat, '&lt;\\1&gt;', value)
@@ -62,7 +93,7 @@


class TaiwanTimeZone(tzinfo):
- '''CST'''
+ """The tzinfo class for Taiwan's timezone."""
ZERO = timedelta(0)
PLUS_8 = timedelta(minutes=8*60)
def utcoffset(self, dt):

Reply all
Reply to author
Forward
0 new messages