Pluggdapps

Component system. Web framework. And more ...

interfaces – Web framework Interface specs.

Module contents

class pluggdapps.web.interfaces.IHTTPRouter[source]

Bases: pluggdapps.plugin.Interface

Interface specification for resolving application request to view callable. A plugin implementing this interfaces, typically, compares request’s url, method and few other header fields with pre-configured router mapping, added via add_view() method, and resolve the request to view callable.

The router plugin will be instantiated by the web-application during boot time and re-used till the platform is shutdown.

onboot()[source]

Chained call from IWebApp.startapp(). Implementation can chain this onboot() call further down to other framwork / application plugins.

While building a web application, this method can be used to configure url route-mapping by calling add_view() or by parsing a mapper file. In any case, when this method returns, route-mapping must be compiled and cached for resolving request’s view-callables.

add_view(*args, **kwargs)[source]

A view is the representation of a resource. During boot-time applications can add resource representation as callables using this API. Since there can be more than one representation of a resource, there can be more than one view-callable for the same request-URL. In which case the view callable had to be resolved based on request predicates.

args and kwargs specific to router plugins, for more details refer to the corresponding router plugin.

route(request, c)[source]

Resolve request to view-callable. For a successful match, populate relevant attributes, like matchdict and view, in request plugin. A view-callable can be a plain python callable that accepts request and context arguments or a plugin implementing IHTTPView interface.

request,
Plugin instance implementing IHTTPRequest interface.
c
Context dictionary for response, and templates.
urlpath(request, *args, **kwargs)[source]

Generate path, including query and fragment (aka anchor), for request using positional arguments args and keyword arguments kwargs. Refer to corresponding router plugin for specific signature for positional and key-word arguments. Returns urlpath string. This does not include SCRIPT_NAME, netlocation and scheme.

request,
Plugin instance implementing IHTTPRequest interface.
onfinish(request)[source]

Callback for asyncrhonous finish(). Means the response is sent and the request is forgotten. Chained call originating from IHTTPResponse.onfinish().

request,
Plugin instance implementing IHTTPRequest interface.
class pluggdapps.web.interfaces.IHTTPNegotiator[source]

Bases: pluggdapps.plugin.Interface

Interface specification to handle server side negotiation for resource variant.

negotiate(request, variants)[source]

When the router finds that a resource (typically indicated by the request-URL) has multiple representations, where each representation is called a variant, it has to pick the best representation negotiated by the client. Negotiation is handled through attributes like media-type, language, charset and content-encoding.

request,
Plugin instance implementing IHTTPRequest interface.
variants,
Dictionary of view configuration containing the following keys, media_type, charset, content_coding, language.

Returns the best matching variant from variants.

class pluggdapps.web.interfaces.IHTTPResource[source]

Bases: pluggdapps.plugin.Interface

Interface specification for resource or model plugins. Resource plugins can be configured for view-callables. In which case they are expected to be called before calling view-callable. They can lookup backend database and populate context that can be consumed by view-callable and view-template.

__call__(request, c)[source]

Resource object to gather necessary data before a request is handled by the view (and templates). Return updated pluggdapps.utils.lib.Context. The context dictionary is also preserved in the pluggdapps.web.interfaces.IHTTPResponse plugin for chunked transfer-encoding.

request,
Plugin instance implementing IHTTPRequest interface.
c,
Context dictionary to be passed on to view callables and eventually to view-templates.
class pluggdapps.web.interfaces.IHTTPCookie[source]

Bases: pluggdapps.plugin.Interface

Handle HTTP cookies. This specification is compatible with IHTTPRequest and python’s Cookie standard library.

parse_cookies(headers)[source]

Use HTTP headers dictionary, to parse cookie name/value pairs, along with its meta-information, into Cookie Morsels. Get the cookie string from headers like,

1
headers.get( 'cookie', '' ) 

Return a SimpleCookie object from python’s standard-library.

Update cookies dictionary with cookie name and its morsel. Optional Key-word arguments, typically, contain domain, expires_days, expires, path, which are set on the Cookie.Morsel directly.

cookies,
Dictionary like object mapping cookie name and its morsel. It is updated inplace and returned back
name,
cookie name as string value.
morsel,
A string value or http.cookies morsel from python’s standard library.

See http://docs.python.org/library/cookie.html#morsel-objects for available attributes.

create_signed_value(name, value)[source]

Encode name and value string into byte-string using ‘utf-8’ encoding settings, convert value into base64. Return signed value as string,:

<base64-encoded-value>|<timestamp>|<signature>

