API Reference

API documentation for the Django Bricks module.

Components

Helper functions

Helper functions generate safe HTML code fragments for several useful situations.

Rendering

bricks.helpers.render(obj, request=None, **kwargs)[source]

Renders object as a safe HTML string.

This function uses single dispatch to make it extensible for user defined types:

@render.register(int)
def _(x, **kwargs):
    if x == 42:
        return safe('the answer')
    else:
        return safe(x)

A very common pattern is to render object from a template. This has specific support:

render.register_template(UserProfile, 'myapp/user_profile.jinja2')

By default, it populates the context dictionary with a snake_case version of the class name, in this case, {'user_profile': x}. The user may pass a context keyword argument to include additional context data.

If you want to personalize how this is done, it is possible to use register_template to register a context factory function. The function should receive the object, a request and kwargs:

@render.register_template(UserProfile, 'myapp/user_profile.jinja2')
def context(profile, request=None, context=None, **kwargs):
    context = context or {}
    context.update(kwargs, request=request, profile=profile)
    return context

Notes

All implementations must receive the user-defined object as first argument and accept arbitrary keyword arguments.

bricks.helpers.render_tag(tag, data=None, attrs=None, children_kwargs=None, request=None, **attrs_kwargs)[source]

Renders HTML tag.

Parameters:
  • tag – Tag name.
  • data – Children elements for the given tag. Each element is rendered with the render_html() function.
  • attrs – A dictionary of attributes.
  • request – A request object that is passed to the render function when it is applied to children.
  • **attr_kwargs – Keyword arguments are converted to additional attributes.

Examples

>>> render_tag('a', 'Click me!', href='www.python.org')
'<a href="www.python.org">Click me!</a>
bricks.helpers.markdown(text, *, output_format='html5', **kwargs)[source]

Renders Markdown content as HTML and return as a safe string.

Escaping

bricks.helpers.safe(x)[source]

Convert string object to a safe Markup instance.

bricks.helpers.escape(s) → markup

Convert the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.

bricks.helpers.escape_silent(s) → markup

Like escape but converts None to an empty string.

bricks.helpers.unescape(s)[source]

