def context_creator(f):
def authenticator(f): class BaseArgument(BaseField):
    """The base class for Pale Arguments.

    Arguments in this context are values passed in to Pale Endpoints from the
    HTTP layer.  These Argument objects are expected to validate parameters
    received from the HTTP layer before they're propagated to the endpoint
    handler that you define in your API.

    The `validate` method in subclasses should return the value if it is
    valid (including returning None if None is a valid value), or raise an
    ArgumentError if the argument is invalid.

    The ArgumentError will generate an HTTP 422 Unprocessable Entity response,
    and propagate the message of the exception to the caller.
    """
    allowed_types = (object,)

    def __init__(self,
            short_doc,
            default=None,
            required=False,
            **kwargs):
        """Initialize an argument.

        This method is usually called from the Endpoint definition, and the
        created object is typically assigned to a key in the endpoint's
        `arguments` dictionary.
        """
        self.description = short_doc
        self.default = default
        self.required = required
        for k, v in kwargs.iteritems():
            setattr(self, k, v)


    def validate(self, item, item_name):
        """Validate the passed in item.

        The `item_name` is passed in so that we can generate a human-readable
        and user friendly error message, but this is architecturally a bit
        cumbersome right now, so we may want to change it in the future.

        Subclasses of BaseArgument should implement their own validation
        function.
        """
        raise ArgumentError(item_name,
                ("ERROR! Your endpoint is missing a parser for your argument. "
                 "The argument validator bubbled all the way up to the base "
                 "argument, which is definitely not what you want!"))


    def _validate_type(self, item, name):
        """Validate the item against `allowed_types`."""
        if item is None:
            # don't validate None items, since they'll be caught by the portion
            # of the validator responsible for handling `required`ness
            return

        if not isinstance(item, self.allowed_types):
            item_class_name = item.__class__.__name__
            raise ArgumentError(name,
                "Expected one of %s, but got `%s`" % (
                    self.allowed_types, item_class_name))


    def _validate_required(self, item, name):
        """Validate that the item is present if it's required."""
        if self.required is True and item is None:
            raise ArgumentError(name, "This argument is required.")


    def doc_dict(self):
        """Returns the documentation dictionary for this argument."""
        doc = {
            'type': self.__class__.__name__,
            'description': self.description,
            'default': self.default,
            'required': self.required
        }
        if hasattr(self, 'details'):
            doc['detailed_description'] = self.details
        return doc class ListField(BaseField):
    """A Field that contains a list of Fields."""

    value_type = 'list'

    def __init__(self, description, item_type=BaseField, **kwargs):
        super(ListField, self).__init__(
                self.value_type,
                description,
                **kwargs)

        # Item type initialization
        self.item_type = item_type
        kd = {'description':'nested_list'}
        if item_type is BaseField:
            kd['value_type'] = 'base_field'
        self.item_type_instance = self.item_type(
            **kd
            )


    def doc_dict(self):
        doc = super(ListField, self).doc_dict()
        doc['item_type'] = self.item_type.value_type
        return doc

    def render(self, obj, name, context):
        if obj is None:
            return []

        output = []

        # again, the base renderer basically just calls getattr.
        # We're expecting the attr to be a list, though.
        lst = super(ListField, self).render(obj, name, context)
        if lst is None:
            return []

        # attempt to wrap any non-iterable in to a list of iterables.
        if not isinstance(lst, Iterable):
            lst = [lst]

        renderer = self.item_type_instance.render
        for res in lst:
            item = renderer(StaticItem(res), 'obj', context)
            output.append(item)
        return output class ResourceField(BaseField):
    """A field that contains a nested resource"""

    value_type = 'resource'


    def __init__(self,
            description,
            resource_type=Resource,
            subfields=None,
            **kwargs):
        super(ResourceField, self).__init__(
                self.value_type,
                description,
                **kwargs)
        self.resource_type = resource_type

        if subfields is None:
            subfields = resource_type._default_fields
        self.subfields = subfields

        self.resource_instance = self.resource_type(
                'nested_resource',
                fields=self.subfields)


    def doc_dict(self):
        doc = super(ResourceField, self).doc_dict()
        doc['resource_type'] = self.resource_type._value_type
        if self.subfields is None:
            logging.warn("paledoc: `subfields` on ResourceField %s is None",
                self.__class__.__name__)
        doc['default_fields'] = list(self.subfields or [])
        return doc


    def render(self, obj, name, context):
        if obj is None:
            return None
        # the base renderer basically just calls getattr, so it will
        # return the resource here
        resource = super(ResourceField, self).render(obj, name, context)
        renderer = self.resource_instance._render_serializable
        output = renderer(resource, context)
        return output class ResourceListField(BaseField):
    """A Field that contains a list of Fields."""
    item_type = ResourceField
    value_type = 'resource_list'

    def __init__(self,
            description,
            resource_type=Resource,
            subfields=None,
            **kwargs):
        super(ResourceListField, self).__init__(
                self.value_type,
                description=description,
                **kwargs)

        self.resource_type = resource_type

        if subfields is None:
            subfields = resource_type._default_fields
        self.subfields = subfields

        self.resource_instance = self.resource_type(
                'nested_resource',
                fields=self.subfields)


    def doc_dict(self):
        doc = super(ResourceListField, self).doc_dict()
        doc['resource_type'] = self.resource_type._value_type
        return doc


    def render(self, obj, name, context):
        if obj is None:
            return None

        output = []
        # again, the base renderer basically just calls getattr.
        # We're expecting the attr to be a list, though.
        resources = super(ResourceListField, self).render(obj, name, context)
        renderer = self.resource_instance._render_serializable
        for res in resources:
            item = renderer(res, context)
            output.append(item)
        return output class APIError(BasePaleError):
    @classmethod
    def Forbidden(cls, message="You don't have permission to do that."):
        err = cls(message)
        err.http_status_code = 403
        return err

    @classmethod
    def NotFound(cls, message):
        err = cls(message)
        err.http_status_code = 404
        return err

    @classmethod
    def UnprocessableEntity(cls, message):
        err = cls(message)
        err.http_status_code = 422
        return err

    @classmethod
    def UnsupportedMedia(cls, message):
        err = cls(message)
        err.http_status_code = 415
        return err

    @classmethod
    def BadRequest(cls, message):
        err = cls(message)
        err.http_status_code = 400
        return err

    @classmethod
    def Exception(cls, message):
        err = cls(message)
        err.http_status_code = 500
        return err class ArgumentError(BasePaleError):
    def __init__(self, arg_name, message):
        error_msg = ("Invalid argument: `%s`.  %s"
                % (arg_name, message))
        self.arg_name = arg_name
        super(ArgumentError, self).__init__(error_msg) class AuthenticationError(BasePaleError):
    pass class MetaHasFields(type):
    """Metaclass for classes that support named field definitions.

    In Pale, this is particularly Endpoint and Resource.  This metaclass is
    here to populate the developer-specified fields on the class so that
    simple API definition like the following is possible:

        class MyEndpoint(Endpoint):
            _method = 'GET'
            _uri = '/hello'

            name = StringArgument(
                description="Who should we say Hello to?",
                default="World")

            _returns = RawStringResource("A 'Hello, world' string")

            def _handle(self, context):
              return "Hello, %s" % context.args.name

    In the above case, this metaclass allows us to create a `_arguments` map
    that would store {"name": MyEndpoint.name}.
    """

    def __init__(cls, name, bases, classdict):
        super(MetaHasFields, cls).__init__(name, bases, classdict)
        cls._fix_up_fields() class NoContentResource(Resource):
    """An empty resource to represent endpoints that return No-Content."""
    _description = "The shell of a Resource where content used to be"

    def _render_serializable(self, obj, context):
        return None class Resource(object):
    __metaclass__ = MetaHasFields

    _value_type = "Base Resource"

    _default_fields = None

    @classmethod
    def _all_fields(cls):
        return tuple(cls._fields.keys())

    @classmethod
    def _fix_up_fields(cls):
        """Add names to all of the Resource fields.

        This method will get called on class declaration because of
        Resource's metaclass.  The functionality is based on Google's NDB
        implementation.

        `Endpoint` does something similar for `arguments`.
        """
        cls._fields = {}
        if cls.__module__ == __name__ and cls.__name__ != 'DebugResource':
            return
        for name in set(dir(cls)):
            attr = getattr(cls, name, None)
            if isinstance(attr, BaseField):
                if name.startswith('_'):
                    raise TypeError("Resource field %s cannot begin with an "
                            "underscore.  Underscore attributes are reserved "
                            "for instance variables that aren't intended to "
                            "propagate out to the HTTP caller." % name)
                attr._fix_up(cls, name)
                cls._fields[attr.name] = attr
        if cls._default_fields is None:
            cls._default_fields = tuple(cls._fields.keys())


    def __init__(self, doc_string=None, fields=None):
        """Initialize the resource with the provided doc string and fields.

        In general, the doc string should never be none for individual
        resources, but may be none when the resource class is included as a
        part of a ResourceList or ResourceDict.
        """
        self._description = doc_string
        if fields is not None:
            self._fields_to_render = fields
        else:
            self._fields_to_render = self._default_fields


    def _render_serializable(self, obj, context):
        """Renders a JSON-serializable version of the object passed in.
        Usually this means turning a Python object into a dict, but sometimes
        it might make sense to render a list, or a string, or a tuple.

        In this base class, we provide a default implementation that assumes
        some things about your application architecture, namely, that your
        models specified in `underlying_model` have properties with the same
        name as all of the `_fields` that you've specified on a
        resource, and that all of those fields are public.

        Obviously this may not be appropriate for your app, so your
        subclass(es) of Resource should implement this method to serialize
        your things in the way that works for you.

        Do what you need to do.  The world is your oyster.
        """
        logging.info("""Careful, you're calling ._render_serializable on the
        base resource, which is probably not what you actually want to be
        doing!""")
        if obj is None:
            logging.debug(
                    "_render_serializable passed a None obj, returning None")
            return None
        output = {}
        if self._fields_to_render is None:
            return output
        for field in self._fields_to_render:
            renderer = self._fields[field].render
            output[field] = renderer(obj, field, context)
        return output class DebugResource(Resource):
    """A schema-less resource to help with debugging.

    This is one of the most dangerous Pale resource types, because it affords
    you the opportunity to _not define your resource_.  You should only use
    this when you're trying to define your resource fields, or on endpoints
    that you might not need to keep for the long term.
    """

    def _render_serializable(self, obj, context):
        return obj class PaleRaisedResponse(PaleBaseResponse, Exception):
    pass
