Web Components

This chapter will provide api documentation of the web components of the KalaPy framework.

Request

class kalapy.web.Request(environ, populate_request=True, shallow=False)

The request object, remembers the matched endpoint, view arguments and current package.

See also

werkzeug.Request

endpoint

The endpoint that matched the request. If an exception happend during url match, this will be None.

package

The name of the current package.

routing_exception

The exception raised during url matching else None. This is usually a NotFound or similar.

view_args

A dict of arguments that matched the request. If an exception happend during url match, this will be None.

view_func

The view function referenced by the endpoint.

Response

class kalapy.web.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)

The response object that is used by default, with default mimetype set to ‘text/html’.

See also

werkzeug.Response

Application

class kalapy.web.Application

The Application class implements a WSGI application. This class is responsible to request dispatching, middleware processing, generating proper response from the view function return values etc.

debug

If application is runing in debug mode.

dispatch(environ, start_response)

The actual wsgi application. This is not implemented in __call__ so that wsgi middlewares can be applied without losing a reference to the class.

get_response(request)

Returns an Response instance for the given request object.

jinja_env

The jinja2 environment

make_response(value)

Converts the given value into a real response object that is an instance of Response.

Parameters:value – the value to be converted
middlewares

List of all the registered middlewares (settings.MIDDLEWARE_CLASSES)

process_exception(request, exception)

This method will be called if there is any unhandled exception occurs during request handling. In turn, this method will call all the registered middleware’s respective process_exception methods.

process_request(request)

This method will be called before actual request dispatching and will call all the registered middleware’s respective process_request methods. If any of these methods returns any values, it is considered as if it was the return value of the view function and further request handling will be stopped.

process_response(request, response)

This method will be called after response is successfully created and will call all the registered middleware’s respective process_response methods.

request_context(environ)

Create request context from the given environ. This must be used with the with statement as the context is bould to the current context.

For example:

with app.request_context():
    do_something_with(request)
Parameters:environ – the wsgi environment to be used to create request.

Middleware

class kalapy.web.Middleware

Application middleware objects (don’t confuse with WSGI middleware). This is more similar to Django’s middleware. It allows to hook into application’s request/response cycle. It’s a ligh, low-level ‘plugin’ system for globally alter the the application input/output.

It defines following interface methods, which derived middleware classes should override.

process_request

this method will be called before request starts.

process_response

this method will be called after request is finished and response is successfully generated.

process_exception

this method will be called when any exception occurred during request/ response cycle.

For more information on middleware, see...

process_exception(request, exception)

This method will be called if any exception occurs during request/ response cycle.

process_request(request)

This method will be called before request starts.

process_response(request, response)

This method will be called after response is successfully generated.

Package

class kalapy.web.Package(import_name)

Container object that represents an installed package.

A package can be enabled/disabled from settings.INSTALLED_PACKAGES. This class is intended for internal use only.

For more information on packages, see...

Parameters:
  • name – name of the package
  • path – directory path where package is located
add_rule(rule, endpoint, func=None, **options)

Add URL rule with the specified rule string, endpoint, view function and options.

Function must be provided if endpoint is None. In that case endpoint will be automatically generated from the function name. Also, the endpoint will be prefixed with current package name.

Other options are similar to werkzeug.routing.Rule constructor.

package

The parent package this package is extending otherwise the self.

route(rule, **options)

Same as route()

submount

Submount for the package. If this is an addon package then it is the same as the extending package.

Routing

kalapy.web.route(rule, **options)

A decorator to register a view function for a given URL rule.

Example:

@web.route('/<path:page>')
def index(page):
    ...

@web.route('/<path:page>', methods=('POST',))
def save(page):
    ...

@web.route('/<path:page>/edit')
def edit(page):
    ...

For more information, see...

Parameters:
  • rule – the URL rule as string
  • methods – a list of http methods this rule is limited to like ('GET', 'POST', etc). By default a rule is limited to 'GET' (and implicitly 'HEAD').
  • options – other options to be forwarded to the underlying werkzeug.routing.Rule object.
kalapy.web.url_for(endpoint, **values)

Generate a URL for the given endpoint with the method provided. The endpoint is a name of the view function in the current package defined in the views module. If you want to refer an endpoint from another package, prefix it with package name like "package:view_func". If your view functions are organized in submodules other then in the views module, the endpoint name should be in "module.view_func" format. The endpoint prefixed with a . will be resolved against current module.

Here are few examples:

Active Package Target Endpoint Target Function
blog 'index' blog.views.index
blog 'page.index' blog.views.page.index
blog '.edit' blog.views.page.edit
wiki 'index' wiki.views.index
blog 'wiki:index' wiki.views.index
any 'wiki:index' wiki.views.index
any 'blog:index' blog.views.index
any 'blog:page.index' blog.views.page.index