<signature> is generated using a secret, name, base64 encoded value and timestamp-in-seconds.

decode_signed_value(name, value)[source]

Reverse of create_signed_value. Returns orignal value string.

class pluggdapps.web.interfaces.IHTTPRequest(httpconn, method, uri, uriparts, version, headers)[source]

Bases: pluggdapps.plugin.Interface

Interface specification to encapulate HTTP request.

httpconn = None

IHTTPConnection plugin instance. Initialized during plugin instantiation.

method = b''

HTTP request method, e.g. b’GET’ or b’POST’. Initialized during plugin instantiation.

uri = b''

HTTP Request URI in byte-string as found in request start-line. Initialized during plugin instantiation.

version = b''

HTTP protocol version found in request start-line, e.g. b’HTTP/1.1’. Initialized during plugin instantiation.

headers = {}

Dictionary-like object for HTTP headers. Key name are in string, while values are in byte-string. Initialized during plugin instantiation.

body = b''

Request body, if present, as a byte string.

chunks = []

List of request chunks. Matching view-callable will be called for every request chunk, stored as the last element in this list, that are received. It is upto the application logic to clear previous chunks or to preserve them, until the request is finished.

trailers = {}

Similar to headers attribute. But received after the last chunk of request in chunked transfer-coding.

uriparts = {}

UserDict object of uri parts in decoded, parsed and unquoted form. scheme, netloc, path, query, fragment, username, password, hostname, port, script, keys are available. Except query, which is a dictionary of query arguments, all other values are in string.

cookies = {}

A dictionary of http.cookies.Morsel objects representing request ” cookies from client.

getparams = {}

GET arguments are available in the params property, which maps parameter names to lists of values (to support multiple values for individual names). Names and values are are of type str, where, response.charset will be used to decode the byte values.

postparams = {}

POST arguments are available in the params property, which maps parameter names to lists of values (to support multiple values for individual names). Names and values are are of type str, where, response.charset will be used to decode the byte values.

multiparts = {}

POST arguments in multipart format (like uploaded file content) are available as a dictionary of name,value pairs.

params = {}

Combined arguments of GET/POST, which maps parameter names to lists of values (to support multiple values for individual names). Names and values are are of type str, where, response.charset will be used to decode the byte values.

files = {}

File uploads are available in this attribute as a dictionary of name and a list of files submited under name. File is a dictionary of,:

{ 'filename' : ...,
  'value' : ...,
  'content-type' : ... }
session = None

If a session factory has been configured, this attribute will represent the current user’s session object.

cookie = None

IHTTPCookie plugin instance to handle request and response cookies.

response = None

Response object corresponding to this request. The object is an instance of plugin implementing IHTTPResponse interface.

router = None

IHTTPRouter plugin resolving this request.

matchdict = {}

Optinal dictionary attribute that contains maps a variable portion of url with matched value.

view = None

A view-callable resolved for this request.

resource = None

When a view is resolved, along with that an optional resource callable might be available. If so this attribute can be one of the following,

  • plugin implementing IHTTPResource interface.
  • An importable string which points to a callable object.
  • Or any python callable object.
receivedat = 0

Timestamp when request was recieved

finishedat = 0

Timestamp when request was finished.

__init__(httpconn, method, uri, uriparts, version, headers)[source]

Instance of plugin implementing this interface corresponds to a single HTTP request. Note that instantiating this class does not essentially mean the entire request is received. Only when IHTTPRequest.handle() is called complete request is available and partially parsed.

httpconn,
IHTTPConnection plugin instance
method,
Request method in byte-string.
uri,
Request URI in byte-string from request message.
uriparts,
Dictionary of uriparts after uri is used to resolve webapp. SCRIPT and PATH are adjusted according to resolved web-application.
version,
Request version in byte-string.
headers,
Dictionary request headers. Key names in this dictionary will be decoded to string-type. Value names will be preserved as byte-string.

When a request object is instantiated no assumption should be made about the web application framework. Only processing of request init parameters are allowed.

supports_http_1_1()[source]

Returns True if this request supports HTTP/1.1 semantics

get_ssl_certificate()[source]

Returns the client’s SSL certificate, if any. To use client certificates, cert_reqs configuration value must be set to ssl.CERT_REQUIRED. The return value is a dictionary, see SSLSocket.getpeercert() in the standard library for more details. http://docs.python.org/library/ssl.html#sslsocket-objects.

Gets the value of the cookie with the given name, else return default. Call to this method is valid only after handle() is called.

Returns a signed cookie if it validates, or None. Call to this method is valid only after handle() is called. Refer to IHTTPCookie interface specification to learn more about secure-signing cookies.