import datetime
import json
import logging
import sys
import threading
import arrow
from pale import config as pale_config
from pale.arguments import BaseArgument
from pale.fields import ResourceField, ListField, ResourceListField
from pale.errors import APIError, ArgumentError, AuthenticationError
from pale.meta import MetaHasFields
from pale.resource import NoContentResource, Resource, DebugResource
from pale.response import PaleRaisedResponse
        updated_cache_ctrl_from_endpoint = False
        if len(response_init_tuple) > 2:
            # headers is the 3rd arg for both flask and webapp2
            headers = response_init_tuple[2]
            cache_ctrl = headers.get('Cache-Control')
            if cache_ctrl is not None:
                context.response.headers['Cache-Control'] = cache_ctrl
                updated_cache_ctrl_from_endpoint = True

        if not updated_cache_ctrl_from_endpoint:
            context.response.headers['Cache-Control'] = \
                    self._default_cache

        # Add default json response type.
        if len(json_content):
            context.response.headers["Content-Type"] = 'application/json'
        else:
            del context.response.content_type
            del context.response.content_length
            status_code = getattr(context.response, "status_int", None) or context.response.status_code
            if status_code == 200: # 200 OK
                context.response.status = '204 No Content'

class ResourcePatch(object):
    """Represents a resource patch which is to be applied
    to a given dictionary or object."""

    def __init__(self, patch, resource, ignore_missing_fields=False):
        self.patch = patch
        self.resource = resource
        self.ignore_missing_fields = ignore_missing_fields

    def get_field_from_resource(self, field):
        if isinstance(self.resource, DebugResource):
            # no fields defined in a DebugResource
            return None

        try:
            return self.resource._fields[field]
        except KeyError:
            if not self.ignore_missing_fields:
                raise APIError.BadRequest(
                    "Field '%s' is not expected." % field)

            return None

    def get_resource_from_field(self, field):
        assert isinstance(field, ResourceField)
        return field.resource_type()

    def cast_value(self, field, value):
        if isinstance(field, ResourceListField):
            if not isinstance(value, dict):
                raise APIError.BadRequest(
                    "Expected nested object in list for %s" % field)
            try:
                resource = field.resource_type()
                if isinstance(resource, DebugResource):
                    return value.copy()
                new_object = dict()
                for k,v in value.iteritems():
                    if not k in resource._fields and self.ignore_missing_fields:
                        new_object[k] = v
                        continue
                    _field = resource._fields[k]
                    if _field.property_name is not None:
                        k = _field.property_name
                    new_object[k] = self.cast_value(_field, v)

                if not getattr(resource, "_underlying_model", None):
                    return new_object

                return resource._underlying_model(**new_object)
            except Exception:
                logging.exception(
                    "Failed to cast value to _underlying_model of resource_type: %s" %
                    getattr(field, 'resource_type', None))
                raise

        # TODO: Use field to cast field back into a value,
        # if possible.
        return value

    def apply_to_dict(self, dt):
        for k,v in self.patch.iteritems():
            field = self.get_field_from_resource(k)
            if field is None:
                dt[k] = v
                continue
            elif isinstance(v, dict):
                # Recursive application.
                resource = self.get_resource_from_field(field)
                patch = ResourcePatch(v, resource,
                    ignore_missing_fields=self.ignore_missing_fields)
                patch.apply_to_dict(dt[k])
            elif isinstance(v, list):
                if (not isinstance(field, ResourceListField) and
                        not isinstance(field, ListField)):
                    raise APIError.BadRequest(
                        "List not expected for field '%s'" % k)
                new_list = []
                for itm in v:
                    new_list.append(self.cast_value(field, itm))
                dt[k] = new_list
            else:
                # Cast value and store
                dt[k] = self.cast_value(field, v)

    def apply_to_model(self, dt):
        for k,v in self.patch.iteritems():
            field = self.get_field_from_resource(k)
            if field is None:
                setattr(dt, k, v)
            elif isinstance(v, dict):
                # Recursive application.
                resource = self.get_resource_from_field(field)
                patch = ResourcePatch(v, resource,
                    ignore_missing_fields=self.ignore_missing_fields)
                patch.apply_to_model(getattr(dt, k, None))
            elif isinstance(v, list):

                if (not isinstance(field, ResourceListField) and