Function command
command( args, **extra )
Undocumented
Function has
has( feature )
Tells if your Python installation has any of the following features:
- FLUP for FCGI, SCGI servers
- WSGIREF for standalone WSGI server
- KID for template processing
Function run
run( app=None, components=(), method='STANDALONE', name='retro', root='.', resetlog=False, address='', port=None, prefix='', async=False, sessions=False, withReactor=None, processStack= at 0x90064c4>, runCondition=True )
Runs this web application with the given method (easiest one is STANDALONE), with the given root (directory from where the web app-related resource will be resolved).
This function is the main
for your web application, so this is basically the last call you should have in your web application main.
bool
bool(x) -> bool
Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.
str
'0.0.0.0'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
int
int(x, base) -> integer
Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead.
tuple
('STANDALONE', 'WSGIREF', 'KID')
tuple() -> an empty tuple tuple(sequence) -> tuple initialized from sequence's items
If the argument is a tuple, the return value is the same object.
str
'KID'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'Specifies the port on which the server should be run'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'Prefix to prepend to the URLs'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'STANDALONE'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'STANDALONE_WSGIREF'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'WSGIREF'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Module retro
This is the main Retro module. You can generally do the following:
from retro import *
class MyCompoment(Component):
@on("/index.html")
def main( self, request ):
return request.respond("Hello World!")
if __name__ == "__main__":
run(Application(MyCompoment()), STANDALONE)
All important classes, functions and decorators are made available through this module, so you should not have to bother with anything else.
tuple
(<class retro.core.Session at 0x8e5998c>,)
tuple() -> an empty tuple tuple(sequence) -> tuple initialized from sequence's items
If the argument is a tuple, the return value is the same object.
Method __init__
__init__( self, request, session=None )
Undocumented
Method expire
expire( self, time )
Undocumented
Method get
get( self, key=, value= )
Undocumented
Method isNew
isNew( self )
Undocumented
Method value
value( self, key=, value= )
Undocumented
Function hasSession
hasSession( request )
Undocumented
Class BeakerSession
Implementation of the Session object for Flup Session Middleware
tuple
()
tuple() -> an empty tuple tuple(sequence) -> tuple initialized from sequence's items
If the argument is a tuple, the return value is the same object.
Method __call__
__call__( self, *args, **kwargs )
Undocumented
Method __init__
__init__( self, name=None, description=None )
Undocumented
Method observe
observe( self, observer )
Undocumented
Method pipe
pipe( self, event )
Undocumented
Method trigger
trigger( self, *args, **kwargs )
Undocumented
Method unobserve
unobserve( self, observer )
Undocumented
Method unpipe
unpipe( self, event )
Undocumented
Method __init__
__init__( self, expect=1 )
Undocumented
Method _eventMet
_eventMet( self, event, observer, *args, **kwargs )
Undocumented
Method joinEvent
joinEvent( self, event )
Undocumented
Method meet
meet( self )
Undocumented
Method onMeet
onMeet( self, callback )
Undocumented
Class RendezVous
Undocumented
Method __init__
__init__( self, environ, charset )
This creates a new request.
Method _applyTemplate
_applyTemplate( self, template, engine=None, **kwargs )
Applies the given template with the given arguments, and returns a string with the serialized template. This hook is called by the display
method, so you should redefine it to suit your needs.
Method _loadPostProcess
_loadPostProcess( self )
Post-processed the data loaded by the loader.
Method _loader
_loader( self, chunksize=None )
Returns a generator that loads the data of this request.
Method body
body( self, body= )
Gets/sets the request body (it is an alias for data)
Method bounce
bounce( self, **kwargs )
Undocumented
Method clientIP
clientIP( self )
Returns the HTTP client IP for this request. This method will get the HTTPXFORWARDEDFOR variable instead of the REMOTEADDR if it is set.
Method clientPort
clientPort( self )
Returns the HTTP client port for this request.
Method contentLength
contentLength( self )
Returns the request content length (if any)
Method contentType
contentType( self )
Returns the request content type
Method cookie
cookie( self, name )
Returns the value of the given cookie or None
Method cookies
cookies( self )
Returns the cookies (as a Cookie.SimpleCookie
instance) attached to this request.
Method data
data( self, data= )
Gets/sets the request data (it is an alias for body)
Method display
display( self, template, engine=None, **kwargs )
Returns a response built from the given template, applied with the given arguments. The engine parameters (KID, CHEETAH, DJANGO, etc) tells which engine should be used to apply the template.
Method environ
environ( self, name=, value= )
Gets or sets the environment attached to this request
Method fail
fail( self, content=None, status=412, headers=None )
Returns an Error 412 with the given content
Method file
file( self, name )
Returns the file (as a cgi.FieldStorage
) which was submitted as parameter with the given name. You will have more information accessible than with get
or param
, retured as a dict with param
, filename
, contentType
and data
fields.
Method get
get( self, name )
Gets the parameter with the given name. It is an alias for param
Method has
has( self, name )
Tells if the request has the given parameter.
Method header
header( self, name )
Undocumented
Method headers
headers( self )
Undocumented
Method load
load( self, chunksize=None )
Loads the (POST) data of this request. The optional @chunksize argument tells the number of bytes the should be read. This function is used internally, and only useful in an external use if you want to split the loading of the data into multiple chunks (using an iterator).
This allows you not to block the processing and requests and do things like a progress indicator.
This function will return you the percentage of the data loaded (an int from 0 to 100).
Here is an example of how to split the loading into
while request.load(1024) < 100:
# Do something
Method loaded
loaded( self )
Returns the percentage (value between 0 and 100) of this request data that was loaded.
Method method
method( self )
Returns the method (GET, POST, etc) for this request.
Method notFound
notFound( self, content='Resource not found', status=404 )
Method param
param( self, name )
Gets the parameter with the given name. It is an alias for get
Method params
params( self )
Returns a dictionary with the request parameters
Method redirect
redirect( self, url, **kwargs )
Responds to this request by a redirection to the following URL, with the given keyword arguments as parameter.
Method referer
referer( self )
Rerturns the HTTP referer for this request.
Method respond
respond( self, content='', contentType=None, headers=None, status=200 )
Responds to this request.
Method respondFile
respondFile( self, path, contentType=None, status=200 )
Responds with a local file. The content type is guessed using the mimetypes
module. If the file is not found in the local filesystem, and exception is raised.
Method respondMultiple
respondMultiple( self, bodies='', contentType='text/html', headers=None, status=200 )
Response with multiple bodies returned by the given sequence or iterator. This allows to implement server push
very easily.
Method returns
returns( self, value=None, js=None, contentType='text/javascript', status=200, headers=None, options=None )
Undocumented
Method session
session( self, name=, value= )
Invokes this request component session
method, and returns a couple (session, sessionState)
Method uri
uri( self )
Returns the URI for this method.
str
'CONTENT_LENGTH'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'CONTENT_TYPE'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'GET'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'HTTP_COOKIE'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'PATH_INFO'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'POST'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'QUERY_STRING'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'REQUEST_METHOD'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'REQUEST_URI'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'SCRIPT_NAME'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'SCRIPT_ROOT'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Class Request
A request object is initialized from data given by the containing webserver, it is not directly built by the developer. As web server receive requests, they have to build responses to fullfill the requests.
Method __init__
__init__( self, content=None, headers=None, status=200, reason=None, produceWhen=None )
Undocumented
Method asString
asString( self )
Undocumented
Method asWSGI
asWSGI( self, startResponse, charset=None )
This is the main WSGI function handler. This is what generates the actual request and produces the response from the attached content
.
Method hasHeader
hasHeader( self, name )
Tells if the given header exists. If so, it returns its value (which cannot be None), or None if it was not found
Method prepare
prepare( self )
Sets default headers for the request before sending it.
Method produceOn
produceOn( self, event )
Guards the production of the response by this event. This allows the reactor (if any) to now when to start.
Method setContentType
setContentType( self, mimeType )
Undocumented
Method setHeader
setHeader( self, name, value, replace=True )
Sets the given header with the given value. If there is already a value and that replace is Fasle, nothing will be done.
str
'text/html'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
dict
{400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.')}
dict() -> new empty dictionary. dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs. dict(seq) -> new dictionary initialized as if via: d = {} for k, v in seq: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
Class Response
A response is sent to a client that sent a request.
Method __init__
__init__( self )
Undocumented
Method get
get( self, key=, value= )
Alias to self.value(key,value)
Method isNew
isNew( self )
Tells if the session is a new session or an existing one.
Method value
value( self, key=, value= )
Sets or gets the value
bound to the given key
Function hasSession
hasSession( request )
Tells if there is a session related to the given request, and returns it if found. If not found, returns None
Class Session
Undocumented
Function asJSON
asJSON( value, **options )
Converts the given value to a JSON representation. This function is an enhanced version of simplejson
, because it supports more datatypes (datetime, struct_time) and provides more flexibilty in how values can be serialized.
Specifically, the given value
contains a asJS
or asJSON
method, this method will be invoked with this function as first argument and the options as keyword-arguments (**options
)
Function json
json( value, *args, **kwargs )
Undocumented
Function unjson
unjson( value )
Undocumented
Module retro.core
The Retro core module defines classes that are at the basis of writing a server-side web application. In this respect, this module defines classes:
- For
Request
and Response
management - For easy headers and cookies management
- For
Session
management - For JSON/JavaScript serialization
This module could be easily re-used in another application, as it is (almost) completely standalone and separated from Retro Web applications.
tuple
(<class retro.web.Component at 0x8feed4c>,)
tuple() -> an empty tuple tuple(sequence) -> tuple initialized from sequence's items
If the argument is a tuple, the return value is the same object.
Method __call__
__call__( self, request, **kwargs )
Undocumented
Method __init__
__init__( self, component, function )
Undocumented
Class AJAXWrapper
This class allows to wrap a function so that its result will be returned as a JavaScript (JSON) object. As with the @TemplateWrapper. this should be not instanciated directly by the user, as it is automatically created by the @Application upon component registration.
Method __call__
__call__( self, request, **kwargs )
Undocumented
Method __init__
__init__( self, component, function, template, engine )
Undocumented
Method __str__
__str__( self )
Undocumented
Class TemplateWrapper
This class allows to wrap a function so that it will display the resulting template. This should not be instanciated by the user, but it may be good to know that is is created by the Application during the @register phase.
Method __call__
__call__( self, environ, start_response, request=None )
Just a proxy to Dispatcher.__call__
so that Application can be directly used as an WSGI app
Method __init__
__init__( self, components=(), prefix='', config=None, defaults=None )
Undocumented
Method _compileCheetahTemplateDeps
_compileCheetahTemplateDeps( self, path )
Undocumented
Method applyTemplate
applyTemplate( self, name, engine=None, **kwargs )
Applies the the given arguments to the template with the given name. This returns a string with the expanded template. This automatically uses the proper template engine, depending on the extension:
.kid
for KID templates .tmpl
for Cheetah templates .dtmpl
for Django templates
Method component
component( self, nameOrClass )
Returns the component with the given class name (not case sensitive) or the component(s) that are instances of the given class. If no component matches, None
is returned, otherwise the component is returned, if there are many, a list of components is returned.
Method config
config( self, name=, value= )
Returns the configuration value for the given name. Please note that this may raise an exception if the property is not part of the configuration properties.
When no configuration property name is given, the whole configuration is returned.
Method configure
configure( self, **kwargs )
Configures this application. The arguments you can use as the same as the properites offered by the Configuration
objects.
Method dispatcher
dispatcher( self )
The dispatcher is the main interface between the RW app and the webserver. This returns the dispatcher currently bound to the application.
Method ensureTemplate
ensureTemplate( self, name, engine=None )
Ensures that the a template with the given name exists and returns the corresponding path, or None if not found.
This method supports KID (.kid
), Cheetah (.tmpl
) or Django(.djtml
).
Method load
load( self, path )
Loads the file at the given path and returns its content.
Method localPath
localPath( self, path )
Returns an absolute path expressed relatively to the root.
Method location
location( self )
Returns the location of this application. The location will not finish by a slash. If the prefix is /
then an empty string will be returned.
Method log
log( self, *args )
Undocumented
Method notFound
notFound( self, request )
Undocumented
Method notSupported
notSupported( self, request )
Undocumented
Method register
register( self, *components )
Registeres the given component into this Web application. The component handlers will be bound to the proper URLs, and the component consistency will be checked against available resources.
This is where all the "gluing" occurs. The component attriutes are introspected to see if there are decorated with Retro decorators. If so, then the corresponding registration/initialization is made.
Method rootPath
rootPath( self )
Returns the absolute path where this application is rooted. This is only set at the execution.
This is an alias for config("root")
Method app
app( self )
Undocumented
Method context
context( self )
Undocumented
Method get
get( self, key )
Undocumented
Method getPriority
getPriority( self )
Returns the priority level for this component (usually 0).
Method init
init( self )
Init is called when the component is registered within its parent application. You can redefine this method to make your custom initialization.
Method name
name( self )
Returns the name for the component.
Method processBurstChannel
processBurstChannel( self, request )
The postRequest
method implements a mechanism that allows the Retro burst channel to work properly. It allows to put multiple requests into a single request, and then put the corresponding responses withing the body of this request.
Method registerHandler
registerHandler( self, handler, urls, priority=0 )
This method takes a function, a list of (HTTPMethod, DispatcherExpression) and a priority, describing a handler for a specific URL within this component. The parameters are actually the same as the ones given to the @on
decorator.
Method session
session( self, request, create=True )
Tells if there is a session attached with this request, creating it if create
is true (by default).
This will required either Flup session middleware or Beaker session middleware to be available. The application configuration session
option will be used to determine which session middleware should be used. Beaker is the recommended one, but Flup remains the default one.
Method set
set( self, key, value )
Undocumented
Method setPriority
setPriority( self, level )
Sets the priority level for this component. The component priority level (0 by default) will be added to the individual dispatcher priorities.
Function introspect
introspect( component )
Returns a list of (name, method, {on:…,priority:…,template:…,ajax:…}) for each slot that was decorated by Retro decorators.
str
''
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Class Application
Undocumented
Method __init__
__init__( self, message, explanation=None, exception=None )
Undocumented
getset_descriptor
Undocumented
Class ApplicationError
Undocumented
Method __init__
__init__( self, name=None )
Undocumented
Method app
app( self )
Undocumented
Method context
context( self )
Undocumented
Method get
get( self, key )
Undocumented
Method getPriority
getPriority( self )
Returns the priority level for this component (usually 0).
Method init
init( self )
Init is called when the component is registered within its parent application. You can redefine this method to make your custom initialization.
Method location
location( self )
Returns the location for this component. It is guaranteed to start with a slash, and not end with one. If it starts with a slash, then nothing is returned.
Method log
log( self, *args )
Undocumented
Method name
name( self )
Returns the name for the component.
Method processBurstChannel
processBurstChannel( self, request )
The postRequest
method implements a mechanism that allows the Retro burst channel to work properly. It allows to put multiple requests into a single request, and then put the corresponding responses withing the body of this request.
Method registerHandler
registerHandler( self, handler, urls, priority=0 )
This method takes a function, a list of (HTTPMethod, DispatcherExpression) and a priority, describing a handler for a specific URL within this component. The parameters are actually the same as the ones given to the @on
decorator.
Method session
session( self, request, create=True )
Tells if there is a session attached with this request, creating it if create
is true (by default).
This will required either Flup session middleware or Beaker session middleware to be available. The application configuration session
option will be used to determine which session middleware should be used. Beaker is the recommended one, but Flup remains the default one.
Method set
set( self, key, value )
Undocumented
Method setPriority
setPriority( self, level )
Sets the priority level for this component. The component priority level (0 by default) will be added to the individual dispatcher priorities.
Class Component
A Component is a class that contains methods that can handle URLs. Use the decorators provided by Retro and register the component into the application.
Method __init__
__init__( self, defaults={}, path=None )
Undocumented
Method __repr__
__repr__( self )
Undocumented
Method _abspath
_abspath( self, path )
Ensures that the given path is absolute. It will be made relative to the root if it is not already absolute.
Method get
get( self, name, value= )
Returns the value bound to the given property.
Method items
items( self )
Returns the key/values pairs of this configuration.
Method load
load( self, path )
Undocumented
Method log
log( self, *args )
A function to easily log data to the logfile.
Method merge
merge( self, config )
Merges the configuration from the given configuration into this one.
Method save
save( self, path )
Undocumented
Method set
set( self, name, value )
Sets the given property with the given value.
Method setdefault
setdefault( self, name, value )
Sets the given property with the given value only if the property did not exist before.
Class Configuration
Configuration objects allow to store configuration information for Retro applications. The supported properties are the following:
name
is the application name logfile
is the path to the log file templates
is the path to the templates directory charset
is the default charset for handling request/response data root
is the location of the server root (default .
) session
is the name of the session adapter (for now, FLUP
or BEAKER
)
It should be noted that unless absolute, paths are all relative to the configured application root, which is set by default to the current working directory when the application is first run.
Method __call__
__call__( self, environ, start_response, request=None )
Delegate request to the appropriate Application. This is the main method of the dispatcher.
Method __init__
__init__( self, app )
Creates a new Dispatcher instance. The @handlers attribute stores couple of (regexp, httphandlers).
Method _parseExpression
_parseExpression( self, expression, isStart=True )
Handler expressions are paths (URLs) that can contain typed variables that will match integers, strings, dates, etc, and optional groups.
Typed variables are like {name:type}
(where type is optional), and optional groups are like [optional/group]
. Of course, everything can be nested.
Method app
app( self )
Returns a reference to the Retro application bound to this dispatcher.
Method dispatch
dispatch( self, environ, path=None, method=None )
Figure out which handler to delegate to or send 404 or 405. This returns the handler plus a map of variables to pass to the handler.
Method on
on( self, expression, prefix='', handlers={}, priority=0 )
Tells that the given list of http methods will be handled by the associated handlers for the given expression. For instance, you can use `on("/{path}", GET=myGetHandler, POST=myPostHandler)
Function decomposeExpression
decomposeExpression( expression )
Converts the given expression pattern into a list of chunks
that are tuples (t, chunk), where t
is u
when the chunk is a litteral url, v
when the chunk is a variable, and uo
or vo
when the chunk is optional.
dict
{'digits': ('\\d+', <type 'int'>), 'word': ('\\w+', <type 'str'>), 'string': ('[^/]+', <type 'str'>), 'int': ('\\-?\\d+', <type 'int'>), 'chunk': ('[^/^.]+', <type 'str'>), 'float': ('\\-?\\d*.?\\d+', <type 'float'>), 'number': ('\\-?\\d*\\.?\\d+', <function <lambda> at 0x8ffb3e4>), 'rest': ('.+', <type 'str'>), 'range': ('\\-?\\d*\\:\\-?\\d*', <function <lambda> at 0x8ffb41c>), 'file': ('\\w+(.\\w+)', <type 'str'>), 'integer': ('\\-?\\d+', <type 'int'>), 'alpha': ('[a-zA-Z]+', <type 'str'>), 'path': ('.+', <type 'str'>), 'segment': ('[^/]+', <type 'str'>), 'any': ('.+', <type 'str'>)}
dict() -> new empty dictionary. dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs. dict(seq) -> new dictionary initialized as if via: d = {} for k, v in seq: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
Class Dispatcher
Dispatcher is a WSGI middleware loosely inspired from Luke Arno own Selector module, only more tailored to the needs of Retro (that is trimmed down and slightly extended).
The dispatcher is used as follows:
- Handlers are registered using the @on method
- The dispatch method is called by the Web application
- Dispatcher tries to identify a matching handler
- It processes the URL into a dict of variables (as declared)
- The @_call_ method is invoked
- The handler is invoked with the generated variables
For the story, the main reason for re-implementing Selector instead of subclassing it was a license problem: I wanted Retro to be BSD, while Selector was GPLed.
wrapper_descriptor
1.init(...) initializes x; see x.class.doc_ for signature
Class DispatcherSyntaxError
These errors are raised by the @Dispatcher when the syntax is not as expected.
Method asJS
asJS( self, asJSON )
Undocumented
Class ValidationError
Validation errors should be raised by @Component handlers when the given parameters (for instance, POST parameters) are not as expected.
Class WebRuntimeError
Undocumented
Function ajax
ajax( priority=0, **methods )
The @ajax decorator is a variation of the @on decorator. The @ajax decorator allows you to expose an existing Python function as a JavaScript (or JSON) producing method.
Basically, the @ajax decorator allows you to automatically bind a method to an URL and to ensure that the result will be JSON-ified before being sent. This is perfect if you have an existing python class and want to expose it to the web.
Function display
display( template, engine= )
The @display(template) decorator can be used to indicate that the decorated handler will display the given page (only when it returns None).
The first argument is the template name with or without the extension ( it can be guessed at runtime). The second argument is the engine (by default, it will be guessed from the extension)
Function log
log( *args )
A log function that outputs information on stdout. It's a good idea to replace this function by another if you want to have a custom logger.
Function on
on( priority=0, **methods )
The @on decorator is one of the main important things you will use within Retro. This decorator allows to wrap an existing method and indicate that it will be used to process an HTTP request.
The @on decorator can take GET
and POST
arguments, which take either a string or a list of strings, each describing an URI pattern (see @Dispatcher) that when matched, will trigger the method.
The decorated method must take a request
argument, as well as the same arguments as those used in the pattern.
For instance:
@on(GET='/list/{what:string}'
implies that the wrapped method is like
def listThings( self, request, what ):
....
it is also crucuial to return a a response at the end of the call:
returns request.respond(...)
The @Request class offers many methods to create and send responses.
Function predicate
predicate( function )
Undocumented
Function when
when( *predicates )
The @when(…) decorate allows to specify that the wrapped method will only be executed when the given predicate (decorated with @on
) succeeds.
list
[]
list() -> new list list(sequence) -> new list initialized from sequence's items
list
['KID']
list() -> new list list(sequence) -> new list initialized from sequence's items
str
'_retro_ajax'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'_retro_ajax_json'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'_retro_isPredicate'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'_retro_on'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'_retro_on_priority'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'_retro_template'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'_retro_template_engine'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'_retro_when'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Module retro.web
Undocumented
Function unjson
unjson( value )
Undocumented
Method getPriority
getPriority( self )
Returns the priority level for this component (usually 0).
str
'_retro_isPredicate'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method onMeet
onMeet( self, callback )
Undocumented
Method isNew
isNew( self )
Tells if the session is a new session or an existing one.
Method localPath
localPath( self, path )
Returns an absolute path expressed relatively to the root.
Method session
session( self, request, create=True )
Tells if there is a session attached with this request, creating it if create
is true (by default).
This will required either Flup session middleware or Beaker session middleware to be available. The application configuration session
option will be used to determine which session middleware should be used. Beaker is the recommended one, but Flup remains the default one.
Method file
file( self, name )
Returns the file (as a cgi.FieldStorage
) which was submitted as parameter with the given name. You will have more information accessible than with get
or param
, retured as a dict with param
, filename
, contentType
and data
fields.
tuple
(<class retro.web.Component at 0x8feed4c>,)
tuple() -> an empty tuple tuple(sequence) -> tuple initialized from sequence's items
If the argument is a tuple, the return value is the same object.
Method location
location( self )
Returns the location for this component. It is guaranteed to start with a slash, and not end with one. If it starts with a slash, then nothing is returned.
Method asWSGI
asWSGI( self, startResponse, charset=None )
This is the main WSGI function handler. This is what generates the actual request and produces the response from the attached content
.
Method returns
returns( self, value=None, js=None, contentType='text/javascript', status=200, headers=None, options=None )
Undocumented
Method ensureTemplate
ensureTemplate( self, name, engine=None )
Ensures that the a template with the given name exists and returns the corresponding path, or None if not found.
This method supports KID (.kid
), Cheetah (.tmpl
) or Django(.djtml
).
Method merge
merge( self, config )
Merges the configuration from the given configuration into this one.
Method _parseExpression
_parseExpression( self, expression, isStart=True )
Handler expressions are paths (URLs) that can contain typed variables that will match integers, strings, dates, etc, and optional groups.
Typed variables are like {name:type}
(where type is optional), and optional groups are like [optional/group]
. Of course, everything can be nested.
Method app
app( self )
Undocumented
str
'QUERY_STRING'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method dispatch
dispatch( self, environ, path=None, method=None )
Figure out which handler to delegate to or send 404 or 405. This returns the handler plus a map of variables to pass to the handler.
Method notFound
notFound( self, content='Resource not found', status=404 )
Method __call__
__call__( self, environ, start_response, request=None )
Just a proxy to Dispatcher.__call__
so that Application can be directly used as an WSGI app
Class Configuration
Configuration objects allow to store configuration information for Retro applications. The supported properties are the following:
name
is the application name logfile
is the path to the log file templates
is the path to the templates directory charset
is the default charset for handling request/response data root
is the location of the server root (default .
) session
is the name of the session adapter (for now, FLUP
or BEAKER
)
It should be noted that unless absolute, paths are all relative to the configured application root, which is set by default to the current working directory when the application is first run.
Method cookies
cookies( self )
Returns the cookies (as a Cookie.SimpleCookie
instance) attached to this request.
Class Session
Undocumented
Method contentType
contentType( self )
Returns the request content type
Method cookie
cookie( self, name )
Returns the value of the given cookie or None
Method set
set( self, key, value )
Undocumented
list
['KID']
list() -> new list list(sequence) -> new list initialized from sequence's items
Method _loader
_loader( self, chunksize=None )
Returns a generator that loads the data of this request.
Method body
body( self, body= )
Gets/sets the request body (it is an alias for data)
Method _applyTemplate
_applyTemplate( self, template, engine=None, **kwargs )
Applies the given template with the given arguments, and returns a string with the serialized template. This hook is called by the display
method, so you should redefine it to suit your needs.
Method _loadPostProcess
_loadPostProcess( self )
Post-processed the data loaded by the loader.
Method clientPort
clientPort( self )
Returns the HTTP client port for this request.
Method contentLength
contentLength( self )
Returns the request content length (if any)
Method bounce
bounce( self, **kwargs )
Undocumented
Method clientIP
clientIP( self )
Returns the HTTP client IP for this request. This method will get the HTTPXFORWARDEDFOR variable instead of the REMOTEADDR if it is set.
Method _eventMet
_eventMet( self, event, observer, *args, **kwargs )
Undocumented
Method joinEvent
joinEvent( self, event )
Undocumented
Class RendezVous
Undocumented
Method __init__
__init__( self, expect=1 )
Undocumented
Class Request
A request object is initialized from data given by the containing webserver, it is not directly built by the developer. As web server receive requests, they have to build responses to fullfill the requests.
Method __init__
__init__( self, environ, charset )
This creates a new request.
Method meet
meet( self )
Undocumented
Method display
display( self, template, engine=None, **kwargs )
Returns a response built from the given template, applied with the given arguments. The engine parameters (KID, CHEETAH, DJANGO, etc) tells which engine should be used to apply the template.
Method __init__
__init__( self, name=None, description=None )
Undocumented
Method observe
observe( self, observer )
Undocumented
Method __call__
__call__( self, *args, **kwargs )
Undocumented
Method unobserve
unobserve( self, observer )
Undocumented
Method unpipe
unpipe( self, event )
Undocumented
Method pipe
pipe( self, event )
Undocumented
Method trigger
trigger( self, *args, **kwargs )
Undocumented
tuple
()
tuple() -> an empty tuple tuple(sequence) -> tuple initialized from sequence's items
If the argument is a tuple, the return value is the same object.
Method items
items( self )
Returns the key/values pairs of this configuration.
Function hasSession
hasSession( request )
Undocumented
str
'PATH_INFO'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method config
config( self, name=, value= )
Returns the configuration value for the given name. Please note that this may raise an exception if the property is not part of the configuration properties.
When no configuration property name is given, the whole configuration is returned.
Method respond
respond( self, content='', contentType=None, headers=None, status=200 )
Responds to this request.
tuple
(<class retro.core.Session at 0x8e5998c>,)
tuple() -> an empty tuple tuple(sequence) -> tuple initialized from sequence's items
If the argument is a tuple, the return value is the same object.
Method __init__
__init__( self, request, session=None )
Undocumented
Module retro.core
The Retro core module defines classes that are at the basis of writing a server-side web application. In this respect, this module defines classes:
- For
Request
and Response
management - For easy headers and cookies management
- For
Session
management - For JSON/JavaScript serialization
This module could be easily re-used in another application, as it is (almost) completely standalone and separated from Retro Web applications.
Class BeakerSession
Implementation of the Session object for Flup Session Middleware
Method isNew
isNew( self )
Undocumented
Method value
value( self, key=, value= )
Undocumented
Method expire
expire( self, time )
Undocumented
Method get
get( self, key=, value= )
Undocumented
str
'KID'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'Specifies the port on which the server should be run'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'REQUEST_METHOD'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
tuple
('STANDALONE', 'WSGIREF', 'KID')
tuple() -> an empty tuple tuple(sequence) -> tuple initialized from sequence's items
If the argument is a tuple, the return value is the same object.
str
'STANDALONE_WSGIREF'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'WSGIREF'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'Prefix to prepend to the URLs'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
str
'STANDALONE'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Function command
command( args, **extra )
Undocumented
Function has
has( feature )
Tells if your Python installation has any of the following features:
- FLUP for FCGI, SCGI servers
- WSGIREF for standalone WSGI server
- KID for template processing
Module retro
This is the main Retro module. You can generally do the following:
from retro import *
class MyCompoment(Component):
@on("/index.html")
def main( self, request ):
return request.respond("Hello World!")
if __name__ == "__main__":
run(Application(MyCompoment()), STANDALONE)
All important classes, functions and decorators are made available through this module, so you should not have to bother with anything else.
str
'0.0.0.0'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Function run
run( app=None, components=(), method='STANDALONE', name='retro', root='.', resetlog=False, address='', port=None, prefix='', async=False, sessions=False, withReactor=None, processStack= at 0x90064c4>, runCondition=True )
Runs this web application with the given method (easiest one is STANDALONE), with the given root (directory from where the web app-related resource will be resolved).
This function is the main
for your web application, so this is basically the last call you should have in your web application main.
Method load
load( self, chunksize=None )
Loads the (POST) data of this request. The optional @chunksize argument tells the number of bytes the should be read. This function is used internally, and only useful in an external use if you want to split the loading of the data into multiple chunks (using an iterator).
This allows you not to block the processing and requests and do things like a progress indicator.
This function will return you the percentage of the data loaded (an int from 0 to 100).
Here is an example of how to split the loading into
while request.load(1024) < 100:
# Do something
Method __repr__
__repr__( self )
Undocumented
Method params
params( self )
Returns a dictionary with the request parameters
Method _compileCheetahTemplateDeps
_compileCheetahTemplateDeps( self, path )
Undocumented
wrapper_descriptor
1.init(...) initializes x; see x.class.doc_ for signature
Class Response
A response is sent to a client that sent a request.
Method name
name( self )
Returns the name for the component.
Method name
name( self )
Returns the name for the component.
Method has
has( self, name )
Tells if the request has the given parameter.
Method __call__
__call__( self, request, **kwargs )
Undocumented
Bases
Methods
Functions
Values
str
'_retro_on_priority'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method setPriority
setPriority( self, level )
Sets the priority level for this component. The component priority level (0 by default) will be added to the individual dispatcher priorities.
Method prepare
prepare( self )
Sets default headers for the request before sending it.
Function display
display( template, engine= )
The @display(template) decorator can be used to indicate that the decorated handler will display the given page (only when it returns None).
The first argument is the template name with or without the extension ( it can be guessed at runtime). The second argument is the engine (by default, it will be guessed from the extension)
Function hasSession
hasSession( request )
Tells if there is a session related to the given request, and returns it if found. If not found, returns None
Method session
session( self, request, create=True )
Tells if there is a session attached with this request, creating it if create
is true (by default).
This will required either Flup session middleware or Beaker session middleware to be available. The application configuration session
option will be used to determine which session middleware should be used. Beaker is the recommended one, but Flup remains the default one.
Method set
set( self, name, value )
Sets the given property with the given value.
Method uri
uri( self )
Returns the URI for this method.
int
int(x, base) -> integer
Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead.
Method context
context( self )
Undocumented
Function predicate
predicate( function )
Undocumented
Method on
on( self, expression, prefix='', handlers={}, priority=0 )
Tells that the given list of http methods will be handled by the associated handlers for the given expression. For instance, you can use `on("/{path}", GET=myGetHandler, POST=myPostHandler)
Method get
get( self, key )
Undocumented
str
'REQUEST_URI'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Function decomposeExpression
decomposeExpression( expression )
Converts the given expression pattern into a list of chunks
that are tuples (t, chunk), where t
is u
when the chunk is a litteral url, v
when the chunk is a variable, and uo
or vo
when the chunk is optional.
Method setHeader
setHeader( self, name, value, replace=True )
Sets the given header with the given value. If there is already a value and that replace is Fasle, nothing will be done.
Class ApplicationError
Undocumented
getset_descriptor
Undocumented
Method get
get( self, key=, value= )
Alias to self.value(key,value)
str
'_retro_ajax_json'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Class Application
Undocumented
Method fail
fail( self, content=None, status=412, headers=None )
Returns an Error 412 with the given content
Method init
init( self )
Init is called when the component is registered within its parent application. You can redefine this method to make your custom initialization.
Method dispatcher
dispatcher( self )
The dispatcher is the main interface between the RW app and the webserver. This returns the dispatcher currently bound to the application.
Method respondMultiple
respondMultiple( self, bodies='', contentType='text/html', headers=None, status=200 )
Response with multiple bodies returned by the given sequence or iterator. This allows to implement server push
very easily.
Function log
log( *args )
A log function that outputs information on stdout. It's a good idea to replace this function by another if you want to have a custom logger.
Method produceOn
produceOn( self, event )
Guards the production of the response by this event. This allows the reactor (if any) to now when to start.
Function introspect
introspect( component )
Returns a list of (name, method, {on:…,priority:…,template:…,ajax:…}) for each slot that was decorated by Retro decorators.
Method log
log( self, *args )
A function to easily log data to the logfile.
Method __call__
__call__( self, request, **kwargs )
Undocumented
Method __str__
__str__( self )
Undocumented
Method method
method( self )
Returns the method (GET, POST, etc) for this request.
dict
{'digits': ('\\d+', <type 'int'>), 'word': ('\\w+', <type 'str'>), 'string': ('[^/]+', <type 'str'>), 'int': ('\\-?\\d+', <type 'int'>), 'chunk': ('[^/^.]+', <type 'str'>), 'float': ('\\-?\\d*.?\\d+', <type 'float'>), 'number': ('\\-?\\d*\\.?\\d+', <function <lambda> at 0x8ffb3e4>), 'rest': ('.+', <type 'str'>), 'range': ('\\-?\\d*\\:\\-?\\d*', <function <lambda> at 0x8ffb41c>), 'file': ('\\w+(.\\w+)', <type 'str'>), 'integer': ('\\-?\\d+', <type 'int'>), 'alpha': ('[a-zA-Z]+', <type 'str'>), 'path': ('.+', <type 'str'>), 'segment': ('[^/]+', <type 'str'>), 'any': ('.+', <type 'str'>)}
dict() -> new empty dictionary. dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs. dict(seq) -> new dictionary initialized as if via: d = {} for k, v in seq: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
bool
bool(x) -> bool
Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.
str
'SCRIPT_NAME'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method getPriority
getPriority( self )
Returns the priority level for this component (usually 0).
Method setPriority
setPriority( self, level )
Sets the priority level for this component. The component priority level (0 by default) will be added to the individual dispatcher priorities.
Method setdefault
setdefault( self, name, value )
Sets the given property with the given value only if the property did not exist before.
Method location
location( self )
Returns the location of this application. The location will not finish by a slash. If the prefix is /
then an empty string will be returned.
str
'CONTENT_LENGTH'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method context
context( self )
Undocumented
str
'_retro_template_engine'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method data
data( self, data= )
Gets/sets the request data (it is an alias for body)
Function json
json( value, *args, **kwargs )
Undocumented
Method asString
asString( self )
Undocumented
Method registerHandler
registerHandler( self, handler, urls, priority=0 )
This method takes a function, a list of (HTTPMethod, DispatcherExpression) and a priority, describing a handler for a specific URL within this component. The parameters are actually the same as the ones given to the @on
decorator.
Method asJS
asJS( self, asJSON )
Undocumented
Class ValidationError
Validation errors should be raised by @Component handlers when the given parameters (for instance, POST parameters) are not as expected.
Module retro.web
Undocumented
Method _abspath
_abspath( self, path )
Ensures that the given path is absolute. It will be made relative to the root if it is not already absolute.
Method applyTemplate
applyTemplate( self, name, engine=None, **kwargs )
Applies the the given arguments to the template with the given name. This returns a string with the expanded template. This automatically uses the proper template engine, depending on the extension:
.kid
for KID templates .tmpl
for Cheetah templates .dtmpl
for Django templates
Method redirect
redirect( self, url, **kwargs )
Responds to this request by a redirection to the following URL, with the given keyword arguments as parameter.
Method registerHandler
registerHandler( self, handler, urls, priority=0 )
This method takes a function, a list of (HTTPMethod, DispatcherExpression) and a priority, describing a handler for a specific URL within this component. The parameters are actually the same as the ones given to the @on
decorator.
Method load
load( self, path )
Undocumented
Method headers
headers( self )
Undocumented
Class TemplateWrapper
This class allows to wrap a function so that it will display the resulting template. This should not be instanciated by the user, but it may be good to know that is is created by the Application during the @register phase.
dict
{400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.')}
dict() -> new empty dictionary. dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs. dict(seq) -> new dictionary initialized as if via: d = {} for k, v in seq: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
list
[]
list() -> new list list(sequence) -> new list initialized from sequence's items
Class Dispatcher
Dispatcher is a WSGI middleware loosely inspired from Luke Arno own Selector module, only more tailored to the needs of Retro (that is trimmed down and slightly extended).
The dispatcher is used as follows:
- Handlers are registered using the @on method
- The dispatch method is called by the Web application
- Dispatcher tries to identify a matching handler
- It processes the URL into a dict of variables (as declared)
- The @_call_ method is invoked
- The handler is invoked with the generated variables
For the story, the main reason for re-implementing Selector instead of subclassing it was a license problem: I wanted Retro to be BSD, while Selector was GPLed.
Method __init__
__init__( self, components=(), prefix='', config=None, defaults=None )
Undocumented
Method param
param( self, name )
Gets the parameter with the given name. It is an alias for get
Method __init__
__init__( self, defaults={}, path=None )
Undocumented
str
'CONTENT_TYPE'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method log
log( self, *args )
Undocumented
Class DispatcherSyntaxError
These errors are raised by the @Dispatcher when the syntax is not as expected.
Method init
init( self )
Init is called when the component is registered within its parent application. You can redefine this method to make your custom initialization.
str
'SCRIPT_ROOT'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method get
get( self, name, value= )
Returns the value bound to the given property.
Class AJAXWrapper
This class allows to wrap a function so that its result will be returned as a JavaScript (JSON) object. As with the @TemplateWrapper. this should be not instanciated directly by the user, as it is automatically created by the @Application upon component registration.
Method get
get( self, name )
Gets the parameter with the given name. It is an alias for param
Method log
log( self, *args )
Undocumented
Method referer
referer( self )
Rerturns the HTTP referer for this request.
Method component
component( self, nameOrClass )
Returns the component with the given class name (not case sensitive) or the component(s) that are instances of the given class. If no component matches, None
is returned, otherwise the component is returned, if there are many, a list of components is returned.
str
'_retro_on'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Class Component
A Component is a class that contains methods that can handle URLs. Use the decorators provided by Retro and register the component into the application.
Method value
value( self, key=, value= )
Sets or gets the value
bound to the given key
Method __init__
__init__( self, app )
Creates a new Dispatcher instance. The @handlers attribute stores couple of (regexp, httphandlers).
Bases
Methods
Functions
Values
Method load
load( self, path )
Loads the file at the given path and returns its content.
Method session
session( self, name=, value= )
Invokes this request component session
method, and returns a couple (session, sessionState)
Method save
save( self, path )
Undocumented
str
'HTTP_COOKIE'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method notSupported
notSupported( self, request )
Undocumented
str
'_retro_template'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Function on
on( priority=0, **methods )
The @on decorator is one of the main important things you will use within Retro. This decorator allows to wrap an existing method and indicate that it will be used to process an HTTP request.
The @on decorator can take GET
and POST
arguments, which take either a string or a list of strings, each describing an URI pattern (see @Dispatcher) that when matched, will trigger the method.
The decorated method must take a request
argument, as well as the same arguments as those used in the pattern.
For instance:
@on(GET='/list/{what:string}'
implies that the wrapped method is like
def listThings( self, request, what ):
....
it is also crucuial to return a a response at the end of the call:
returns request.respond(...)
The @Request class offers many methods to create and send responses.
str
''
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method setContentType
setContentType( self, mimeType )
Undocumented
Method __init__
__init__( self )
Undocumented
str
'_retro_ajax'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method environ
environ( self, name=, value= )
Gets or sets the environment attached to this request
Method __call__
__call__( self, environ, start_response, request=None )
Delegate request to the appropriate Application. This is the main method of the dispatcher.
Method notFound
notFound( self, request )
Undocumented
str
'GET'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method app
app( self )
Returns a reference to the Retro application bound to this dispatcher.
Method hasHeader
hasHeader( self, name )
Tells if the given header exists. If so, it returns its value (which cannot be None), or None if it was not found
Method set
set( self, key, value )
Undocumented
Function ajax
ajax( priority=0, **methods )
The @ajax decorator is a variation of the @on decorator. The @ajax decorator allows you to expose an existing Python function as a JavaScript (or JSON) producing method.
Basically, the @ajax decorator allows you to automatically bind a method to an URL and to ensure that the result will be JSON-ified before being sent. This is perfect if you have an existing python class and want to expose it to the web.
Class WebRuntimeError
Undocumented
Method loaded
loaded( self )
Returns the percentage (value between 0 and 100) of this request data that was loaded.
Method __init__
__init__( self, component, function, template, engine )
Undocumented
Method register
register( self, *components )
Registeres the given component into this Web application. The component handlers will be bound to the proper URLs, and the component consistency will be checked against available resources.
This is where all the "gluing" occurs. The component attriutes are introspected to see if there are decorated with Retro decorators. If so, then the corresponding registration/initialization is made.
Function when
when( *predicates )
The @when(…) decorate allows to specify that the wrapped method will only be executed when the given predicate (decorated with @on
) succeeds.
Method __init__
__init__( self, message, explanation=None, exception=None )
Undocumented
str
'text/html'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Bases
Classes
Methods
Inhertied Methods
Inhertied Functions
Inhertied Values
Method respondFile
respondFile( self, path, contentType=None, status=200 )
Responds with a local file. The content type is guessed using the mimetypes
module. If the file is not found in the local filesystem, and exception is raised.
Method configure
configure( self, **kwargs )
Configures this application. The arguments you can use as the same as the properites offered by the Configuration
objects.
Method processBurstChannel
processBurstChannel( self, request )
The postRequest
method implements a mechanism that allows the Retro burst channel to work properly. It allows to put multiple requests into a single request, and then put the corresponding responses withing the body of this request.
Method __init__
__init__( self, content=None, headers=None, status=200, reason=None, produceWhen=None )
Undocumented
str
'_retro_when'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method get
get( self, key )
Undocumented
str
'POST'
str(object) -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
Method rootPath
rootPath( self )
Returns the absolute path where this application is rooted. This is only set at the execution.
This is an alias for config("root")
Method __init__
__init__( self, name=None )
Undocumented
Method app
app( self )
Undocumented
Function asJSON
asJSON( value, **options )
Converts the given value to a JSON representation. This function is an enhanced version of simplejson
, because it supports more datatypes (datetime, struct_time) and provides more flexibilty in how values can be serialized.
Specifically, the given value
contains a asJS
or asJSON
method, this method will be invoked with this function as first argument and the options as keyword-arguments (**options
)
Method processBurstChannel
processBurstChannel( self, request )
The postRequest
method implements a mechanism that allows the Retro burst channel to work properly. It allows to put multiple requests into a single request, and then put the corresponding responses withing the body of this request.
Method __init__
__init__( self, component, function )
Undocumented
Method header
header( self, name )
Undocumented