Asynchronous Content¶
The pulsar.apps.wsgi.content introduces several utility classes for
handling asynchronous content within a WSGI handler or
middleware.
These classes can operate instead or in conjunction with a template engine,
their main purpose is to do what a web framework does: to provide a set of
tools working together to concatenate strings to return as a
response to an HTTP client request.
A string can be html, json, plain text or any other valid HTTP
content type.
The main class of this module is the String, which can be
considered as the atomic component of an asynchronous web framework:
>>> from pulsar.apps.wsgi import String
>>> string = String('Hello')
>>> string.render()
'Hello'
>>> string.render()
...
RuntimeError: String already streamed
An String can only be rendered once, and it accepts
asynchronous components:
>>> a = Future()
>>> string = String('Hello, ', a)
>>> value = string.render()
>>> value
MultiFuture (pending)
>>> value.done()
False
Once the future is done, we have the concatenated string:
>>> a.set_result('World!')
'World!'
>>> value.done()
True
>>> value.result()
'Hello, World!'
Design¶
The do_stream() method is responsible for the streaming
of strings or asynchronous components.
It can be overwritten by subclasses to customise the way an
String streams its children.
On the other hand, the to_string() method is responsible
for the concatenation of strings and, like do_stream(),
it can be customised by subclasses.
Asynchronous String¶
-
class
pulsar.apps.wsgi.content.String(*children, **params)[source]¶ An asynchronous string which can be used with pulsar WSGI servers.
-
append(child)[source]¶ Append
childto the list ofchildren.Parameters: child – String, bytes or another String. If it is anString, this instance will be set as itsparent. IfchildisNone, this method does nothing.
-
before_render(callback)[source]¶ Add a callback to be executed before this content is rendered
The callback accept
requestandselfas the only two arguments
-
children¶ A copy of all children of this
String.Children can be other
Stringor string or bytes, depending on implementation.childrenare added and removed via theappend()andremove()methods.
-
do_stream(request)[source]¶ Returns an iterable over strings or asynchronous components.
If asynchronous elements are included in the iterable, when called, they must result in strings. This method can be re-implemented by subclasses and should not be invoked directly. Use the
stream()method instead.
-
has_default_content_type¶ Trueif this is as the default content type.
-
http_response(request, *stream)[source]¶ Return a
WsgiResponseor aFuture.This method asynchronously wait for
stream()and subsequently returns aWsgiResponse.
-
prepend(child)[source]¶ Prepend
childto the list ofchildren.This is a shortcut for the
insert()method at index 0.Parameters: child – String, bytes or another String. If it is anString, this instance will be set as itsparent. IfchildisNone, this method does nothing.
-
render(request=None, callback=None)[source]¶ Render this string.
This method returns a string or a
Futurewhich results in a string. On the other hand, the callable method of aStringalways returns aFuture.
-
stream(request)[source]¶ An iterable over strings or asynchronous elements.
This is the most important method of an
String. It is called byhttp_response()or by theparentof thisString. It returns an iterable (list, tuple or a generator) over strings (unicode/strfor python 2,stronly for python 3) or asynchronous elements which result in strings. This method can be called once only, otherwise aRuntimeErroroccurs.This method should not be overwritten, instead one should use the
do_stream()to customise behaviour.
-
Asynchronous Json¶
-
class
pulsar.apps.wsgi.content.Json(*children, **params)[source]¶ An
Stringwhich renders into a json string.The
String.content_typeattribute is set toapplication/json.-
as_list¶ If
True, the content is always a list of objects. DefaultFalse.
-
parameters¶ Additional dictionary of parameters passed during initialisation.
-
Asynchronous Html¶
-
class
pulsar.apps.wsgi.content.Html(tag, *children, **params)[source]¶ An
Stringforhtmlcontent.The
content_typeattribute is set totext/html.Parameters: - tag – Set the
tagattribute. Must be given and can beNone. - children – Optional children which will be added via the
append()method. - params –
Optional keyed-value parameters including:
cnclass name or list of class names.attrdictionary of attributes to add.datadictionary of data to add (rendered as HTML data attribute).typetype of element, only supported for tags which accept thetypeattribute (for example theinputtag).
-
add_media(request)[source]¶ Invoked just before streaming this content.
It can be used to add media entries to the document.
TODO: more docs
-
attr(*args)[source]¶ Add the specific attribute to the attribute dictionary with key
nameand valuevalueand returnself.
-
css(mapping=None)[source]¶ Update the css dictionary if
mappingis a dictionary, otherwise return the css value atmapping.If
mappingis not given, return the wholecssdictionary if available.
-
get_form_value()[source]¶ Return the value of this
Htmlelement when it is contained in a Html form element.For most element it gets the
valueattribute.
-
set_form_value(value)[source]¶ Set the value of this
Htmlelement when it is contained in a Html form element. For most element it sets thevalueattribute.
-
tag¶ The tag for this HTML element.
One of
div,a,tableand so forth. It can beNone.
- tag – Set the
Html Document¶
The HtmlDocument class is a python representation of an
HTML5 document, the latest standard for HTML.
It can be used to build a web site page in a pythonic fashion rather than
using template languages:
>>> from pulsar.apps.wsgi import HtmlDocument
>>> doc = HtmlDocument(title='My great page title')
>>> doc.head.add_meta(name="description", content=...)
>>> doc.head.scripts.append('jquery')
...
>>> doc.body.append(...)
Document¶
-
class
pulsar.apps.wsgi.content.HtmlDocument(title=None, media_path='/media/', charset=None, minified=False, loop=None, asset_protocol=None, **params)[source]¶ An
Htmlcomponent rendered as an HTML5 document.An instance of this class can be obtained via the
WsgiRequest.html_documentattribute.-
head¶ The
Headpart of thisHtmlDocument
-
body¶ The body part of this
HtmlDocument, anHtmlelement
-
Head¶
-
class
pulsar.apps.wsgi.content.Head(media_path=None, title=None, meta=None, minified=False, asset_protocol=None, **params)[source]¶ HtmlDocumentheadtag element.Contains
Htmlattributes for the various part of an HTML Head element. The head element is accessed via theHtmlDocument.headattribute.-
title¶ Text in the
titletag.
-
meta¶ A container of
Htmlmetatags. To add new meta tags use theadd_meta()method rather than accessing themetaattribute directly.
-
embedded_js¶ Javascript embedded in the html page.
Rendered just after the
embedded_csscontainer
-
scripts¶ A
Scriptscontainer.Rendered just after the
embedded_jscontainer. To add new javascript files simply use theappend()method on this attribute. You can add relative paths:html.head.scripts.append('/media/js/scripts.js')
as well as absolute paths:
html.head.scripts.append( 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js')
-
get_meta(name, meta_key=None)[source]¶ Get the
contentattribute of a meta tagname.For example:
head.get_meta('decription')
returns the
contentattribute of the meta tag with attributenameequal todescriptionorNone. If a different meta key needs to be matched, it can be specified via themeta_keyparameter:head.get_meta('og:title', meta_key='property')
-
Media¶
-
class
pulsar.apps.wsgi.content.Media(media_path, minified=False, asset_protocol=None)[source]¶ A container for both
LinksandScripts.-
media_path¶ The base url path to the local media files, for example
/media/. Must include both slashes.
-
minified¶ Optional flag indicating if relative media files should be modified to end with
.min.jsor.min.cssrather than.jsor.cssrespectively.Default:
False
-
absolute_path(path, minify=True)[source]¶ Return a suitable absolute url for
path.If
pathis_relative()build a suitable url by prepending themedia_pathattribute.Returns: A url path to insert in a HTML linkorscript.
-
Scripts¶
-
class
pulsar.apps.wsgi.content.Scripts(*args, **kwargs)[source]¶ A
Mediacontainer forscripttags.Supports javascript Asynchronous Module Definition
-
insert(index, child, **kwargs)[source]¶ add a new script to the container.
Parameters: child – a stringrepresenting an absolute path to the script or relative path (does not start withhttpor/), in which case theMedia.media_pathattribute is prepended.
-
Links¶
-
class
pulsar.apps.wsgi.content.Links(media_path, minified=False, asset_protocol=None)[source]¶ A
Mediacontainer forlinktags.The
<link>tag defines the relationship between aHtmlDocumentand an external resource. It is most used to link to style sheets.-
insert(index, child, rel=None, type=None, media=None, condition=None, **kwargs)[source]¶ Append a link to this container.
Parameters: - child – a string indicating the location of the linked document
- rel – Specifies the relationship between the document
and the linked document. If not given
stylesheetis used. - type – Specifies the content type of the linked document.
If not given
text/cssis used. It an empty string is given, it won’t be added. - media – Specifies on what device the linked document will be
displayed. If not given or
all, the media is for all devices. - kwargs – additional attributes
-