Convert all named and numeric character references (e.g. &gt;, &#62;, &x3e;) in the string s to the corresponding unicode characters. This function uses the rules defined by the HTML 5 standard for both valid and invalid character references, and the list of HTML 5 named character references defined in html.entities.html5.

bricks.helpers.sanitize(data, **kwargs)[source]

Sanitize HTML and return as a safe string.

Utilities

bricks.helpers.attr(x, **kwargs)[source]

Renders object as an HTML attribute value.

It define the following dispatch rules:

str:
Quotations and & are escaped, any other content, including <, >, is allowed.
numeric types:
Are simply converted to strings.
lists and mappings:
Are converted to JSON and returned as safe strings. This is used in some modern javascript frameworks reads JSON from tag attributes.
bricks.helpers.attrs(x, **kwargs)[source]

Convert object into a list of key-value HTML attributes.

Parameters:
  • uses multiple dispatch, so the behaviour might differ a little bit (It) –
  • o the first argument. (depending) –
  • mappings – Renders key-values into the corresponding HTML results.
  • sequences – Any non-string sequence is treated as sequence of (key, value) pairs. If any repeated keys are found, it keeps only the last value.
  • protocol (*attrs*) – Any object that define an attrs attribute that can be either a mapping or a sequence of pairs.
  • all cases, attrs takes arbitrary keyword attributes that are (In) –
  • as additional attributes. PyML converts all underscores (interpreted) –
  • in the attribute names to dashes since this is the most common (present) –
  • in HTML. (convention) –

Creates an hyperlink string from object and renders it as an <a> tag.

It implements some common use cases:
str:
Renders string as content inside the <a>...</a> tags. Additional options including href can be passed as keyword arguments. If no href is given, it tries to parse a string of “Value <link>” and uses href=’#’ if no link is found.
dict or mapping:

Most keys are interpreted as attributes. The visible content of the link must be stored in the ‘content’ key:

>>> hyperlink({'href': 'www.python.com', 'content': 'Python'})
<a href="www.python.com">Python</a>
django User:

You must monkey-patch to define get_absolute_url() function. This function uses this result as the href field.

The full name of the user is used as the hyperlink content.

>>> hyperlink(User(first_name='Joe', username='joe123'))
<a href="/users/joe123">Joe</a>

In order to support other types, use the lazy_singledispatch mechanism:

@hyperlink.register(MyFancyType)
def _(x, **kwargs):
    return safe(render_object_as_safe_html(x))

See also

pyml.helpers.attrs(): See this function for an exact explanation
of how keyword arguments are translated into HTML attributes.

Client and JavaScript emulation

Bricks flavored JSON

Serialize/deserialize Bricks flavored JSON (see Bricks flavored JSON).

Functions

bricks.json.encode(data)[source]

Encode some arbitrary Python data into a JSON-compatible structure.

This naive implementation does not handle recursive structures. This might change in the future.

This function encode subclasses of registered types as if they belong to the base class. This is convenient, but is potentially fragile and make the operation non-invertible.

bricks.json.decode(data)[source]

Decode a JSON-like structure into the corresponding Python data.

bricks.json.dumps(obj)[source]

Return a JSON string dump of a Python object.

bricks.json.loads(data)[source]

Load a string of JSON-encoded data and return the corresponding Python object.

bricks.json.register(cls, name=None, encode=None, decode=None)[source]

Register encode/decode pair of functions for the given Python type. Registration extends Bricks flavored JSON to handle arbitrary python objects.

Parameters:
  • cls – python data type
  • name – name associated with the ‘@’ when encoded to JSON.
  • encode – the encode function; convert object to JSON. The resulting JSON can have non-valid JSON types as long as they can be also converted to JSON using the bricks.json.encode() function.
  • decode – decode function; converts JSON back to Python. The decode function might assume that all elements were already converted to their most Pythonic forms (i.e., all dictionaries with an ‘@’ key were already decoded to their Python forms).

See also

Custom types

Errors

class bricks.json.JSONDecodeError[source]

Error raised when decoding a JSON structure to a Python object.

class bricks.json.JSONEncodeError[source]

Error raised when encoding a Python object to JSON.

Remote procedure calls (RPC)

JSON-RPC 2.0 utilities.

Functions and decorators

bricks.rpc.jsonrpc_endpoint(login_required=False, perms_required=None)[source]

Decorator that converts a function into a JSON-RPC enabled view.

After using this decorator, the function is not usable as a regular function anymore.

@jsonrpc_endpoint(login_required=True)
def add_at_server(request, x=1, y=2):
    return x + y

Generic views

class bricks.rpc.RPCView(function, action='api', login_required=False, perms_required=None, request_argument=True, **kwds)[source]

Wraps a Bricks RPC end point into a view.

Parameters:
  • function – (required) The function that implements the given API.
  • login_required – If True, the API will only be available to logged in users.
  • perms_required – The list of permissions a user can use in order gain access to the API. A non-empty list implies login_required.
check_credentials(request)[source]

Assure that user has the correct credentials to the process.

Must raise a BadResponseError if credentials are not valid.

execute(request, data)[source]

Execute the API function and return a dictionary with the results.

get_content_type()[source]

Content type of the resulting message.

For JSON, it returns ‘application/json’.

get_data(request)[source]

Decode and return data sent by the client.

get_raw_response(request, data)[source]

Return the payload that will be sent back to the client.

The default implementation simply converts data to JSON.

post(request, *args, **kwargs)[source]

Process the given request, call handler and return result.

wrap_error(ex, tb=None, wrap_permission_errors=False)[source]

Wraps an exception raised during the execution of an API function.

Routing

Contrib modules