Where blog.views.index is defined in blogs/views/__init__.py and blog.views.page.index is defined in blogs/views/page.py and so on.

Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments.

This function can also be used to generate URL for static contents in templates. In that case, if you want to refer global static dir then just prefix the endpoint with ‘:’ like :static.

Here are few examples:

Active Package Target Endpoint Target Static Dir
blog 'static' /blog/static
wiki 'static' /wiki/static
any ':static' /static
any 'blog:static' /blog/static

For more information, see...

Parameters:
  • endpoint – the endpoint for the URL
  • values – the variable arguments for the URL
  • _external – if set to True, an absolute URL will be generated.
Returns:

generate URL string

Raises :

BuildError

kalapy.web.redirect(location, code=302)

Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.

New in version 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function.

Parameters:
  • location – the location the response should redirect to.
  • code – the redirect status code.
kalapy.web.locate(endpoint, **values)

Similar to werkzeug.redirect but uses url_for to generate target location from the url rules.

Parameters:
  • endpoint – the endpoint for the URL
  • values – the variable arguments for the URL
  • _external – if set to True, an absolute URL will be generated.
  • _code – http status code, default 302

Templates

This module provides render_template() function that can be used to render jinja2 templates. It also provides special version of gettext and ngettext implementation to allow rst style syntax to apply jinja2 macro to the strings.

For example, we want to translate following template:

Click <a href="{{ url_for('some.endpoint') }}">here</a> for more information.

As the embedded url markup is dynamically generated, it is hard to translate the entire sentence. Also, translating the sentence into pieces might result in wrong translation in some languages. This can be solved like:

{% macro here_link(val) %}
    <a href="{{ url_for('some.endpoint') }}">{{ val }}</a>
{% endmacro %}

{{ _('Click :here_link:`here` for more information.', here_link=here_link)|safe }}

You can see, rst like construct has been embedded into the string. Now, the translator can correctly translate the sentence without loosing the context.

The gettext function _() will then apply the macro to the translated string resulting correct translation.

kalapy.web.templating.render_template(template, **context)

Render the template of the current package with the given context.

The template loader will try to load the template from the templates folder of the current package. If there are any addon packages activated for the current package, the loader will give prefences to the templates provided with the addon packages.

Parameters:
  • template – the name of the template to be rendered.
  • context – the variables that should be available in the context of the template.
Returns:

string generated after rendering the template

Raises :

TemplateNotFound or any other exceptions thrown during rendering process

Request Context

kalapy.web.request

The request instance of the current request context.

Other Useful Functions & Classes

kalapy.web.jsonify(*args, **kw)

Creates a Response with JSON representation of the given data provided from the arguments with an application/json mimetype. The arguments to this function are same as dict constructor.

Example:

@web.route('/user/info')
def get_user():
    return jsonify(name="somename", active=True, key=34)

This will send a JSON response to the client like this:

{
    'name': 'somename',
    'active': true,
    'key': 34
}
Returns:an instance of Response
kalapy.web.json()

The standard simplejson.json() function exposed for convenience.

kalapy.web.abort(mapping=None, extra=None)

When passed a dict of code -> exception items it can be used as callable that raises exceptions. If the first argument to the callable is an integer it will be looked up in the mapping, if it’s a WSGI application it will be raised in a proxy exception.

The rest of the arguments are forwarded to the exception constructor.

class kalapy.web.HTTPException(description=None)

Baseclass for all HTTP exceptions. This exception can be called as WSGI application to render a default error page or you can catch the subclasses of it independently and render nicer error messages.

class kalapy.web.NotFound(description=None)

404 Not Found

Raise if a resource does not exist and never existed.

class kalapy.web.SecureCookie(data=None, secret_key=None, new=True)

Represents a secure cookie. You can subclass this class and provide an alternative mac method. The import thing is that the mac method is a function with a similar interface to the hashlib. Required methods are update() and digest().

Example usage:

>>> x = SecureCookie({"foo": 42, "baz": (1, 2, 3)}, "deadbeef")
>>> x["foo"]
42
>>> x["baz"]
(1, 2, 3)
>>> x["blafasel"] = 23
>>> x.should_save
True
Parameters:
  • data – the initial data. Either a dict, list of tuples or None.
  • secret_key – the secret key. If not set None or not specified it has to be set before serialize() is called.
  • new – The initial value of the new flag.

See SecureCookie for more information.

Table Of Contents

Previous topic

Database Abstraction Layer

Next topic

Internationalization and Localization

This Page