plastic.app — Application factories

plastic.app.DEFAULT_CONFIG = ImmutableDict({'session_store': 'werkzeug.contrib.sessions:FilesystemSessionStore(filename_template="plastic_%s.sess")'})

(collections.Mapping) The default configuration mapping.

class plastic.app.BaseApp(config={})

The application base class. In order to make an application you have to inherit this class. As you know Python’s subclassing can be done like:

from plastic.app import BaseApp

class MyApp(BaseApp):
    pass

However in most cases you don’t have to fill its body but simply clone():

from plastic.app import BaseApp

MyApp = BaseApp.clone()

Use route() class method for routing.

classmethod add_rule(rule, function)

Adds a new rule and maps it to the function. It is a lower-level primitive method. In most cases you don’t need it and just use route() decorator or other higher-level methods.

Parameters:
classmethod add_serializer(mimetype, function)

Registers a function which serializes a value into a string. The funtion has to take two arguments and return its serialized result.

add_serializer.function(request, value)
Parameters:
  • request (Request) – the current request object
  • value – a value to serialize into a string
Returns:

a serialized result

Return type:

basestring

Parameters:
  • mimetype (basestring) – a mimetype to assiciate the function with e.g. 'application/json'
  • function (collections.Callable) – serializer function. see also function() for its signature
classmethod add_template_engine(suffix, function)

Registers a templating function to the given suffix. The function has to take three arguments and return its rendering result:

add_template_engine.function(request, path, values)
Parameters:
  • request (Request) – the current request object
  • path (basestring) – the path of the template file. it can be a key of template_directory mapping object
  • values (collections.Mapping) – the values to be passed to the template
Returns:

the rendering result

Return type:

basestring

Parameters:
  • suffix (basestring) – the filename suffix (without period character) to register the template engine e.g. 'mako'
  • function (collections.Callable) – templating function. see also function() for its signature
classmethod associate_mimetypes(mimetypes={}, **suffixes)

Associates mimetype to suffix. Associations made by this are used by render() function. For example:

from plastic.rendering import render

App.associate_mimetypes({
    'text/plain': 'rst',
    'text/x-rst': 'rst',
    'text/html': 'html'
})

@App.route('/')
def home(request):
    return render(request, None, 'main/home')

with the above setting when you make a request like:

GET / HTTP/1.0
Accept: text/html

will find a template file main/home.html.* (* is suffix for template engine).

Parameters:
  • mimetypes (collections.Mapping) – a mapping object of mimetypes to suffixes e.g. {'text/html': 'txt', 'text/xml': 'xml'}
  • **suffixes – keyword arguments are interpreted as suffixes to mimetypes. for example, passing txt='text/html' is equivalent to passing {'text/html': 'txt'}
classmethod clone(__module__=None, __name__=None, **values)

Subclasses the application class. It is a just shorthand of normal subclassing. If your application becomes bigger stop using this and normaly subclass the application class using class keyword instead.

config = None

(Config) Each application instance’s configuration.

endpoints = {}

(collections.Mapping) The dict of endpoints to view functions.

mimetype_mapping = ImmutableDict({})

(ImmutableDict) The immutable dictionary of mimetype to registered renderers.

render_template(request, path, values={}, **keywords)

Renders the response using registered template_engines.

You have to pass the path without specific suffix. The last suffix will be used for determining what template engine to use. For example, if there is user_profile.html.mako file in the template_path and 'mako' is associated to Mako template engine in template_engines mapping, the following code will find user_profile.html.mako (not user_profile.html) and render it using Mako:

app.render_template(request, 'user_profile.html')

In other words, you have to append a suffix to determine what template engine to use into filenames of templates.

Parameters:
  • request (Request) – a request which make it to render
  • path (basestring) – a path to template files without specific suffix
  • values (collections.Mapping) – a dictionary of values to pass to template
  • **keywords – the same to values except these are passed by keywords
Returns:

a rendered result

Return type:

basestring

Raises plastic.exceptions.RenderError:
 

when there are no matched template files

classmethod route(*rule_args, **rule_kwargs)

The function decorator which maps the path to the decorated view function.

It takes the same arguments to the constructor of werkzeug.routing.Rule class. In most case simply give a path string to route:

@App.route('/people/<name>')
def person(request, name):
    return 'Hi, ' + name
rules = []

(collections.Sequence) The list of routing rules.

run(host='127.0.0.1', port=5555, debug=True, **options)

Starts serving the application.

Parameters:
  • host (basestring) – the hostname to listen. default is '127.0.0.1' (localhost)
  • port (int) – the port number to listen. default is 5555
  • debug (bool) – use debugger and reloader. default is True
  • **options – other options to be passed to werkzeug.routing.run_simple() function
classmethod serializer(mimetypes)

The function decorator which associate the given serializer function with mimetypes.

import json
import plistlib

@App.serializer('application/json')
def serialize_json(request, value):
    return json.dumps(value)

@App.serializer(['application/x-plist', 'text/xml'])
def serialize_plist(request, value):
    return plistlib.writePlistToString(value)
Parameters:mimetypes (basestring, collections.Iterable) – one or more mimetypes to assiciate the function with. it can be either a single string or multiple strings in an iterable e.g. 'application/json', ['application/xml', 'text/xml']

(collections.Mapping) The mapping of cookie settings sessions will use. It has the following configuable keys:

  • 'key' (basestring)
  • 'max_age' (numbers.Integral)
  • 'domain' (basestring)
  • 'path' (basestring)
  • 'secure' (bool)
  • 'httponly' (bool)

See also

Method werkzeug.wrappers.BaseResponse.set_cookie()
Sets a cookie.
session_store

(werkzeug.contrib.sessions.SessionStore) The session store instance an application uses. It’s a proxy to 'session_store' value of config.

template_directory

(ResourceDirectory) The mapping object of the template directory.

classmethod template_engine(suffix)

The function decorator which makes the given function the template engine of the suffix.

# The following example has several issues.  Do not C&P
# it into your program to use Mako.
from mako.template import Template

@App.template_engine(suffix='mako')
def render_mako(request, path, values):
    with request.app.template_directory[path] as f:
        template = Template(f.read())
    return template.render(**values)
Parameters:suffix (basestring) – the filename suffix (without period character) to register the template engine e.g. 'mako'
template_engines = ImmutableDict({})

(ImmutableDict) The immutable dictionary of suffix to registered templating functions.

template_path = 'templates/'

(basestring) The path to the directory which contains template files. It has to be relative to the application module. It can be overridden. Default is templates/.

wsgi_app(environ, start_response)

The actual WSGI function. Replace it when the application should be wrapped by middlewares.

app.wsgi_app = Middleware(app.wsgi_app)

Project Versions

Previous topic

plastic — Plastic

Next topic

plastic.message — Request/response messages

This Page