'Returns the given value as a string (used to cast handler functions).
If the value is a dictionary, returns a JSON-string.
If the value is a generator, starts a stream.
If the value is an iterable, joins the values with a space.'

def _cast(self, v):

    if isinstance(v, basestring):
        return v
    if isinstance(v, cp.lib.file_generator):
        return v
    if isinstance(v, dict):
        cp.response.headers['Content-Type'] = 'application/json;    charset=utf-8'
        return json.dumps(v)
    if isinstance(v, types.GeneratorType):
        cp.response.stream = True
        return iter((self._cast(v) for v in v))
    if isinstance(v, (list, tuple, set)):
        return '    '.join((self._cast(v) for v in v))
    if isinstance(v, HTTPError):
        raise cp.HTTPError(v.status, message=v.message)
    if (v is None):
        return ''
    try:
        return unicode(v)
    except:
        return encode_entities(repr(v))