has_finished()[source]

Return True if this request is considered finished, which is, when the flush( finishing=True ) method is called on IHTTPResponse.

ischunked()[source]

Returns True if this request is received using chunked Transfer-Encoding.

handle(body=None, chunk=None, trailers=None)[source]

Typically called by IWebApp plugin, after the request is resolved for a web-application. Along with applying in-bound request transformers, the method will initialize most of the attributes under this specification.

body,
Optional kwarg, if request body is present. Passed as byte-string.
chunk,
Optional kwarg, if request is received in chunks. Chunk received as a tuple of, (chunk_size, chunk_ext, chunk_data).
trailers,
Optional kwarg, if chunked-request is over and final trailer was also received.
onfinish()[source]

Callback for asyncrhonous finish(). Means the response is sent and the request is forgotten. Called by IHTTPResponse.onfinish(). It is the responsibility of this plugin to dispatch onfinish() calls on view-callable and web-application plugins.

urlfor(name, **matchdict)[source]

Use request.webapp.urlfor() to generate the url.

pathfor(name, **matchdict)[source]

Use request.webapp.pathfor() to generate the url.

appurl(instkey, name, **matchdict)[source]

Generate url for a different web-application identified by instkey. Typically uses webapp.appurl().

instkey,
A tuple of (appsec, netpath, configini) indexes into platform’s webapps attribute
class pluggdapps.web.interfaces.IHTTPResponse(request)[source]

Bases: pluggdapps.plugin.Interface

Interface specification to encapulate HTTP response.

statuscode = b''

Response status code in byte-string.

reason = b''

Reason byte-string for response status.

version = b''

HTTP protocol version, in byte-string, supported by this server.

headers = {}

HTTP header dictionary to sent in the response message.

body = b''

Response body, if present, as a byte string.

chunks = []

List of response chunks. It is the responsibility of the implementing plugin to remove or keep the previous chunks in this list. For chunked response atleast one chunk must be present.

trailers = {}

In chunked transfer-coding, HTTP header dictionary to be sent after the last chunk is transfered.

setcookies = {}

A dictionary of Cookie.Morsel objects representing a new set of cookies to be set on the client side.

request = None

Plugin instance implementing IHTTPRequest interface.

context = None

A dictionary like object that will be passed to resource objects and view callables, and eventually to template code.

media_type = None

If route configuration or content-negotiation supplies media_type specification, this attribute will be set with supplied value before calling view-callable. View-callable can also override this attribute, the media-type header field is normally set in out-bound-transformer plugin ResponseHeaders.

charset = None

If route configuration or content-negotiation supplies charset specification, this attribute will be set with supplied value before calling view-callable. View-callable can also override this attribute, the charset header field is normally set in out-bound-transformer plugin ResponseHeaders.

language = None

If route configuration or content-negotiation supplies language specification, this attribute will be set with supplied value before calling view-callable. View-callable can also override this attribute, the language header field is normally set in out-bound-transformer plugin ResponseHeaders.

content_coding = None

If route configuration or content-negotiation supplies content-encoding specification, this attribute will be set with supplied value before calling view-callable. View-callable can also override this attribute, the content-encoding header field is normally set in out-bound-transformer plugin ResponseHeaders.

__init__(request)[source]

Instantiate a response plugin for a corresponding request plugin.

request,
Is an instance object for plugin implementing IHTTPResponse interface.
set_status(code)[source]

Set a response status code. By default it will be 200.

set_header(name, value)[source]

Sets the given response header name and value. If there is already a response header by name present, it will be overwritten. Returns the new value for header name as byte-string.

name,
byte-string of header field name, in lower case.
value,
any type, which can be converted to string.
add_header(name, value)[source]

Similar to set_header() except that, if there is already a response header by name present, value will be appended to existing value using ‘,’ seperator. Returns the new value for header name as byte-string.

name,
byte-string of header field name, in lower case.
value,
Any type which can be converted to string.
set_trailer(name, value)[source]

Sets the given chunk trailing header, name and value. If there is already a trailing header by name present, it will be overwritten. Returns the new value for header name as byte-string.

name,
byte-string of header field name, in lower case.
value,
any type, which can be converted to string.
add_trailer(name, value)[source]

Similar to set_trailer() except that, if there is already a trailing header by name present, value will be appended to existing value using ‘,’ seperator. Returns the new value for header name as byte-string.

name,
byte-string of header field name, in lower case.
value,
any type, which can be converted to string.

