web Package

api Module

class tic.web.api.Cookie(input=None)[source]

Bases: Cookie.SimpleCookie

load(rawdata, ignore_parse_errors=False)[source]
exception tic.web.api.HTTPBadGateway(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 502 Bad Gateway

code = 502
reason = 'Bad Gateway'
exception tic.web.api.HTTPBadRequest(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 400 Bad Request

code = 400
reason = 'Bad Request'
exception tic.web.api.HTTPConflict(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 409 Conflict

code = 409
reason = 'Conflict'
exception tic.web.api.HTTPException(detail, *args)[source]

Bases: exceptions.Exception

classmethod subclass(name, code)[source]

Create a new Exception class representing a HTTP status code.

exception tic.web.api.HTTPExpectationFailed(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 417 Expectation Failed

code = 417
reason = 'Expectation Failed'
exception tic.web.api.HTTPForbidden(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 403 Forbidden

code = 403
reason = 'Forbidden'
exception tic.web.api.HTTPGatewayTimeout(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 504 Gateway Timeout

code = 504
reason = 'Gateway Timeout'
exception tic.web.api.HTTPGone(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 410 Gone

code = 410
reason = 'Gone'
exception tic.web.api.HTTPInternalError(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 500 Internal Server Error

code = 500
reason = 'Internal Server Error'
exception tic.web.api.HTTPLengthRequired(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 411 Length Required

code = 411
reason = 'Length Required'
exception tic.web.api.HTTPMethodNotAllowed(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 405 Method Not Allowed

code = 405
reason = 'Method Not Allowed'
exception tic.web.api.HTTPNotAcceptable(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 406 Not Acceptable

code = 406
reason = 'Not Acceptable'
exception tic.web.api.HTTPNotFound(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 404 Not Found

code = 404
reason = 'Not Found'
exception tic.web.api.HTTPNotImplemented(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 501 Not Implemented

code = 501
reason = 'Not Implemented'
exception tic.web.api.HTTPPaymentRequired(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 402 Payment Required

code = 402
reason = 'Payment Required'
exception tic.web.api.HTTPPreconditionFailed(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 412 Precondition Failed

code = 412
reason = 'Precondition Failed'
exception tic.web.api.HTTPProxyAuthenticationRequired(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 407 Proxy Authentication Required

code = 407
reason = 'Proxy Authentication Required'
exception tic.web.api.HTTPRequestEntityTooLarge(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 413 Request Entity Too Large

code = 413
reason = 'Request Entity Too Large'
exception tic.web.api.HTTPRequestTimeout(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 408 Request Timeout

code = 408
reason = 'Request Timeout'
exception tic.web.api.HTTPRequestUriTooLong(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 414 Request-Uri Too Long

code = 414
reason = 'Request-Uri Too Long'
exception tic.web.api.HTTPRequestedRangeNotSatisfiable(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 416 Requested Range Not Satisfiable

code = 416
reason = 'Requested Range Not Satisfiable'
exception tic.web.api.HTTPServiceUnavailable(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 503 Service Unavailable

code = 503
reason = 'Service Unavailable'
exception tic.web.api.HTTPUnauthorized(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 401 Unauthorized

code = 401
reason = 'Unauthorized'
exception tic.web.api.HTTPUnsupportedMediaType(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 415 Unsupported Media Type

code = 415
reason = 'Unsupported Media Type'
exception tic.web.api.HTTPVersionNotSupported(detail, *args)

Bases: tic.web.api.HTTPException

Exception for HTTP 505 Http Version Not Supported

code = 505
reason = 'Http Version Not Supported'
class tic.web.api.IAuthenticator[source]

Bases: tic.core.Interface

Extension point interface for components that can provide the name of the remote user.

authenticate(req)[source]

Return the name of the remote user, or None if the identity of the user is unknown.

class tic.web.api.IEmailHandler[source]

Bases: tic.core.Interface

Extension point interface for email handlers.

match_email(emailMessage)[source]

Return whether the handler wants to process the given email message. TODOC: Args?

process_email(emailMessate)[source]

Process the email message. TODOC: Args?

class tic.web.api.IRequestFilter[source]

Bases: tic.core.Interface

Extension point interface for components that want to filter HTTP requests, before and/or after they are processed by the main handler.

post_process_request(req, template, data, content_type)[source]

Do any post-processing the request might need; typically adding values to the template data dictionary, or changing template or mime type.

data may be update in place.

Always returns a tuple of (template, data, content_type), even if unchanged.

Note that template, data, content_type will be None if:
  • called when processing an error page
  • the default request handler did not return any result

(Since 0.11)

pre_process_request(req, handler)[source]

Called after initial handler selection, and can be used to change the selected handler or redirect request.

Always returns the request handler, even if unchanged.

class tic.web.api.IRequestHandler[source]

Bases: tic.core.Interface

Extension point interface for request handlers.

match_request(req)[source]

Return whether the handler wants to process the given request.

process_request(req)[source]

Process the request

class tic.web.api.Request(environ, start_response)[source]

Bases: object

Represents a HTTP request/response pair.

This class provides a convenience API over WSGI.

add_redirect_listener(listener)[source]

Add a callable to be called prior to executing a redirect.

The callable is passed the arguments to the redirect() call.

base_path

The root path of the application

check_modified(datetime, extra='')[source]

Check the request “If-None-Match” header against an entity tag.

The entity tag is generated from the specified last modified time (datetime), optionally appending an extra string to indicate variants of the requested resource.

That extra parameter can also be a list, in which case the MD5 sum of the list content will be used.

If the generated tag matches the “If-None-Match” header of the request, this method sends a “304 Not Modified” response to the client. Otherwise, it adds the entity tag as an “ETag” header to the response so that consecutive requests can be cached.

end_headers()[source]

Must be called after all headers have been sent and before the actual content is written.

get_header(name)[source]

Return the value of the specified HTTP header, or None if there’s no such header in the request.

method

The HTTP method of the request

path_info

Path inside the application

query_string

Query part of the request

read(size=None)[source]

Read the specified number of bytes from the request body.

redirect(url, permanent=False)[source]

Send a redirect to the client, forwarding to the specified URL. The url may be relative or absolute, relative URLs will be translated appropriately.

remote_addr

IP address of the remote user

remote_user

Name of the remote user, None if the userhas not logged in using HTTP authentication

scheme

The scheme of the request URL

send(content, content_type='text/html', status=200)[source]
send_error(exc_info, template='error.html', content_type='text/html', status=500, env=None, data={})[source]
send_file(path, mimetype=None)[source]

Send a local file to the browser.

This method includes the “Last-Modified”, “Content-Type” and “Content-Length” headers in the response, corresponding to the file attributes. It also checks the last modification time of the local file against the “If-Modified-Since” provided by the user agent, and sends a “304 Not Modified” response if it matches.

send_header(name, value)[source]

Send the response header with the specified name and value.

value must either be an unicode string or can be converted to one (e.g. numbers, ...)

send_response(code=200)[source]

Set the status code of the response.

server_name

Name of the server

server_port

Port number the server is bound to

write(data)[source]

Write the given data to the response body.

data can be either a str or an unicode string. If it’s the latter, the unicode string will be encoded using the charset specified in the ‘’Content-Type’’ header or ‘utf-8’ otherwise.

exception tic.web.api.RequestDone[source]

Bases: exceptions.Exception

Marker exception that indicates whether request processing has completed and a response was sent.

tic.web.api.parse_query_string(query_string)[source]

Parse a query string into a _RequestArgs.

boot Module

dojo Module

tic.web.dojo.is_dojo_class(js_file_path_or_content)[source]
tic.web.dojo.render_xd_classes(js_file_path_or_content, req)[source]

Renders the cross-domain dojo files

tic.web.dojo.to_dojo(object)[source]

@Depreicated converts a python class to a dojo class

href Module

class tic.web.href.Href(base)[source]

Bases: object

Implements a callable that constructs URLs with the given base. The function can be called with any number of positional and keyword arguments which than are used to assemble the URL.

Positional arguments are appended as individual segments to the path of the URL:

>>> href = Href('/trac')
>>> href('ticket', 540)
'/trac/ticket/540'
>>> href('ticket', 540, 'attachment', 'bugfix.patch')
'/trac/ticket/540/attachment/bugfix.patch'
>>> href('ticket', '540/attachment/bugfix.patch')
'/trac/ticket/540/attachment/bugfix.patch'

If a positional parameter evaluates to None, it will be skipped:

>>> href('ticket', 540, 'attachment', None)
'/trac/ticket/540/attachment'

The first path segment can also be specified by calling an attribute of the instance, as follows:

>>> href.ticket(540)
'/trac/ticket/540'
>>> href.changeset(42, format='diff')
'/trac/changeset/42?format=diff'

Simply calling the Href object with no arguments will return the base URL:

>>> href()
'/trac'

Keyword arguments are added to the query string, unless the value is None:

>>> href = Href('/trac')
>>> href('timeline', format='rss')
'/trac/timeline?format=rss'
>>> href('timeline', format=None)
'/trac/timeline'
>>> href('search', q='foo bar')
'/trac/search?q=foo+bar'

Multiple values for one parameter are specified using a sequence (a list or tuple) for the parameter:

>>> href('timeline', show=['ticket', 'wiki', 'changeset'])
'/trac/timeline?show=ticket&show=wiki&show=changeset'

Alternatively, query string parameters can be added by passing a dict or list as last positional argument:

>>> href('timeline', {'from': '02/24/05', 'daysback': 30})
'/trac/timeline?daysback=30&from=02%2F24%2F05'
>>> href('timeline', {})
'/trac/timeline'
>>> href('timeline', [('from', '02/24/05')])
'/trac/timeline?from=02%2F24%2F05'
>>> href('timeline', ()) == href('timeline', []) == href('timeline', {})
True

The usual way of quoting arguments that would otherwise be interpreted as Python keywords is supported too:

>>> href('timeline', from_='02/24/05', daysback=30)
'/trac/timeline?from=02%2F24%2F05&daysback=30'

If the order of query string parameters should be preserved, you may also pass a sequence of (name, value) tuples as last positional argument:

>>> href('query', (('group', 'component'), ('groupdesc', 1)))
'/trac/query?group=component&groupdesc=1'
>>> params = []
>>> params.append(('group', 'component'))
>>> params.append(('groupdesc', 1))
>>> href('query', params)
'/trac/query?group=component&groupdesc=1'

By specifying an absolute base, the function returned will also generate absolute URLs:

>>> href = Href('http://trac.edgewall.org')
>>> href('ticket', 540)
'http://trac.edgewall.org/ticket/540'
>>> href = Href('https://trac.edgewall.org')
>>> href('ticket', 540)
'https://trac.edgewall.org/ticket/540'

In common usage, it may improve readability to use the function-calling ability for the first component of the URL as mentioned earlier:

>>> href = Href('/trac')
>>> href.ticket(540)
'/trac/ticket/540'
>>> href.browser('/trunk/README.txt', format='txt')
'/trac/browser/trunk/README.txt?format=txt'

main Module

class tic.web.main.DefaultHandler(compmgr, init=None, cls=<class 'tic.web.main.DefaultHandler'>)[source]

Bases: tic.core.Component

This is the default handler. It basically handles the entry, index.html and converting any dojo files to cross domain,xd, files if needed

match_request(req)[source]
process_request(req)[source]
templates_dir = 'templates'
class tic.web.main.FavIconHanlder(compmgr, init=None, cls=<class 'tic.web.main.FavIconHanlder'>)[source]

Bases: tic.core.Component

Default handler for the favicon to return nothing.. this is just to escape erroring out which cost alot in appengine

This can be overridden by configuring it in the app.yaml file. see appengine docs for more details

match_request(req)[source]
process_request(req)[source]
class tic.web.main.MailHandler(compmgr, init=None, cls=<class 'tic.web.main.MailHandler'>)[source]

Bases: tic.core.Component

Router for all incomming mail

handlers

List of components that implement tic.web.api.IEmailHandler

match_request(req)[source]
process_request(req)[source]
class tic.web.main.RequestDispatcher(compmgr, init=None, cls=<class 'tic.web.main.RequestDispatcher'>)[source]

Bases: tic.core.Component

Web request dispatcher. This component dispatches incoming requests to registered handlers.

authenticate(req)[source]
authenticators

List of components that implement tic.web.api.IAuthenticator

dispatch(req)[source]
handlers

List of components that implement tic.web.api.IRequestHandler

required = True
tic.web.main.dispatch_request(environ, start_response)[source]

Main entry point for the TIC web interface.

Args:
environ: the WSGI environment dict start_response: the WSGI callback for starting the response

sessions Module

Modifications by Adam Thurlow – extracted to be standalone sessions

Copyright (c) 2008, appengine-utilities project All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this

list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

class tic.web.sessions.Session(cookie_path='/', cookie_domain=False, cookie_name='gaeutilities_session', session_expire_time=7200, clean_check_percent=50, integrate_flash=False, check_ip=True, check_user_agent=True, set_cookie_expires=True, session_token_ttl=5, last_activity_update=60, writer='datastore')[source]

Bases: object

Sessions are used to maintain user presence between requests.

Sessions can either be stored server side in the datastore/memcache, or be kept entirely as cookies. This is set either with the settings file or on initialization, using the writer argument/setting field. Valid values are “datastore” or “cookie”.

Session can be used as a standard dictionary object.
session = appengine_utilities.sessions.Session() session[“keyname”] = “value” # sets keyname to value print session[“keyname”] # will print value
Datastore Writer:

The datastore writer was written with the focus being on security, reliability, and performance. In that order.

It is based off of a session token system. All data is stored server side in the datastore and memcache. A token is given to the browser, and stored server side. Optionally (and on by default), user agent and ip checking is enabled. Tokens have a configurable time to live (TTL), which defaults to 5 seconds. The current token, plus the previous 2, are valid for any request. This is done in order to manage ajax enabled sites which may have more than on request happening at a time. This means any token is valid for 15 seconds. A request with a token who’s TTL has passed will have a new token generated.

In order to take advantage of the token system for an authentication system, you will want to tie sessions to accounts, and make sure only one session is valid for an account. You can do this by setting a db.ReferenceProperty(_AppEngineUtilities_Session) attribute on your user Model, and use the get_ds_entity() method on a valid session to populate it on login.

Note that even with this complex system, sessions can still be hijacked and it will take the user logging in to retrieve the account. In the future an ssl only cookie option may be implemented for the datastore writer, which would further protect the session token from being sniffed, however it would be restricted to using cookies on the .appspot.com domain, and ssl requests are a finite resource. This is why such a thing is not currently implemented.

Session data objects are stored in the datastore pickled, so any python object is valid for storage.

Cookie Writer:

Sessions using the cookie writer are stored entirely in the browser and no interaction with the datastore is required. This creates a drastic improvement in performance, but provides no security for session hijack. This is useful for requests where identity is not important, but you wish to keep state between requests.

Information is stored in a json format, as pickled data from the server is unreliable.

Note: There is no checksum validation of session data on this method, it’s streamlined for pure performance. If you need to make sure data is not tampered with, use the datastore writer which stores the data server side.

django-middleware:
Included with the GAEUtilties project is a django-middleware.middleware.SessionMiddleware which can be included in your settings file. This uses the cookie writer for anonymous requests, and you can switch to the datastore writer on user login. This will require an extra set in your login process of calling request.session.save() once you validated the user information. This will convert the cookie writer based session to a datastore writer.
COOKIE_NAME = 'gaeutilities_session'
classmethod check_token(cookie_name='gaeutilities_session', delete_invalid=True)[source]

Retrieves the token from a cookie and validates that it is a valid token for an existing cookie. Cookie validation is based on the token existing on a session that has not expired.

This is useful for determining if datastore or cookie writer should be used in hybrid implementations.

Args:

cookie_name: Name of the cookie to check for a token. delete_invalid: If the token is not valid, delete the session

cookie, to avoid datastore queries on future requests.

Returns True/False

classmethod clean_old_sessions(session_expire_time, count=50)[source]

Delete expired sessions from the datastore.

This is a class method which can be used by applications for maintenance if they don’t want to use the built in session cleaning.

Args:

count: The amount of session to clean. session_expire_time: The age in seconds to determine outdated

sessions.

Returns True on completion

clear()[source]

Removes session data items, doesn’t delete the session. It does work with cookie sessions, and must be called before any output is sent to the browser, as it set cookies.

Returns True

cycle_key()[source]

Changes the session id/token.

Returns new token.

delete()[source]

Delete the current session and start a new one.

This is useful for when you need to get rid of all data tied to a current session, such as when you are logging out a user.

Returns True

classmethod delete_all_sessions()[source]

Deletes all sessions and session data from the data store. This does not delete the entities from memcache (yet). Depending on the amount of sessions active in your datastore, this request could timeout before completion and may have to be called multiple times.

NOTE: This can not delete cookie only sessions as it has no way to access them. It will only delete datastore writer sessions.

Returns True on completion.

delete_item(keyname, throw_exception=False)[source]

Delete item from session data, ignoring exceptions if necessary.

Args:
keyname: The keyname of the object to delete. throw_exception: false if exceptions are to be ignored.
Returns:
Nothing.
flush()[source]

Delete’s the current session, creating a new one.

Returns True

get(keyname, default=None)[source]

Returns either the value for the keyname or a default value passed.

Args:
keyname: keyname to look up default: (optional) value to return on keyname miss

Returns value of keyname, or default, or None

get_ds_entity()[source]

Will return the session entity from the datastore if one exists, otherwise will return None (as in the case of cookie writer session.

has_key(keyname)[source]

Equivalent to k in a, use that form in new code

Args:
keyname: keyname to check

Returns True/False

items()[source]

Creates a copy of just the data items.

Returns dictionary of session data objects.

keys()[source]

Returns a list of keys.

new_sid()[source]

Create a new session id.

Returns session id as a unicode string.

no_cache_headers()[source]

Generates headers to avoid any page caching in the browser. Useful for highly dynamic sites.

Returns a unicode string of headers.

setdefault(keyname, default=None)[source]

Returns either the value for the keyname or a default value passed. If keyname lookup is a miss, the keyname is set with a value of default.

Args:
keyname: keyname to look up default: (optional) value to return on keyname miss

Returns value of keyname, or default, or None

update(*dicts)[source]

Updates with key/value pairs from b, overwriting existing keys

Returns None

values()[source]

Returns a list object of just values in the session.

wsgi Module

class tic.web.wsgi.WSGIGateway(environ, stdin=<open file '<stdin>', mode 'r' at 0x100284150>, stderr=<open file '<stderr>', mode 'w' at 0x100284270>)[source]

Bases: object

Abstract base class for WSGI servers or gateways.

run(application)[source]

Start the gateway with the given WSGI application.

wsgi_file_wrapper

alias of _FileWrapper

wsgi_multiprocess = True
wsgi_multithread = True
wsgi_run_once = False
wsgi_version = (1, 0)
class tic.web.wsgi.WSGIRequestHandler(request, client_address, server)[source]

Bases: BaseHTTPServer.BaseHTTPRequestHandler

finish()[source]

We need to help the garbage collector a little.

handle_one_request()[source]
setup_environ()[source]
class tic.web.wsgi.WSGIServer(server_address, application, gateway=<class 'tic.web.wsgi.WSGIServerGateway'>, request_handler=<class tic.web.wsgi.WSGIRequestHandler at 0x103969d50>)[source]

Bases: BaseHTTPServer.HTTPServer

class tic.web.wsgi.WSGIServerGateway(handler, environ)[source]

Bases: tic.web.wsgi.WSGIGateway

Table Of Contents

Previous topic

simplejson Package

Next topic

appengine Package

This Page