Set cookie name/value with optional kwargs. Key-word arguments typically contains, domain, expires_days, expires, path. Additional keyword arguments are set on the Cookie.Morsel directly. By calling this method cookies attribute will be updated inplace. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes.

Similar to set_cookie() method, additionally signs and timestamps a cookie value so it cannot be forged. Uses IHTTPCookie.create_signed_value() method to sign the cookie. To read a cookie set with this method, use get_secure_cookie().

Deletes the cookie with the given name. Note that setcookies will still contain cookie-name name, only that it is set to expire in the client side. Return the original value of the cookie.

clear_all_cookies()[source]

Deletes all the cookies the user sent with this request.

set_finish_callback(callback)[source]

Subscribe a callback function, to be called when this response is finished.

has_finished()[source]

Return True if finish() method is called on IHTTPResponse.

isstarted()[source]

For chunked-encoding, returns a boolean, if True means the response has started and response headers are written.

ischunked()[source]

Returns True if this response is transferred using chunked Transfer-Encoding.

write(data)[source]

Writes the given chunk to the output buffer. To actually write the output to the network, use the flush() method below.

data,
byte-string of data to buffer for writing to socket.
flush(finishing=False, callback=None)[source]

Flushes the response-header (if not written already) to the socket connection. Then flushes the write-buffer to the socket connection.

finishing,
If True, signifies that data written since the last flush() on this response instance is the last chunk. It will also flush the trailers at the end of the chunked response. In non-chunked mode, it is signifies that the body is done.
callback,
If given, can be used for flow control it will be run when all flushed data has been written to the socket.
httperror(status_code=500, message=b'')[source]

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

It is the caller’s responsibility to finish the request, by calling finish().

render(*args, **kwargs)[source]

Use the view configuration parameter ‘IHTTPRenderer’ to invoke the view plugin and apply IHTTPRenderer.render() method with request, c, args and kwargs.

chunk_generator(callback, request, c)[source]

A python generate which returns a response chunk for every iteration.

chunk_generator(callback, request, c)[source]

A python generate which returns a response chunk for every iteration.

class pluggdapps.web.interfaces.IHTTPView(viewname, view)[source]

Bases: pluggdapps.plugin.Interface

viewname = ''

String name that maps into IHTTPRouter.views dictionary.

view = {}

Dictionary of view predicates for which this view-callbale was resolved.

__init__(viewname, view)[source]

Instantiate plugin with viewname and view attributes.

__call__(request, c)[source]

In the absence of method specific attributes or if the resolver cannot find an instance attribute to apply the handler call back, the object will simply be called.

request,
Plugin instance implementing IHTTPRequest interface.
c,
Dictionary like Context object. Typically populated by IHTTPResource and view-callable. Made availabe inside HTML templates.
onfinish(request)[source]

Optional callable attribute, if present will be called at the end of a request, after the response has been sent to the client. Note that this is not the same as close callback, which is called when the connection get closed. In this case the connection may or may not remain open. Refer to HTTP/1.1 spec.

request,
Plugin instance implementing IHTTPRequest interface.
class pluggdapps.web.interfaces.IHTTPInBound[source]

Bases: pluggdapps.plugin.Interface

Specification to transform response headers and body. A chain of transforms can be configured on IWebApp plugin.

transform(request, data, finishing=False)[source]

Transform in-coming message entity. request will be updated in place. Returns the transformed request data.

request,
IHTTPRequest plugin whose request.response attribute is being transformed.
data,
Either request body or chunk data (in case of chunked encoding) in byte-string.
finishing,
In case of chunked encoding, this denotes whether this is the last chunk to be received.
class pluggdapps.web.interfaces.IHTTPOutBound[source]

Bases: pluggdapps.plugin.Interface

Specification to transform response headers and message-body. A chain of transforms can be configured on IWebApp plugin.

transform(request, data, finishing=False)[source]

Transform out-going message entity. request.response will be updated inplace.

request,
IHTTPRequest plugin and its response attribute which is being transformed.
data,
Either response body or chunk data (in case of chunked encoding) in byte-string.
finishing,
In case of chunked encoding, this denotes whether this is the last chunk to be transmitted.
class pluggdapps.web.interfaces.IHTTPLiveDebug[source]

Bases: pluggdapps.plugin.Interface

Catch exceptions in application code and handle them. Typically the exceptions can be formated and logged and/or sent as email and/or rendered as html page in debug mode and optionally provide interactive debugging via browser.

render(request, etype, value, tb)[source]

Handle exception in the context of a HTTP request request. (etype, value, tb) tuple is what is returned by sys.exc_info().

Return a web page, capable of live debuging.